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>svk2000/MovieRental_StrategyPattern<file_sep>/src/main/java/edu/utd/movierental/MovieRentalApplication.java
package edu.utd.movierental;
import edu.utd.movierental.models.*;
import edu.utd.movierental.utils.RentalType;
import javax.xml.bind.*;
public class MovieRentalApplication {
public static void main(String[] args) throws JAXBException {
// Test Case - 1
Customer customer = new Customer("<NAME>", 25);
Transaction transaction = new Transaction(customer);
customer.addRental(new Rental(new Movie("Toy Story"), 1, RentalType.CHILDREN_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Star Wars"), 3, RentalType.NEW_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Mission Impossible"), 4, RentalType.REGULAR_MOVIE_RENTAL));
transaction.processTransaction();
System.out.println("Scenario 1: Testing Doubling Rental Points when customer rented more than two different categories ");
System.out.println(transaction.printTransactionAsXML());
// Test Case - 2
customer = new Customer("Zack", 20);
transaction = new Transaction(customer);
customer.addRental(new Rental(new Movie("Toy Story"), 1, RentalType.CHILDREN_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Star Wars"), 3, RentalType.NEW_MOVIE_RENTAL));
transaction.processTransaction();
System.out.println("Scenario 2:Testing Doubling Rental Points for first Rental when customer age is between 18-22 & Renting at least one new release movie ");
System.out.println(transaction.printTransactionAsXML());
// Test Case - 3
customer = new Customer("Tom", 21);
transaction = new Transaction(customer);
customer.addRental(new Rental(new Movie("Toy Story"), 1, RentalType.CHILDREN_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Star Wars"), 3, RentalType.NEW_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Mission Impossible"), 4, RentalType.REGULAR_MOVIE_RENTAL));
transaction.processTransaction();
System.out.println("Scenario 3:(Scenario 1) & (Scenario 2)");
System.out.println(transaction.printTransactionAsXML());
// Test Case - 4
customer = new Customer("Tom", 21);
transaction = new Transaction(customer);
customer.addRental(new Rental(new Movie("Toy Story"), 1, RentalType.CHILDREN_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Frozen"), 1, RentalType.CHILDREN_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Star Wars"), 3, RentalType.NEW_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Avengers"), 1, RentalType.NEW_MOVIE_RENTAL));
customer.addRental(new Rental(new Movie("Mission Impossible"), 4, RentalType.REGULAR_MOVIE_RENTAL));
transaction.processTransaction();
System.out.println("Scenario 4: (Scenario 1) & (Scenario 2) & Testing Free rental when there are 10 or more frequent renter points");
System.out.println(transaction.printTransactionAsXML());
}
}<file_sep>/src/main/java/edu/utd/movierental/factory/RentalPricingStrategyFactory.java
package edu.utd.movierental.factory;
import edu.utd.movierental.models.Rental;
import edu.utd.movierental.strategy.pricing.ChildrenMovieRentalPricingStrategy;
import edu.utd.movierental.strategy.pricing.NewMovieRentalPricingStrategy;
import edu.utd.movierental.strategy.pricing.RegularMovieRentalPricingStrategy;
import edu.utd.movierental.strategy.pricing.RentalPricingStrategy;
import edu.utd.movierental.strategy.rentalpoints.DefaultFrequentRentalPointsStrategy;
import edu.utd.movierental.strategy.rentalpoints.FrequentRentalPointsStrategy;
import edu.utd.movierental.strategy.rentalpoints.NewReleaseFrequentRentalPointsStrategy;
public class RentalPricingStrategyFactory {
public static RentalPricingStrategy getStrategy(Rental rental){
RentalPricingStrategy rentalPricingStrategy = null;
switch (rental.getRentalType()) {
case REGULAR_MOVIE_RENTAL:
rentalPricingStrategy = RegularMovieRentalPricingStrategy.getInstance();
break;
case CHILDREN_MOVIE_RENTAL:
rentalPricingStrategy = ChildrenMovieRentalPricingStrategy.getInstance();
break;
case NEW_MOVIE_RENTAL:
rentalPricingStrategy = NewMovieRentalPricingStrategy.getInstance();
break;
default:
rentalPricingStrategy = RegularMovieRentalPricingStrategy.getInstance();
break;
}
return rentalPricingStrategy;
}
}
<file_sep>/src/main/java/edu/utd/movierental/strategy/rentalpoints/NewReleaseFrequentRentalPointsStrategy.java
package edu.utd.movierental.strategy.rentalpoints;
import edu.utd.movierental.models.Customer;
import edu.utd.movierental.models.Rental;
public class NewReleaseFrequentRentalPointsStrategy implements FrequentRentalPointsStrategy {
private static NewReleaseFrequentRentalPointsStrategy newReleaseFrequentRentalPointsStrategy = null;
private NewReleaseFrequentRentalPointsStrategy()
{ }
public static NewReleaseFrequentRentalPointsStrategy getInstance()
{
if (newReleaseFrequentRentalPointsStrategy == null)
newReleaseFrequentRentalPointsStrategy = new NewReleaseFrequentRentalPointsStrategy();
return newReleaseFrequentRentalPointsStrategy;
}
@Override
public int computeRentalPoints(int frequentRenterPoints, Rental rental){
if(rental.getDaysRented() > 1) {
++frequentRenterPoints ;
}
return ++frequentRenterPoints;
}
}
<file_sep>/src/main/java/edu/utd/movierental/utils/RentalType.java
package edu.utd.movierental.utils;
public enum RentalType {
REGULAR_MOVIE_RENTAL,
CHILDREN_MOVIE_RENTAL,
NEW_MOVIE_RENTAL;
}
<file_sep>/README.md
# MovieRental_StrategyPattern
DESIGN
We have created below three strategies for Movie Rental Project
§ Rental Pricing Strategy:
We have created this strategy to calculate rental pricing based on the rental
category (Regular Vs New Vs Children). Following are the classes to compute pricing
§ Rental Frequent Renter Points Strategy:
We have created this strategy to calculate frequent renter point based on the
rental category (Regular Vs New Vs Children) and based on the conditions mentioned below. Following are the classes to compute rental points
Þ DefaultFrequentRentalPointsStrategy: For Regular & Children rental categories
Þ NewReleaseFrequentRentalPointsStrategy: For New Release Rental Category
Þ DoubleRegularRentalPointsStrategy: This strategy is for doubling renter points for below conditions
o The first new frequent rental point computation gives double regular points to any customer who is renting more than two types of categories
o The first new frequent rental point computation gives double regular points to any customer who is 18-22 and renting one or multiple new release movies.
§ Transaction Pricing Strategy:
We have created this strategy to apply promotions at the transaction level and calculate price accordingly.
• PATTERNS IMPLEMENTED
We have implemented following patterns in this project
§ Factory pattern: This factory is implemented in below classes to provide
list of strategies to perform in Rental & Transaction classes
Þ FrequentRentalStrategyFactory: This factory will provide list of strategies during calculation of frequent renter points for a given rental. In few scenarios, we will have multiple strategies based on scenario
(Eg: NewReleaseFrequentRentalPointsStrategy & DoubleRegularRentalPointsStrategy)
2
Þ FrequentRenterPointsTransactionStrategy: This strategy provides free rental if customer has more than 10 frequent renter points in a transaction
§ Singleton pattern: This pattern is implemented in all rental and transaction strategy classes to provide same instance during strategy execution
§ Strategy pattern: This pattern is implemented for calculation of rental price, frequent renter points and transaction amount
§ Composite pattern: We have implemented this pattern to execute multiple strategies during renter point calculation
Eg: Calculating regular rental points on rental along with doubling the renter points based on following conditions
o The first new frequent rental point computation gives double regular points to any customer who is renting more than two types of categories
o The first new frequent rental point computation gives double regular points to any customer who is 18-22 and renting one or multiple new release movies.
• TEST RESULTS Execute command:
java -cp $JAR_PATH edu.utd.movierental.MovieRentalApplication
Scenario 1: Testing Doubling Rental Points when customer rented more than two different categories <Customer>
<Name&Age> <NAME>( Age: 25) </Name&Age> <Rentals>
<Rental>
<Movie> Toy Story </Movie>
<Rental_Category> CHILDREN_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 1 </Days_Rented> <Renter_Points> 3 </Renter_Points> <Rental_Price> 1.5 </Rental_Price>
</Rental> <Rental>
<Movie> Star Wars </Movie>
<Rental_Category> NEW_MOVIE_RENTAL </Rental_Category> <Days_Rented> 3 </Days_Rented>
<Renter_Points> 2 </Renter_Points>
<Rental_Price> 9.0 </Rental_Price>
</Rental> <Rental>
<Movie> Mission Impossible </Movie>
<Rental_Category> REGULAR_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 4 </Days_Rented> <Renter_Points> 1 </Renter_Points> <Rental_Price> 5.0 </Rental_Price>
</Rental> </Rentals>
3
4
<Transaction_Amount> 15.5 </Transaction_Amount> <Frequent_Renter_Points> 6 </Frequent_Renter_Points> </Customer>
Scenario 2: Testing Doubling Rental Points for first Rental when customer age is between 18-22 & Renting at least one new release movie
<Customer>
<Name&Age> Zack( Age: 20) </Name&Age> <Rentals>
<Rental>
<Movie> Toy Story </Movie>
<Rental_Category> CHILDREN_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 1 </Days_Rented> <Renter_Points> 3 </Renter_Points> <Rental_Price> 1.5 </Rental_Price>
</Rental> <Rental>
<Movie> Star Wars </Movie>
<Rental_Category> NEW_MOVIE_RENTAL </Rental_Category> <Days_Rented> 3 </Days_Rented>
<Renter_Points> 2 </Renter_Points>
<Rental_Price> 9.0 </Rental_Price>
</Rental> </Rentals>
<Transaction_Amount> 10.5 </Transaction_Amount> <Frequent_Renter_Points> 5 </Frequent_Renter_Points> </Customer>
Scenario 3: (Scenario 1) & (Scenario 2) <Customer>
<Name&Age> Tom( Age: 21) </Name&Age> <Rentals>
<Rental>
<Movie> Toy Story </Movie>
<Rental_Category> CHILDREN_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 1 </Days_Rented> <Renter_Points> 5 </Renter_Points> <Rental_Price> 1.5 </Rental_Price>
</Rental> <Rental>
<Movie> Star Wars </Movie>
<Rental_Category> NEW_MOVIE_RENTAL </Rental_Category> <Days_Rented> 3 </Days_Rented>
<Renter_Points> 2 </Renter_Points>
5
<Rental_Price> 9.0 </Rental_Price> </Rental>
<Rental>
<Movie> Mission Impossible </Movie> <Rental_Category> REGULAR_MOVIE_RENTAL
</Rental_Category>
<Days_Rented> 4 </Days_Rented>
<Renter_Points> 1 </Renter_Points>
<Rental_Price> 5.0 </Rental_Price> </Rental>
</Rentals>
<Transaction_Amount> 15.5 </Transaction_Amount> <Frequent_Renter_Points> 8 </Frequent_Renter_Points> </Customer>
Scenario 4: (Scenario 1) & (Scenario 2) & Testing Free rental when there are 10 or more frequent renter points
<Customer>
<Name&Age> Tom( Age: 21) </Name&Age> <Rentals>
<Rental>
<Movie> Toy Story </Movie>
<Rental_Category> CHILDREN_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 1 </Days_Rented> <Renter_Points> 5 </Renter_Points> <Rental_Price> 0.0 </Rental_Price>
</Rental> <Rental>
<Movie> Frozen </Movie>
<Rental_Category> CHILDREN_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 1 </Days_Rented> <Renter_Points> 1 </Renter_Points> <Rental_Price> 1.5 </Rental_Price>
</Rental> <Rental>
<Movie> Star Wars </Movie>
<Rental_Category> NEW_MOVIE_RENTAL </Rental_Category> <Days_Rented> 3 </Days_Rented>
<Renter_Points> 2 </Renter_Points>
<Rental_Price> 9.0 </Rental_Price>
</Rental> <Rental>
<Movie> Avengers </Movie>
<Rental_Category> NEW_MOVIE_RENTAL </Rental_Category>
6
<Days_Rented> 1 </Days_Rented> <Renter_Points> 1 </Renter_Points> <Rental_Price> 3.0 </Rental_Price>
</Rental> <Rental>
<Movie> Mission Impossible </Movie>
<Rental_Category> REGULAR_MOVIE_RENTAL </Rental_Category>
<Days_Rented> 4 </Days_Rented> <Renter_Points> 1 </Renter_Points> <Rental_Price> 5.0 </Rental_Price>
</Rental> </Rentals>
<Transaction_Amount> 18.5 </Transaction_Amount> <Frequent_Renter_Points> 10 </Frequent_Renter_Points> </Customer>
| 20ac36906bdfa7d4f776fe32c2b60900cc58f058 | [
"Markdown",
"Java"
] | 5 | Java | svk2000/MovieRental_StrategyPattern | 7f36c461b502a58d9d4599884db7fc68297be948 | 1cca3a29f5527c31e851cd3957e687f886f8f20c |
refs/heads/master | <file_sep>var express = require('express');
var { Apierror } = require('../utils/errorUtils')
var router = express.Router();
const bodyParser = require('body-parser');
const Query = require('../db/Query');
module.exports=function(app){
app.use(bodyParser.json());
app.post('/admin',[validateBody,isEmailExist,signUp])
}
validateBody=function(req,res,next){
if(req.body && req.body.name === '' && req.body.name.trim() == ''){
res.status(400)
res.send("Invlid Nme")
}
next();
}
isEmailExist= async function(req,res,next){
console.log('hello 111');
const condition={
'email':req.body.email
}
const n = await Query.find('user','*',condition);
if(n.length ===0)
next();
else{
res.status(409);
res.send('Error')
}
}
signUp=function(req,res,next){
Query.save('USER',req.body);
res.status(200).end();
}
<file_sep>var express = require('express');
var bodyParser = require('body-parser');
var Query = require('../db/Query');
const jwt = require('jsonwebtoken')
const jwtKey = 'my_secret_key'
const jwtExpirySeconds = 300000
module.exports = function (app) {
app.use(bodyParser.json());
app.get('/login', [validateBody, login]);
}
validateBody = function (req, res, next) {
next();
}
login = async function (req, res, next) {
const condition = {
'email': req.query.email
}
const usernme = req.query.email;
const condtiton2 = {
'password': <PASSWORD>
}
const dt = await Query.find('USER', '*', condition).andWhere(condtiton2);
console.log(dt.length);
if (dt && dt.length !== 0) {
const token = jwt.sign({ usernme }, jwtKey, {
algorithm: 'HS256',
expiresIn: jwtExpirySeconds
})
res.json({'token ': token})
}
else {
console.log("not found")
res.status(404).end();
}
}<file_sep>const knex = require('knex')({
client: 'mysql2',
connection: {
host : 'localhost',
port : '3306',
user : 'root',
password : '<PASSWORD>',
database : 'work'
}
});
class Query {
static save(table , value){
knex(table).insert(value).then(
console.log('USER CREated')
);
}
static find(table,select,condition){
return knex(table).select(select).where(condition);
}
static findll(table,select){
return knex(table).select(select);
}
static count(table,select,condition){
return knex(table).count(select).where(condition);
}
}
module.exports = Query;
<file_sep>var express=require('express');
const Query = require('../db/Query');
var bodyParser = require('body-parser');
const jwt = require('jsonwebtoken')
const jwtKey = 'my_secret_key'
module.exports=function(app){
app.use(bodyParser.json());
app.get('/getstudent',[authorization,validateBody,getstudent]);
}
authorization=function(req,res,next){
const token=req.query.token;
try {
// Parse the JWT string and store the result in `payload`.
// Note that we are passing the key in this method as well. This method will throw an error
// if the token is invalid (if it has expired according to the expiry time we set on sign in),
// or if the signature does not match
payload = jwt.verify(token, jwtKey)
} catch (e) {
console.log(e)
// if the error thrown is because the JWT is unauthorized, return a 401 error
return res.status(401).end()
}
// Finally, return the welcome message to the user, along with their
// username given in the token
next();
}
validateBody=function(req,res,next){
next();
}
getstudent= async function(req,res,next){
const select=['name','email','aadhar','age']
const dt = await Query.findll('student',select)
res.send(dt);
}
// <file_sep>var express = require('express');
var Query = require('../db/Query');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
const jwtKey = 'my_secret_key';
module.exports=function(app){
app.use(bodyParser.json());
app.delete('deletestudent',[authorization,deletestudent]);
}
authorization=function(req,res,next){
const token=req.query.token;
try{
payload=jwt.verify(token,jwtKey);
}
catch(error){
console.log('error while authorization');
return res.status(401).end();
}
}
deletestudent= async function(req,res,next){
Query.delete()
}<file_sep>var express=require('express');
const Query = require('../db/Query');
var router=express.Router();
const jwt=require('jsonwebtoken');
const jwtKey='my_secret_key';
const bodyParser=require('body-parser');
module.exports=function(app){
app.use(bodyParser.json());
app.get('/searchstudent',[authorization,validateBody,searchStudent]);
}
authorization=function(req,res,next){
const token=req.query.token;
try{
payload=jwt.verify(token,jwtKey);
}
catch(error){
return res.status(401).end();
}
next();
}
validateBody=function(req,res,next){
next();
}
searchStudent= async function(req,res,next){
const condition = {'email': req.body.email};
console.log('hello world' +req.body.email);
console.log()
const data=await Query.find('student','*',condition);
res.send(data);
} | 6d95a94949d97feda36cb964e46c70c4bc675ddb | [
"JavaScript"
] | 6 | JavaScript | SamanZubair/NodeSchoolProject | 22a06777a1d8984b1ed206b0fae1bda8bf237296 | 710662cb2231fb8c69c85f629a3d4fed62d11bad |
refs/heads/master | <repo_name>npsc-tx/xuexitong-chaoxing<file_sep>/caoxing.js
// ==UserScript==
// @name 超星助手-视频静音播放
// @namespace https://github.com/npsc-tx/xuexitong-chaoxing
// @version 0.1
// @description 视频静音以及自动播放
// @author 天析
// @match https://mooc1-1.chaoxing.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
//核心片段开始
setInterval(function () {
//读取视频
var sp = $("iframe").contents().find("iframe").contents();
//读取加载
var jz = sp.find("#loading");
//读取进度
var jd = sp.find("#video > div.vjs-control-bar > div.vjs-progress-control.vjs-control > div").attr("aria-valuenow");
//静音播放
var bofang = function () {
sp.find("#video > button").click();
var jy = sp.find("#video > div.vjs-control-bar > div.vjs-volume-panel.vjs-control.vjs-volume-panel-vertical > button");
if (jy.attr("title") != "取消静音") {
jy.click()
}
}
//主程序开始
if (jd != 100) {
//调用播放
console.log("完成进度:" + jd);
bofang();
}
if (jd == 100) {
console.log("本页面视频进度完成!");
}
}, 100);
//核心片段结束
})();<file_sep>/README.md
# 学习通视频播放脚本
适用于Windows操作系统,部分浏览器可能存在各种玄学原因导致无法使用,你可以在阅读完本片段原理后尝试自己编写
----
苦于超星播放器一开鼠标会停止播放,所以写了这样的一个脚本,用于更安心的学习!
## 使用方法:
你可以将该脚本的核心片段放于浏览器调试控制台执行,也可以复制整个代码添加到油猴脚本中运行!
该方法较为简单,简单阅读代码即可明白原理!下面是核心代码片段:
```
//核心片段开始
setInterval(function () {
//读取视频
var sp = $("iframe").contents().find("iframe").contents();
//读取加载
var jz = sp.find("#loading");
//读取进度
var jd = sp.find("#video > div.vjs-control-bar > div.vjs-progress-control.vjs-control > div").attr("aria-valuenow");
//静音播放
var bofang = function () {
sp.find("#video > button").click();
var jy = sp.find("#video > div.vjs-control-bar > div.vjs-volume-panel.vjs-control.vjs-volume-panel-vertical > button");
if (jy.attr("title") != "取消静音") {
jy.click()
}
}
//主程序开始
if (jd != 100) {
//调用播放
console.log("完成进度:" + jd);
bofang();
}
if (jd == 100) {
console.log("本页面视频进度完成!");
}
}, 100);
//核心片段结束
``` | 62ff06fc473cba1f9ca44a4ec3ba62fb3224b149 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | npsc-tx/xuexitong-chaoxing | fcb23157dd69c025357150bd6a952a8a31f1baaf | 5f1d61e5c513ee02db6f025d3b71d6b6761d7ddc |
refs/heads/master | <file_sep>## clustering
cdata = read.csv('customer_hier_clus.csv',header=T)
customer = scale(cdata[,-1])
## agglomerative heirarchical clusting:
hc = hclust(dist(customer, method='euclidian'), method='ward.D2')
## plot dendrogram:
plot(hc, hang=-.01, cex=.7)
##use single method to perform heirarchical clustering:
hc2 = hclust(dist(customer), method='single')
plot(hc2, hang=-.01, cex=.7)
library(cluster)
dv = diana(customer, metric='euclidian')##divisive
ag = agnes(customer, metric = 'euclidian')##agglomerative
summary(dv)
plot(dv)
library(dendextend)
## set up dendrogram
dend = customer %>% dist %>% hclust %>% as.dendrogram
## horizontal dendrogram
dend %>% plot(horiz = T, main = 'Sidewise Dendogram')
## categorise data into groups:
fit = cutree(hc, k=4)
## Count data within each cluster:
table(fit)
## Place a rectangle around a certain cluster:
plot(hc)
rect.hclust(hc, k=4, which=1, border='red')
## Color the brach according to the cluster it belongs to:
dend %>% color_branches(k=4) %>% plot(horiz=F, main='Horiz Dendrogram')
## Add a rectangle around clusters:
dend %>% rect.dendrogram(k=4, horiz=F)
## add a line to see cutting location:
abline(h= heights_per_k.dendrogram(dend)['4']+.1, lwd=2, lty=2, col='blue')
| 8314622d5ca260e6b5202b9f0395cc9b3b53a93f | [
"R"
] | 1 | R | Divnsh/hierarchical-clustering | e82c94b75b1fc1b8ff3d864567c276c7f0898063 | 3f1add7feb95f876772ee4b3f88991bc8c92f16e |
refs/heads/master | <file_sep>package main
import (
"os"
"strings"
log "github.com/sirupsen/logrus"
_ "github.com/kshvakov/clickhouse"
)
func main() {
cfg, err := _ConfigFromEnv()
if err != nil {
log.Fatalf("failed to init config: %v", err)
}
var logLevel log.Level
if cfg.Debug {
logLevel = log.DebugLevel
} else {
logLevel = log.InfoLevel
}
log.SetLevel(logLevel)
log.Debugf("max workers size is %d", cfg.MaxWorkers)
args := append([]string{"clickhouse-client"}, os.Args[1:]...)
query := strings.Join(args, " ")
log.Debugf("searches shodan using \"%s\"", query)
cd, err := _NewClickDown(cfg)
if err != nil {
log.Fatalf("failed to init clickdown: %v", err)
}
defer func() {
if err := cd.Shutdown(); err != nil {
log.Fatalf("failed to shutdown: %v", err)
}
}()
if err := cd.Run(query); err != nil {
log.Fatalf("failed to run clickdown: %v", err)
}
}
<file_sep>module github.com/fdhadzh/clickdown
go 1.13
require (
github.com/google/go-querystring v1.0.0 // indirect
github.com/jmoiron/sqlx v1.2.0
github.com/kelseyhightower/envconfig v1.4.0
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kshvakov/clickhouse v1.3.11
github.com/moul/http2curl v1.0.0 // indirect
github.com/panjf2000/ants v1.3.0
github.com/sirupsen/logrus v1.4.2
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3 // indirect
gopkg.in/ns3777k/go-shodan.v3 v3.1.0
)
<file_sep>package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/jmoiron/sqlx"
"github.com/panjf2000/ants"
log "github.com/sirupsen/logrus"
"gopkg.in/ns3777k/go-shodan.v3/shodan"
)
// ErrUnreachable is the server unreachable error
var ErrUnreachable = errors.New("service is unreachable")
var (
// GetClickHouseVersionQuery is the query to obtain server version
GetClickHouseVersionQuery = `SELECT version() AS version`
// GetClickHousePartsQuery is the query to obtain parts (tables) size
GetClickHousePartsQuery = `SELECT concat(database, '.', table) AS name,
formatReadableSize(sum(bytes)) as size
FROM system.parts
WHERE active
GROUP BY name`
)
type _ClickDown struct {
cfg *_Config
client *shodan.Client
pool *ants.Pool
}
type _ServerMeta struct {
Server _ClickHouseServer
Parts []_ClickHousePart
}
type _ClickHouseServer struct {
Version string `db:"version"`
}
type _ClickHousePart struct {
Name string `db:"name"`
Size string `db:"size"`
}
func _NewClickDown(cfg *_Config) (*_ClickDown, error) {
client := shodan.NewClient(&http.Client{}, cfg.ShodanAPIKey)
client.SetDebug(cfg.Debug)
pool, err := ants.NewPool(cfg.MaxWorkers)
if err != nil {
return nil, err
}
return &_ClickDown{cfg, client, pool}, nil
}
func (cd *_ClickDown) Run(query string) error {
var wg sync.WaitGroup
page := 1
for {
opts := &shodan.HostQueryOptions{
Query: query,
Page: page,
Minify: true,
}
resp, err := cd.client.GetHostsForQuery(context.Background(), opts)
if err != nil {
if strings.HasPrefix(err.Error(), "Request rate limit") {
log.Debug("rate limit exceeded")
time.Sleep(time.Second * 3)
continue
}
return err
}
for _, match := range resp.Matches {
wg.Add(1)
endpoint := fmt.Sprintf("%s:%d", match.IP.String(), match.Port)
task := cd.WrapCheckServer(endpoint)
err := cd.pool.Submit(func() {
task()
wg.Done()
})
if err != nil {
return err
}
}
if len(resp.Matches) != resp.Total && len(resp.Matches) != 0 {
page++
} else {
break
}
}
wg.Wait()
return nil
}
func (cd *_ClickDown) WrapCheckServer(endpoint string) func() {
wrapper := func() {
meta, err := cd.CheckServer(endpoint)
if err != nil {
log.Debugf("failed to check server: %v", err)
return
}
version := fmt.Sprintf("ClickHouse %s", meta.Server.Version)
for _, part := range meta.Parts {
log.Infof("table \"%s\" (%s) on \"%s\" (%s)", part.Name,
part.Size, endpoint, version)
}
}
return wrapper
}
func (cd *_ClickDown) CheckServer(endpoint string) (*_ServerMeta, error) {
opts := url.Values{}
opts.Set("read_timeout", strconv.Itoa(cd.cfg.ClickHouseReadTimeout))
if cd.cfg.Debug {
opts.Set("debug", "true")
}
dsn := fmt.Sprintf("tcp://%s?%s", endpoint, opts.Encode())
db, err := sqlx.Open("clickhouse", dsn)
if err != nil {
return nil, err
}
defer func() {
if err := db.Close(); err != nil {
log.Errorf("failed to close db: %v", err)
}
}()
if err := db.Ping(); err != nil {
return nil, ErrUnreachable
}
parts := []_ClickHousePart{}
err = db.Select(&parts, GetClickHousePartsQuery)
if err != nil {
return nil, err
}
server := _ClickHouseServer{}
row := db.QueryRowx(GetClickHouseVersionQuery)
if err != nil {
return nil, err
}
if err := row.StructScan(&server); err != nil {
return nil, err
}
meta := &_ServerMeta{
Server: server,
Parts: parts,
}
return meta, nil
}
func (cd *_ClickDown) Shutdown() error {
cd.pool.Release()
return nil
}
<file_sep>package main
import "github.com/kelseyhightower/envconfig"
type _Config struct {
Debug bool
MaxWorkers int `envconfig:"MAX_WORKERS" default:"32"`
ClickHouseReadTimeout int `envconfig:"CLICKHOUSE_READ_TIMEOUT" default:"10"`
ShodanAPIKey string `envconfig:"SHODAN_API_KEY" required:"true"`
}
func _ConfigFromEnv() (*_Config, error) {
cfg := &_Config{}
err := envconfig.Process("", cfg)
return cfg, err
}
<file_sep>DEBUG="true"
MAX_WORKERS="16"
CLICKHOUSE_READ_TIMEOUT="30"
SHODAN_API_KEY="<KEY>"<file_sep># ClickDown


[](https://goreportcard.com/report/github.com/fdhadzh/clickdown)
[](https://microbadger.com/images/fdhadzh/clickdown)
Explore vulnerable ClickHouse servers using Shodan.io
## Table of Contents
- [Disclaimer](#disclaimer)
- [Installing](#installing)
- [Usage](#usage)
- [Configuration](#configuration)
- [Running](#running)
- [Using Docker](#using-docker)
- [License](#license)
### Disclaimer
When used properly, ClickDown helps protect your ClickHouse servers.
But when used improperly, ClickDown can get you sued, fired, expelled or jailed.
Reduce your risk by reading this legal guide before launching ClickDown.
### Installing
Install ClickDown by running:
```bash
go get github.com/fdhadzh/clickdown
```
and ensuring that $GOPATH/bin is added to your $PATH.
### Usage
#### Configuration
Configuration using environment variables:
| Variable | Description | Default |
|---------------------------|------------------------------------|---------|
| `DEBUG` | Debug flag | `false` |
| `MAX_WORKERS` | Max workers count | `32` |
| `CLICKHOUSE_READ_TIMEOUT` | ClickHouse read timeout in seconds | `10` |
| `SHODAN_API_KEY` | Shodan.io API key | |
#### Running
ClickDown usage format:
```bash
clickdown <search-query>
```
> Where `search-query` is a Shodan.io search query ([Shodan.io Search Query Fundamentals](https://help.shodan.io/the-basics/search-query-fundamentals))
For example, explore ClickHouse servers from Russian country:
```bash
$ clickdown country:ru
INFO[0001] table "tsb_shard_2.app_method" (17.90 MiB) on "172.16.31.10:9000" (ClickHouse 18.16.1)
INFO[0001] table "tsb_shard_2.app_method_aggr_min" (3.65 KiB) on "172.16.31.10:9000" (ClickHouse 18.16.1)
INFO[0001] table "axs.events" (2.10 GiB) on "172.16.31.10:9000" (ClickHouse 1.1.54394)
INFO[0001] table "axs.transactions" (12.00 GiB) on "172.16.31.10:9000" (ClickHouse 1.1.54394)
INFO[0001] table "tipico.bets" (1.76 GiB) on "172.16.17.32:9000" (ClickHouse 1.1.54385)
INFO[0001] table "tipico.players" (3.77 MiB) on "172.16.17.32:9000" (ClickHouse 1.1.54385)
INFO[0001] table "tipico.all_bets" (2.88 GiB) on "172.16.17.32:9000" (ClickHouse 1.1.54385)
INFO[0001] table "tipico.events" (18.69 MiB) on "172.16.17.32:9000" (ClickHouse 1.1.54385)
INFO[0001] table "tipico.tickets" (432.57 MiB) on "172.16.17.32:9000" (ClickHouse 1.1.54385)
...
```
Ensure that found server is open for everyone:
```bash
$ docker run -it --rm yandex/clickhouse-client --host 172.16.31.10 --port 9000
ClickHouse client version 19.1.6.
Connecting to 172.16.31.10:9000.
Connected to ClickHouse server version 18.16.1 revision 54412.
localhost :) SELECT count(*) FROM tsb_shard_2.app_method
SELECT count(*)
FROM tsb_shard_2.app_method
┌─count()─┐
│ 314034 │
└─────────┘
1 rows in set. Elapsed: 0.493 sec. Processed 314.03 thousand rows, 1.26 MB (637.59 thousand rows/s., 2.55 MB/s.)
```
#### Using Docker
```bash
docker run -e SHODAN_API_KEY="<shodan-api-key>" fdhadzh/clickdown
```
### License
MIT; see [LICENSE](/LICENSE) for details. | 0bc469b8c22b37ee41f213bc45c979e25ef4de0b | [
"Markdown",
"Go Module",
"Go",
"Shell"
] | 6 | Go | fdhadzh/clickdown | 7b301a5df7ec1d78eb853a582b58e6b4cd89b908 | 5948710b8511fddbdc7770b7b92f7ad657ea45d2 |
refs/heads/master | <repo_name>vanathin/spring-rabbitmq-producer<file_sep>/src/main/java/com/example/learning/springrabbitproducer/controller/EmployeeController.java
package com.example.learning.springrabbitproducer.controller;
import com.example.learning.springrabbitproducer.bean.Employee;
import com.example.learning.springrabbitproducer.service.RabbitMQSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmployeeController {
@Autowired
RabbitMQSender rabbitMQSender;
@PostMapping(value = "/employees")
public boolean saveEmployee(@RequestBody Employee employee){
rabbitMQSender.send(employee);
return true;
}
}
<file_sep>/README.md
# spring-rabbitmq-producer
Event Driven Miscroservice Communication:
1. This act as a producer and for consumer please refer spring-rabbitmq-consumer project
| e3354747c5a4771bd8ba14075d0804fa14d029d2 | [
"Markdown",
"Java"
] | 2 | Java | vanathin/spring-rabbitmq-producer | f78909a31da972456072d83f5baede2e0f30f880 | 495284405d736987d6cae5496d0e80d937a3be48 |
refs/heads/master | <repo_name>eimantaszlabys/NetCoreDocker<file_sep>/src/netCoreHandlers/DI/ReaderModule.cs
using System;
using Autofac;
using netCoreReaderCore;
using netCoreReaderRmysql;
namespace netCoreHandlers.DI
{
public class ReaderModule : Module
{
private readonly string _connectionString;
public ReaderModule(string connectionString)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_connectionString = connectionString;
}
protected override void Load(ContainerBuilder builder)
{
builder.Register(x => new DataReader(_connectionString))
.As<IDataReaderClient>()
.SingleInstance();
}
}
}
<file_sep>/src/netCoreWriterRmysql/DataWriter.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using netCoreWriterCore;
namespace netCoreWriterRmysql
{
public class DataWriter : IDataWriterClient
{
private readonly string _connectionString;
public DataWriter(string connectionString)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_connectionString = connectionString;
}
public Task<int> AddData(string value)
{
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
const string sql = "INSERT INTO Data (Value) VALUES (@value)";
return connection.ExecuteAsync(sql, new { value = String.Concat("('", value, "')") }, commandType: CommandType.Text);
}
}
public Task<int> AddData(string[] value)
{
var values = new List<string>(value.Length);
foreach (string val in value)
{
values.Add(String.Concat("('", val, "')"));
}
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
string sql = $"INSERT INTO Data (Value) VALUES {string.Join(",", values)}";
return connection.ExecuteAsync(sql, commandType: CommandType.Text);
}
}
public Task<int> UpdateData(int id, string value)
{
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
const string sql = "UPDATE Data SET Value = @value WHERE Id = @id";
return connection.ExecuteAsync(sql, new { value, id }, commandType: CommandType.Text);
}
}
public Task<int> DeleteData(int id)
{
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
const string sql = "DELETE Data WHERE Id = @id";
return connection.ExecuteAsync(sql, new { id }, commandType: CommandType.Text);
}
}
}
}
<file_sep>/src/netCoreContracts/AddDataRequest.cs
namespace netCoreContracts
{
public class AddDataRequest : BaseRequest
{
public string[] Value { get; set; }
}
}<file_sep>/src/netCoreHandlers/GetDataHandler.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using netCoreContracts;
using netCoreReaderCore;
namespace netCoreHandlers
{
public class GetDataHandler : BaseHandler<GetDataRequest, GetDataResponse>
{
private readonly IDataReaderClient _dataReaderClient;
public GetDataHandler(IDataReaderClient dataReaderClient)
{
if (dataReaderClient == null) throw new ArgumentNullException(nameof(dataReaderClient));
_dataReaderClient = dataReaderClient;
}
protected override async Task<GetDataResponse> HandleCore(GetDataRequest request)
{
GetDataResponse response = new GetDataResponse
{
Data = new List<DataDto>()
};
if (request.Id == null)
{
throw new ArgumentNullException(nameof(request));
}
if (request.Id.Length == 1)
{
DataModel data = await _dataReaderClient.GetValue(request.Id[0]);
response.Data.Add(new DataDto
{
Id = data.Id,
Value = data.Value
});
}
else
{
IEnumerable<DataModel> data = await _dataReaderClient.GetValues(request.Id);
foreach (DataModel dataModel in data)
{
var res = new DataDto
{
Id = dataModel.Id,
Value = dataModel.Value
};
response.Data.Add(res);
}
}
return response;
}
}
}<file_sep>/src/netCoreContracts/GetDataResponse.cs
using System.Collections.Generic;
namespace netCoreContracts
{
public class GetDataResponse : BaseResponse
{
public IList<DataDto> Data { get; set; }
}
public class DataDto
{
public int Id { get; set; }
public string Value { get; set; }
}
}<file_sep>/tools/Database/01.Inner/01.Create_Database.sql
CREATE DATABASE NetCore CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;<file_sep>/src/netCore/Dockerfile
FROM ubuntu:16.04
COPY "bin/release/netcoreapp1.0/ubuntu.16.04-x64/publish/" /root/
EXPOSE 5000/tcp
# Install required packages
RUN apt-get update && apt-get --yes install apt-transport-https && apt-get --yes install apt-utils
RUN sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotnetdev.list'
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
RUN apt-get update && apt-get --yes install dotnet-dev-1.0.0-preview2.1-003177
ENTRYPOINT dotnet /root/netCore.dll<file_sep>/src/netCore/Startup.cs
using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using netCoreHandlers.DI;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Swashbuckle.Swagger.Model;
using Chimera.Extensions.Logging.Log4Net;
namespace netCore
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
IMvcBuilder mvcBuilder = services.AddMvc();
mvcBuilder.AddJsonOptions(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.AddSwaggerGen(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Swagger Sample API",
Description = "API Sample made",
TermsOfService = "None"
});
});
ContainerBuilder builder = new ContainerBuilder();
builder.Populate(services);
builder.RegisterModule<HandlersModule>();
builder.RegisterModule(new ReaderModule(Configuration.GetConnectionString("rmysql")));
builder.RegisterModule(new WriterModule(Configuration.GetConnectionString("rmysql")));
IContainer container = builder.Build();
return container.Resolve<IServiceProvider>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net(Configuration.GetSection("log4net").Get<Log4NetSettings>());
app.UseSwagger();
app.UseSwaggerUi();
app.UseMvc();
}
}
}
<file_sep>/src/netCoreContracts/AddDataResponse.cs
namespace netCoreContracts
{
public class AddDataResponse : BaseResponse
{
}
}<file_sep>/src/netCoreContracts/BaseResponse.cs
namespace netCoreContracts
{
public class BaseResponse
{
public string Exception { get; set; }
public string Ip { get; set; }
}
}<file_sep>/src/netCoreWriterCore/IDataWriterClient.cs
using System.Threading.Tasks;
namespace netCoreWriterCore
{
public interface IDataWriterClient
{
Task<int> AddData(string value);
Task<int> AddData(string[] value);
Task<int> UpdateData(int id, string value);
Task<int> DeleteData(int id);
}
}
<file_sep>/tools/Database/run.sh
#!/bin/bash
# My first script
function RunScript() {
echo "Running script: $1";
mysql --user=root --password=<PASSWORD> < "$1";
}
function ExecuteScripts() {
for path in $(find ./ -type f -iname "*.sql" -follow);
do
RunScript $path
done
}
ExecuteScripts
$SHELL
<file_sep>/tests/netCoreReaderRmysqlTests/DataReaderTests.cs
using System.Collections.Generic;
using netCoreReaderCore;
using netCoreReaderRmysql;
using NUnit.Framework;
namespace netCoreReaderRmysqlTests
{
[TestFixture]
public class DataReaderTests
{
private IDataReaderClient _readerClient;
[SetUp]
public void Setup()
{
_readerClient = new DataReader("Server=localhost;Database=NetCore;Uid=root;Pwd=<PASSWORD>;");
}
[Test]
public void ValueExists()
{
Assert.DoesNotThrowAsync(() => _readerClient.GetValue(1));
}
[Test]
public void ValueNotExists()
{
Assert.DoesNotThrowAsync(() => _readerClient.GetValue(0));
}
[Test]
public void ValuesExists()
{
Assert.DoesNotThrowAsync(() => _readerClient.GetValues(new List<int>(1) { 1 }));
}
[Test]
public void ValuesNotExists()
{
Assert.DoesNotThrowAsync(() => _readerClient.GetValues(new List<int>(1) { 0 }));
}
}
}
<file_sep>/src/netCoreHandlers/BaseHandler.cs
using System;
using System.Threading.Tasks;
using netCoreContracts;
namespace netCoreHandlers
{
public interface IHandler<in TRequest, TResponse>
where TRequest : BaseRequest
where TResponse : BaseResponse, new()
{
Task<TResponse> Handle(TRequest request);
}
public abstract class BaseHandler<TRequest, TResponse> : IHandler<TRequest, TResponse>
where TRequest : BaseRequest
where TResponse : BaseResponse, new()
{
public async Task<TResponse> Handle(TRequest request)
{
if (request == null)
throw new Exception("Request is not provided");
TResponse response;
try
{
response = await HandleCore(request);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return response;
}
protected abstract Task<TResponse> HandleCore(TRequest request);
}
}
<file_sep>/src/netCoreHandlers/AddDataHandler.cs
using System;
using System.Threading.Tasks;
using netCoreContracts;
using netCoreWriterCore;
namespace netCoreHandlers
{
public class AddDataHandler : BaseHandler<AddDataRequest, AddDataResponse>
{
private readonly IDataWriterClient _writerClient;
public AddDataHandler(IDataWriterClient writerClient)
{
if (writerClient == null) throw new ArgumentNullException(nameof(writerClient));
_writerClient = writerClient;
}
protected override async Task<AddDataResponse> HandleCore(AddDataRequest request)
{
if (request.Value == null || request.Value.Length == 0)
{
throw new ArgumentNullException(nameof(request));
}
await _writerClient.AddData(request.Value);
return new AddDataResponse();
}
}
}<file_sep>/src/netCoreReaderRmysql/DataReader.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using netCoreReaderCore;
namespace netCoreReaderRmysql
{
public class DataReader : IDataReaderClient
{
private readonly string _connectionString;
public DataReader(string connectionString)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_connectionString = connectionString;
}
public Task<DataModel> GetValue(int id)
{
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
const string query = "SELECT Id, Value FROM Data WHERE Id = @id";
return connection.QueryFirstOrDefaultAsync<DataModel>(query, new { id }, commandType: CommandType.Text);
}
}
public Task<IEnumerable<DataModel>> GetValues(IList<int> ids)
{
SqlBuilder builder = new SqlBuilder();
SqlBuilder.Template template = builder.AddTemplate("SELECT Id, Value FROM Data /**where**/");
if (ids.Count > 0)
{
builder.Where("Id IN (@ids)", new {ids = String.Join(",", ids)});
}
using (MySqlConnection connection = new MySqlConnection(_connectionString))
{
return connection.QueryAsync<DataModel>(template.RawSql, template.Parameters, commandType: CommandType.Text);
}
}
}
}
<file_sep>/src/netCore/Controllers/ValuesController.cs
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using netCoreContracts;
using netCoreHandlers;
namespace netCore.Controllers
{
[Route("api/[controller]")]
public class ValuesController : BaseController
{
private readonly IServiceProvider _serviceProvider;
public ValuesController(IServiceProvider serviceProvider)
{
if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));
_serviceProvider = serviceProvider;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int[] id)
{
GetDataRequest request = new GetDataRequest
{
Id = id
};
var handler = _serviceProvider.GetService<IHandler<GetDataRequest, GetDataResponse>>();
var response = await handler.Handle(request);
return Ok(response);
}
[HttpPost]
[Route("GetMany")]
public async Task<IActionResult> GetMany([FromBody] GetDataRequest request)
{
var handler = _serviceProvider.GetService<IHandler<GetDataRequest, GetDataResponse>>();
return Ok(await handler.Handle(request));
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] AddDataRequest request)
{
var handler = _serviceProvider.GetService<IHandler<AddDataRequest, AddDataResponse>>();
return Ok(await handler.Handle(request));
}
}
}
<file_sep>/src/netCoreHandlers/DI/HandlersModule.cs
using Autofac;
using netCoreContracts;
namespace netCoreHandlers.DI
{
public class HandlersModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<GetDataHandler>()
.As<IHandler<GetDataRequest, GetDataResponse>>()
.SingleInstance();
builder.RegisterType<AddDataHandler>()
.As<IHandler<AddDataRequest, AddDataResponse>>()
.SingleInstance();
}
}
}<file_sep>/src/netCoreReaderCore/IDataReaderClient.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace netCoreReaderCore
{
public interface IDataReaderClient
{
Task<DataModel> GetValue(int id);
Task<IEnumerable<DataModel>> GetValues(IList<int> ids);
}
}
<file_sep>/src/netCore/Controllers/BaseController.cs
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace netCore.Controllers
{
public class BaseController : Controller
{
public override async void OnActionExecuted(ActionExecutedContext context)
{
IPHostEntry host = await Dns.GetHostEntryAsync(Dns.GetHostName());
Response.Headers.Add("Ip", host.AddressList.FirstOrDefault().MapToIPv4().ToString());
base.OnActionExecuted(context);
}
}
}<file_sep>/src/netCoreContracts/GetDataRequest.cs
namespace netCoreContracts
{
public class GetDataRequest : BaseRequest
{
public int[] Id { get; set; }
}
}<file_sep>/tools/Deploy_Local/Dockerfile
FROM ubuntu:16.04
COPY release/ /root/
# Install required packages
RUN apt-get update && apt-get --yes install apt-utils && apt-get --yes install apt-transport-https
RUN sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotnetdev.list'
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
RUN apt-get update && apt-get --yes install dotnet-dev-1.0.0-preview2.1-003177
ENTRYPOINT dotnet /root/netCore.dll<file_sep>/tools/Database/00.Clean/_clean.sql
DROP DATABASE IF EXISTS NetCore;<file_sep>/src/netCoreHandlers/DI/WriterModule.cs
using System;
using Autofac;
using netCoreWriterCore;
using netCoreWriterRmysql;
namespace netCoreHandlers.DI
{
public class WriterModule : Module
{
private readonly string _connectionString;
public WriterModule(string connectionString)
{
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
_connectionString = connectionString;
}
protected override void Load(ContainerBuilder builder)
{
builder.Register(x => new DataWriter(_connectionString))
.As<IDataWriterClient>()
.SingleInstance();
}
}
}
<file_sep>/tools/Database/01.Inner/02.Create_Data_Table.sql
USE `NetCore`
CREATE TABLE IF NOT EXISTS `Data` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Value` text NULL,
PRIMARY KEY (`Id`)
);
INSERT INTO `Data` (`Value`) VALUES ("Test"); | 7bbb0b20c64e866384096381004cd445809fe199 | [
"C#",
"Dockerfile",
"Shell",
"SQL"
] | 25 | C# | eimantaszlabys/NetCoreDocker | 7acbf3df446c467158071cb0c8bfbb3e47c604b5 | 6116006198e39eec013c1a7d54630a42ed75786d |
refs/heads/master | <repo_name>liliilli/KNU_econtrade<file_sep>/app/src/main/java/kr/ac/knu/bist/knu_econtrade/Activities/Scene_Intro.java
package kr.ac.knu.bist.knu_econtrade.Activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import kr.ac.knu.bist.knu_econtrade.R;
/**
* Created by neu on 16. 8. 29.
*
* Scene_Intro
* First activity when application has been initialized.
* Next scene activity will be Scene_Login after being loaded all of components.
*
*/
public class Scene_Intro extends Activity {
Handler Handler_Local;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*no title bar, and status bar*/
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_intro_intro);
Handler_Local = new Handler(); //딜래이를 주기 위해 핸들러 생성
Handler_Local.postDelayed(millirun, 2000);
}
Runnable millirun = new Runnable() {
@Override
public void run() {
Intent Local_Intent = new Intent(Scene_Intro.this, Scene_Main.class);
startActivity(Local_Intent); finish();
// animation effect
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
@Override
public void onBackPressed() {
super.onBackPressed();
Handler_Local.removeCallbacks(millirun);
}
}
<file_sep>/README.md
# KNU_econtrade
ONLY FOR BIST DEVELOPERS!!
| 9ae1bf9afa53afeeb984bb3387eb1a395be37b6d | [
"Markdown",
"Java"
] | 2 | Java | liliilli/KNU_econtrade | cadf7778b345001fad3e813db72d9d609fe430d6 | e4b9a8d75c421a4100e41fe0b1b4b38abc8a24b2 |
refs/heads/master | <file_sep>from abc import ABC
class Target(ABC):
"""
The Target defines the domain-specific interface required by the client code.
"""
def request(self) -> str: pass
class Adaptee:
"""
The Adaptee contains some useful behavior, but its interface is incompatible
with the existing client code. The Adaptee needs some adaptation before the
client code can use it.
"""
def specific_request(self) -> str:
return ".eetpadA eht fo roivaheb laicepS"
class Adapter(Target):
"""
The Adapter makes the Adaptee's interface compatible with the Target's
interface.
"""
def __init__(self, adaptee: Adaptee) -> None:
self.adaptee = adaptee
def request(self) -> str:
return f"Adapter: (TRANSLATED) {self.adaptee.specific_request()[::-1]}"
def client_code(target: Target) -> None:
"""
The client code supports all concrete classes that follow the Target interface.
"""
print(target.request(), end="")
if __name__ == "__main__":
adaptee = Adaptee()
print("Client: The Adaptee class has a weird interface, which doesn't work well with my code")
print(f"Adaptee: {adaptee.specific_request()}", end="\n\n")
print("Client: But I can work with it via the Adapter:")
adapter = Adapter(adaptee)
client_code(adapter)<file_sep>## Design Patterns in Python
### Section 3: Factory
- A `factory method` is a static method that creates objects
- A `factory` is an entity that can take care of object creation
- A `factory` can be an external class, or reside inside the object as an inner class
- Hierarchies(family) of factories can be used to create related object
Factory Class
```python
from math import cos, sin
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"x is {str(self.x)}, y is {str(self.y)}"
class PointFactory:
def new_cartesian_point(self, x, y):
return Point(x, y)
def new_polar_point(self, rho, theta):
return Point(rho * cos(theta), rho * sin(theta))
if __name__ == "__main__":
my_point = Point(2, 3)
my_point_factory = my_point.PointFactory()
p1 = my_point_factory.new_cartesian_point(my_point.x, my_point.y)
p2 = my_point_factory.new_polar_point(my_point.x, my_point.y)
```
Abstract Factory
```python
from abc import ABC
from enum import Enum, auto
class HotDrink(ABC):
"""
Abstract class for concrete products(drinks)
"""
def consume(self):
pass
class Tea(HotDrink):
def consume(self):
print("This is a tea product")
class Coffee(HotDrink):
def consume(self):
print("This is a Coffee product")
class HotDrinkFactory(ABC):
"""
Abstract class for a family of factories
"""
def produce(self, amount):
pass
class TeaFactory(HotDrinkFactory):
def produce(self, amount=2):
print(f"{amount} {'cups' if amount > 1 else 'cup'} of Tea has been produced")
return Tea()
class CoffeeFactory(HotDrinkFactory):
def produce(self, amount=2):
print(f"{amount} {'cups' if amount > 1 else 'cup'} of Coffee has been produced")
return Coffee()
class Drinks(Enum):
TEA = auto()
COFFEE = auto()
if __name__ == "__main__":
target_product = "COFFEE"
if target_product not in Drinks.__members__:
raise ValueError(f"{target_product} is not supported product type.")
# capitalize first letter, lower remaining letters
# eg: 'COFFEE' to 'Coffee'
product_name = f"{target_product[0]}{target_product[1:].lower()}"
factory_name = f"{product_name}Factory"
factory_instance = eval(factory_name)()
product = factory_instance.produce()
print("product produced:", type(product))
```
### Section 4: Prototype
1. To implement a prototype, firstly partially/fully construct an object, and store it somewhere (like we did forsyndey_office_emp_proto and melbourne_office_emp_proto)
2. Then you deepcopy the prototype
3. Then customize the deeocopy instance
4. You can then use a factory to provide a convenient API for using prototypes (like the \_\_new_employee method)
```python
import copy
class Address:
def __init__(self, suite, street_address, city):
self.street_address = street_address
self.suite = suite
self.city = city
def __str__(self):
return f"{self.suite}, {self.street_address}, {self.city}"
class Employee:
def __init__(self, name, address):
self.name = name
self.address = address
def __str__(self):
return f"{self.name} works @ {self.address}"
class EmployeeFactory:
# setup 2 prototypes to be used
syndey_office_emp_proto = Employee('', Address('001', "Main street", "Sydney"))
melbourne_office_emp_proto = Employee('', Address('500', "Kings street", "Melbourne"))
@staticmethod
# Used for deep copy a prototype, then customize it
def __new_employee(proto, name):
new_emp = copy.deepcopy(proto)
new_emp.name = name
return new_emp
@staticmethod
def new_sydney_employee(name):
return EmployeeFactory.__new_employee(EmployeeFactory.syndey_office_emp_proto, name)
@staticmethod
def new_melbourne_employee( name):
return EmployeeFactory.__new_employee(EmployeeFactory.melbourne_office_emp_proto, name)
john = EmployeeFactory.new_sydney_employee("John") # John works @ 001, Main street, Sydney
jane = EmployeeFactory.new_melbourne_employee("Jane") # Jane works @ 500, Kings street, Melbourne
```
### Section 6: Adapter
1. Determine the API that you have, and the API you need
2. Create an Adapter component, which aggregates (has a reference to) the adaptee
```py
from abc import ABC
class Target(ABC):
"""
The Target defines the domain-specific interface required by the client code.
"""
def request(self) -> str: pass
class Adaptee:
"""
The Adaptee contains some useful behavior, but its interface is incompatible
with the existing client code. The Adaptee needs some adaptation before the
client code can use it.
"""
def specific_request(self) -> str:
return ".eetpadA eht fo roivaheb laicepS"
class Adapter(Target):
"""
The Adapter makes the Adaptee's interface compatible with the Target's
interface.
"""
def __init__(self, adaptee: Adaptee) -> None:
self.adaptee = adaptee
def request(self) -> str:
return f"Adapter: (TRANSLATED) {self.adaptee.specific_request()[::-1]}"
def client_code(target: Target) -> None:
"""
The client code supports all concrete classes that follow the Target interface.
"""
print(target.request(), end="")
if __name__ == "__main__":
adaptee = Adaptee()
print("Client: The Adaptee class has a weird interface, which doesn't work well with my code")
print(f"Adaptee: {adaptee.specific_request()}", end="\n\n")
print("Client: But I can work with it via the Adapter:")
adapter = Adapter(adaptee)
client_code(adapter)
```
### Section 7: Bridge
1. Decouple abstraction from implementation
2. Both can exist as hierarchies, both can change without affecting each other
```py
# line type: solid, dashed
# color: colored, black & white
# shape: circle, square
from abc import ABC
class Formatter(ABC):
def format_circle(self, str): pass
def format_square(self, str): pass
class DashedFormatter(Formatter):
def format_circle(self, str):
print(f'Use dashed line to circle')
def format_square(self, str):
print(f'Use dashed line to square')
class SolidFormatter(Formatter):
def format_circle(self, radius):
print(f'Use solid line to circle')
def format_square(self, side):
print(f'Use solid line to square')
class Renderer(ABC):
def render_circle(self, radius): pass
def render_square(self, side): pass
class ColoredRenderer(Renderer):
def render_circle(self, radius):
print(f'Coloring a circle with radius {radius}')
def render_square(self, side):
print(f'Coloring a square with side {side}')
class BlackAndWhiteRenderer(Renderer):
def render_circle(self, radius):
print(f'Drawing a circle with radius {radius}')
def render_square(self, side):
print(f'Drawing a square with side {side}')
class Shape:
"""
Base class for all subtypes of shapes
"""
def __init__(self, renderer: Renderer, formatter: Formatter):
self.renderer = renderer
self.formatter = formatter
def draw(self): pass
class Circle(Shape):
def __init__(self, renderer: Renderer, formatter: Formatter, radius):
super().__init__(renderer, formatter)
self.radius = radius
def draw(self):
self.formatter.format_circle(self.renderer.render_circle(self.radius))
class Square(Shape):
def __init__(self, renderer: Renderer, formatter: Formatter, side):
super().__init__(renderer, formatter)
self.side = side
def draw(self):
self.formatter.format_square(self.renderer.render_square(self.side))
if __name__ == '__main__':
square_black_white = Square(BlackAndWhiteRenderer(), DashedFormatter(), 10)
square_black_white.draw()
# Drawing a square with side 10
# Use dashed line to square
circle_colored = Circle(ColoredRenderer(), SolidFormatter(), 5)
circle_colored.draw()
# Coloring a circle with radius 5
# Use solid line to circle
```
### Section 09: Decorator
1. Python's functional decorators wrap functions, no direct relations to the GoF Decorator pattern
2. A decorator keeps the reference to the decorated object(s)
3. Adds utility attributes and methods to augment the object's feature
4. Proxying of underlying calls can be done dynamically (dynamic decorator)
5. May or may not forward calls to the underlying object (dynamic decorator)
Functional decorator ( no direct relations to the GoF Decorator pattern )
```python
import time
def time_it(func):
def wrapper():
start = time.time()
result = func()
end = time.time()
print(f"{func.__name__} took {int((end-start)*1000)} ms")
return result
return wrapper
@time_it
def some_op():
print('Start op')
time.sleep(1)
print('Done op')
return 123
if __name__ == "__main__":
some_op()
```
Class Decorator (keeps the reference to the decorated object(s) via **init**)
```python
from abc import ABC
class Shape(ABC):
def __str__(self):
return ''
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def resize(self, factor):
self.radius *= factor
def __str__(self):
return f"A circle of radius {self.radius}"
class Square(Shape):
def __init__(self, side):
self.side = side
def __str__(self):
return f"A square of radius {self.side}"
class ColoredShape(Shape):
def __init__(self, shape, color):
# prevent use same decorator twice on same underlying class
if isinstance(shape, ColoredShape):
raise Exception("Cannot apply same decorator twice")
self.shape = shape # always hold a reference to the underlying class
self.color = color
def __str__(self):
return f"{self.shape} of color {self.color}"
if __name__ == "__main__":
shape = ColoredShape(
Circle(100),
'Red'
)
print(shape) # A circle of radius 100 of color Red
```
Dynamic Decorator (Proxying of underlying calls can be done dynamically, by forward calls to the underlying object)
For example: in below code, use `__getattr__` magic method to forward calls to the underlying file object
```python
from io import TextIOWrapper
class FileWithLogging:
def __init__(self, file: TextIOWrapper):
self.file = file
def writelines(self, strings):
self.file.writelines(strings)
print(f'wrote {len(strings)} lines')
"""
Below we override getattr, setattr, and delattr method of FileWithLogging class,
to redirect IO operation to self.file
"""
# Python will call this method whenever you request an attribute that hasn't already been defined.
# But if the attribute does exist, __getattr__ won’t be invoked
def __getattr__(self, item):
print(f'__getattr__ invoked with item: {item}')
return getattr(self.__dict__['file'], item) # get file[item], eg: file.write, file.close
# Called when an attribute assignment is attempted
def __setattr__(self, key, value):
# print(f'__setattr__ invoked with key: {key}, value: {value}')
if key == 'file':
"""
If __setattr__() wants to assign to an instance attribute,
it should not simply execute self.name = value
this would cause a recursive call to itself.
Instead, it should insert the value in the dictionary of instance attributes,
e.g., self.__dict__[name] = value
"""
self.__dict__[key] = value
else:
setattr(self.__dict__['file'], key)
# Called when an attribute deletion is attempted.
def __delattr__(self, item):
delattr(self.__dict__['file'], item)
def __iter__(self):
return self.file.__iter__()
def __next__(self):
return self.file.__next__()
if __name__ == "__main__":
file = open("./hello.txt", "w")
file_with_logging = FileWithLogging(file)
file_with_logging.writelines([
"First line\n",
"Second line\n",
"Third line\n"
])
file_with_logging.write('testing last line.')
file_with_logging.close()
```
### Section 12: Proxy
1. A proxy has the same interface as the underlying object
2. To create a proxy, simply replicate the existing interface of an object
3. Add relevant functionality to the redefined member function
Protection proxy
```python
class ProtectedResource:
def __init__(self, user):
self.user = user
def secured_method(self):
print(self.user.name)
class User:
def __init__(self, name, auth_code):
self.name = name
self.auth_code = auth_code
class ProtectedResourceProxy:
def __init__(self, user):
self.user = user
def secured_method(self):
if self.user.auth_code != "my super secret auth code":
print("Invalid auth code")
return
print(self.user.name)
if __name__ == "__main__":
user = User("Jeremy", "my super secret auth code")
# Instead of calling ProtectedResource directly,
# now we call its proxy, which has added security logic
# resource = ProtectedResource(user)
resource = ProtectedResourceProxy(user)
resource.secured_method()
```
Virtual Proxy (Lazy)
```python
class Bitmap:
def __init__(self, filename):
print("Bitmap initialized")
self.filename = filename
def draw(self):
print(f"Start drawing bitmap loaded from {self.filename}")
class LazyBitmapProxy:
def __init__(self, filename):
self.filename = filename
self._instance = None
def draw(self):
if self._instance is None:
self._instance = Bitmap(self.filename)
print(f"Start drawing bitmap loaded from {self.filename}")
def draw_image(image):
print("About to draw image")
image.draw()
print("Done drawing image")
if __name__ == "__main__":
bmp = LazyBitmapProxy("emoji.png")
draw_image(bmp)
```
### Section 13: Chain of Responsibility
```py
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional
class Handler(ABC):
"""
The Handler interface declares a method for building the chain of handlers.
It also declares a method for executing a request.
"""
@abstractmethod
def set_next(self, handler: Handler) -> Handler:
pass
@abstractmethod
def handle(self, request) -> Optional[str]:
pass
class AbstractHandler(Handler):
"""
The default chaining behavior can be implemented inside a base handler
class.
"""
_next_handler: Handler = None
def set_next(self, handler: Handler) -> Handler:
self._next_handler = handler
# Returning a handler from here will let us link handlers in a
# convenient way like this:
# monkey.set_next(squirrel).set_next(dog)
return handler
@abstractmethod
def handle(self, request: Any) -> str:
if self._next_handler:
return self._next_handler.handle(request)
return None
"""
All Concrete Handlers either handle a request or pass it to the next handler in
the chain.
"""
class MonkeyHandler(AbstractHandler):
def handle(self, request: Any) -> str:
if request == "Banana":
return f"Monkey: I'll eat the {request}"
else:
return super().handle(request)
class SquirrelHandler(AbstractHandler):
def handle(self, request: Any) -> str:
if request == "Nut":
return f"Squirrel: I'll eat the {request}"
else:
return super().handle(request)
class DogHandler(AbstractHandler):
def handle(self, request: Any) -> str:
if request == "MeatBall":
return f"Dog: I'll eat the {request}"
else:
return super().handle(request)
def client_code(handler: Handler) -> None:
"""
The client code is usually suited to work with a single handler. In most
cases, it is not even aware that the handler is part of a chain.
"""
for food in ["Nut", "Banana", "Cup of coffee"]:
print(f"\nClient: Who wants a {food}?")
result = handler.handle(food)
if result:
print(f" {result}", end="")
else:
print(f" {food} was left untouched.", end="")
if __name__ == "__main__":
monkey = MonkeyHandler()
squirrel = SquirrelHandler()
dog = DogHandler()
monkey.set_next(squirrel).set_next(dog)
# The client should be able to send a request to any handler, not just the
# first one in the chain.
print("Chain: Monkey > Squirrel > Dog")
client_code(monkey)
print("\n")
print("Subchain: Squirrel > Dog")
client_code(squirrel)
```
### Section 21: Strategy
1. Define an algorithm at high level
2. Define the interface you expect each concrete strategy to follow
3. Provide for dynamic composition of strategies in the resulting object
```python
from abc import ABC
class FormatStrategy(ABC):
def start(self, buffer): pass
def text(self, buffer, item): pass
def end(self, buffer): pass
class MarkdownStrategy(FormatStrategy):
def text(self, buffer, item):
[ buffer.append(f' * {i}\n') for i in item ]
class HtmlStrategy(FormatStrategy):
def start(self, buffer):
buffer.append('<ul>\n')
def text(self, buffer, item):
[ buffer.append(f' <li>{i}</li>\n') for i in item ]
def end(self, buffer):
buffer.append('</ul>')
class TextProcessor:
def __init__(self, formatStrategy:FormatStrategy = MarkdownStrategy()):
self.buffer = []
self.formatStrategy = formatStrategy
def process(self, items: list):
self.formatStrategy.start(self.buffer)
self.formatStrategy.text(self.buffer, items)
self.formatStrategy.end(self.buffer)
def __str__(self):
return ''.join(self.buffer)
if __name__ == '__main__':
# textProcessor = TextProcessor()
textProcessor = TextProcessor(HtmlStrategy())
items = [
"First item",
"Second item",
"Third item"
]
textProcessor.process(items)
print(textProcessor)
```
<file_sep>import copy
class Address:
def __init__(self, suite, street_address, city):
self.street_address = street_address
self.suite = suite
self.city = city
def __str__(self):
return f"{self.suite}, {self.street_address}, {self.city}"
class Person:
def __init__(self, name, address):
self.name = name
self.address = address
def __str__(self):
return f"{self.name} lives @ {self.address}"
# create prototype
john = Person("John", Address('301', 'London Road', "Sydney"))
print(john)
# deep copy from prototype
jane = copy.deepcopy(john)
# then customize it
jane.name = 'Jane'
jane.address = copy.deepcopy(john.address)
jane.address.suite = '302'
jane.address.city = 'Melbourne'
print(jane)<file_sep>from math import cos, sin
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"x is {str(self.x)}, y is {str(self.y)}"
class PointFactory:
def new_cartesian_point(self, x, y):
return Point(x, y)
def new_polar_point(self, rho, theta):
return Point(rho * cos(theta), rho * sin(theta))
if __name__ == "__main__":
my_point = Point(2, 3)
my_point_factory = my_point.PointFactory()
p1 = my_point_factory.new_cartesian_point(my_point.x, my_point.y)
p2 = my_point_factory.new_polar_point(my_point.x, my_point.y)
print("with new_cartesian_point:", p1)
print("with new_polar_point:", p2)
<file_sep>from abc import ABC
from enum import Enum, auto
class HotDrink(ABC):
"""
Abstract class for concrete products(drinks)
"""
def consume(self):
pass
class Tea(HotDrink):
def consume(self):
print("This is a tea product")
class Coffee(HotDrink):
def consume(self):
print("This is a Coffee product")
class HotDrinkFactory(ABC):
"""
Abstract class for a family of factories
"""
def produce(self, amount):
pass
class TeaFactory(HotDrinkFactory):
def produce(self, amount=2):
print(f"{amount} {'cups' if amount > 1 else 'cup'} of Tea has been produced")
return Tea()
class CoffeeFactory(HotDrinkFactory):
def produce(self, amount=2):
print(f"{amount} {'cups' if amount > 1 else 'cup'} of Coffee has been produced")
return Coffee()
class Drinks(Enum):
TEA = auto()
COFFEE = auto()
if __name__ == "__main__":
target_product = "COFFEE"
if target_product not in Drinks.__members__:
raise ValueError(f"{target_product} is not supported product type.")
# capitalize first letter, lower remaining letters
# eg: 'COFFEE' to 'Coffee'
product_name = f"{target_product[0]}{target_product[1:].lower()}"
factory_name = f"{product_name}Factory"
factory_instance = eval(factory_name)()
product = factory_instance.produce()
print("product produced:", type(product))
<file_sep>class ProtectedResource:
def __init__(self, user):
self.user = user
def secured_method(self):
print(self.user.name)
class User:
def __init__(self, name, auth_code):
self.name = name
self.auth_code = auth_code
class ProtectedResourceProxy:
def __init__(self, user):
self.user = user
def secured_method(self):
if self.user.auth_code != "my super secret auth code":
print("Invalid auth code")
return
print(self.user.name)
if __name__ == "__main__":
user = User("Jeremy", "my super secret auth code")
# Instead of calling ProtectedResource directly,
# now we call its proxy, which has added security logic
# resource = ProtectedResource(user)
resource = ProtectedResourceProxy(user)
resource.secured_method()
<file_sep>class Bitmap:
def __init__(self, filename):
print("Bitmap initialized")
self.filename = filename
def draw(self):
print(f"Start drawing bitmap loaded from {self.filename}")
class LazyBitmapProxy:
def __init__(self, filename):
self.filename = filename
self._instance = None
def draw(self):
if self._instance is None:
self._instance = Bitmap(self.filename)
print(f"Start drawing bitmap loaded from {self.filename}")
def draw_image(image):
print("About to draw image")
image.draw()
print("Done drawing image")
if __name__ == "__main__":
bmp = LazyBitmapProxy("emoji.png")
draw_image(bmp)
"""
OUTPUT:
About to draw image
Bitmap initialized
Start drawing bitmap loaded from emoji.png
Done drawing image
"""
<file_sep># line type: solid, dashed
# color: colored, black & white
# shape: circle, square
from abc import ABC
class Formatter(ABC):
def format_circle(self, str): pass
def format_square(self, str): pass
class DashedFormatter(Formatter):
def format_circle(self, str):
print(f'Use dashed line to circle')
def format_square(self, str):
print(f'Use dashed line to square')
class SolidFormatter(Formatter):
def format_circle(self, radius):
print(f'Use solid line to circle')
def format_square(self, side):
print(f'Use solid line to square')
class Renderer(ABC):
def render_circle(self, radius): pass
def render_square(self, side): pass
class ColoredRenderer(Renderer):
def render_circle(self, radius):
print(f'Coloring a circle with radius {radius}')
def render_square(self, side):
print(f'Coloring a square with side {side}')
class BlackAndWhiteRenderer(Renderer):
def render_circle(self, radius):
print(f'Drawing a circle with radius {radius}')
def render_square(self, side):
print(f'Drawing a square with side {side}')
class Shape:
"""
Base class for all subtypes of shapes
"""
def __init__(self, renderer: Renderer, formatter: Formatter):
self.renderer = renderer
self.formatter = formatter
def draw(self): pass
class Circle(Shape):
def __init__(self, renderer: Renderer, formatter: Formatter, radius):
super().__init__(renderer, formatter)
self.radius = radius
def draw(self):
self.formatter.format_circle(self.renderer.render_circle(self.radius))
class Square(Shape):
def __init__(self, renderer: Renderer, formatter: Formatter, side):
super().__init__(renderer, formatter)
self.side = side
def draw(self):
self.formatter.format_square(self.renderer.render_square(self.side))
if __name__ == '__main__':
square_black_white = Square(BlackAndWhiteRenderer(), DashedFormatter(), 10)
square_black_white.draw()
# Drawing a square with side 10
# Use dashed line to square
circle_colored = Circle(ColoredRenderer(), SolidFormatter(), 5)
circle_colored.draw()
# Coloring a circle with radius 5
# Use solid line to circle<file_sep>import copy
class Address:
def __init__(self, suite, street_address, city):
self.street_address = street_address
self.suite = suite
self.city = city
def __str__(self):
return f"{self.suite}, {self.street_address}, {self.city}"
class Employee:
def __init__(self, name, address):
self.name = name
self.address = address
def __str__(self):
return f"{self.name} works @ {self.address}"
class EmployeeFactory:
# setup 2 prototypes to be used
syndey_office_emp_proto = Employee('', Address('001', "Main street", "Sydney"))
melbourne_office_emp_proto = Employee('', Address('500', "Kings street", "Melbourne"))
@staticmethod
# Used for deep copy a prototype, then customize it
def __new_employee(proto, name):
new_emp = copy.deepcopy(proto)
new_emp.name = name
return new_emp
@staticmethod
def new_sydney_employee(name):
return EmployeeFactory.__new_employee(EmployeeFactory.syndey_office_emp_proto, name)
@staticmethod
def new_melbourne_employee( name):
return EmployeeFactory.__new_employee(EmployeeFactory.melbourne_office_emp_proto, name)
john = EmployeeFactory.new_sydney_employee("John")
jane = EmployeeFactory.new_melbourne_employee("Jane")
print(john)
print(jane)<file_sep>from abc import ABC
class Shape(ABC):
def __str__(self):
return ''
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def resize(self, factor):
self.radius *= factor
def __str__(self):
return f"A circle of radius {self.radius}"
class Square(Shape):
def __init__(self, side):
self.side = side
def __str__(self):
return f"A square of radius {self.side}"
class ColoredShape(Shape):
def __init__(self, shape, color):
# prevent use same decorator twice on same underlying class
if isinstance(shape, ColoredShape):
raise Exception("Cannot apply same decorator twice")
self.shape = shape # always hold a reference to the underlying class
self.color = color
def __str__(self):
return f"{self.shape} of color {self.color}"
if __name__ == "__main__":
shape = ColoredShape(
Circle(100),
'Red'
)
print(shape) # A circle of radius 100 of color Red
# shape2 = ColoredShape(
# shape,
# 'Red'
# ) # Exception: Cannot apply same decorator twice
<file_sep>from io import TextIOWrapper
class FileWithLogging:
def __init__(self, file: TextIOWrapper):
self.file = file
def writelines(self, strings):
self.file.writelines(strings)
print(f'wrote {len(strings)} lines')
"""
Below we override getattr, setattr, and delattr method of FileWithLogging class,
to redirect IO operation to self.file
"""
# Python will call this method whenever you request an attribute that hasn't already been defined.
# But if the attribute does exist, __getattr__ won’t be invoked
def __getattr__(self, item):
print(f'__getattr__ invoked with item: {item}')
return getattr(self.__dict__['file'], item) # get file[item], eg: file.write, file.close
# Called when an attribute assignment is attempted
def __setattr__(self, key, value):
# print(f'__setattr__ invoked with key: {key}, value: {value}')
if key == 'file':
"""
If __setattr__() wants to assign to an instance attribute,
it should not simply execute self.name = value
this would cause a recursive call to itself.
Instead, it should insert the value in the dictionary of instance attributes,
e.g., self.__dict__[name] = value
"""
self.__dict__[key] = value
else:
setattr(self.__dict__['file'], key)
# Called when an attribute deletion is attempted.
def __delattr__(self, item):
delattr(self.__dict__['file'], item)
def __iter__(self):
return self.file.__iter__()
def __next__(self):
return self.file.__next__()
if __name__ == "__main__":
file = open("./hello.txt", "w")
file_with_logging = FileWithLogging(file)
file_with_logging.writelines([
"First line\n",
"Second line\n",
"Third line\n"
])
file_with_logging.write('testing last line.')
file_with_logging.close()<file_sep>from abc import ABC
class FormatStrategy(ABC):
def start(self, buffer): pass
def text(self, buffer, item): pass
def end(self, buffer): pass
class MarkdownStrategy(FormatStrategy):
def text(self, buffer, item):
[ buffer.append(f' * {i}\n') for i in item ]
class HtmlStrategy(FormatStrategy):
def start(self, buffer):
buffer.append('<ul>\n')
def text(self, buffer, item):
[ buffer.append(f' <li>{i}</li>\n') for i in item ]
def end(self, buffer):
buffer.append('</ul>')
class TextProcessor:
def __init__(self, formatStrategy:FormatStrategy = MarkdownStrategy()):
self.buffer = []
self.formatStrategy = formatStrategy
def process(self, items: list):
self.formatStrategy.start(self.buffer)
self.formatStrategy.text(self.buffer, items)
self.formatStrategy.end(self.buffer)
def __str__(self):
return ''.join(self.buffer)
if __name__ == '__main__':
# textProcessor = TextProcessor()
textProcessor = TextProcessor(HtmlStrategy())
items = [
"First item",
"Second item",
"Third item"
]
textProcessor.process(items)
print(textProcessor) | 2c873e381e832e594080120679f3935d31cb3a9a | [
"Markdown",
"Python"
] | 12 | Python | xndong1020/design_pattern_python | 68b426f51ea7821928694ca038ca59208383bb9a | 91e20ea043c4fd772bc4ea4503e0abf0f9e7c070 |
refs/heads/main | <file_sep>from tkinter import *
import tkinter as tk
import random
def btn_click(event):
l1.config(text=random.randint(1,1001))
l2.config(text=random.randint(1,1001))
l3.config(text=random.randint(1,1001))
root = Tk()
#root['bg']='#000000'
root.title("однорукий бандит")
root.geometry('200x200')
root.resizable(width=False,height=False)
btn1=tk.Button(root,text='кнопка',bg="#708090",activebackground='#000000',font=("Verdana", 13))
root.bind('<Button-1>', btn_click)
btn1.pack()
l1 = Label(text=random.randint(1,1001), font="Arial 14")
l2 = Label(text=random.randint(1,1001),font="Arial 14")
l3 = Label(text=random.randint(1,1001),font="Arial 14")
l1.pack()
l2.pack()
l3.pack()
root.mainloop()
| 68c005eea5fc28718fca5d8e4c95caa9a8031e76 | [
"Python"
] | 1 | Python | error50592/homework | 8f00186c2d11a2bd9c19e1efed04fd05607f24e7 | 13d3a5655a81d7f2b6bb18f1c78cae57f34ed0d7 |
refs/heads/master | <file_sep>from __future__ import absolute_import, print_function
import unittest
import six
import schema_salad
from schema_salad.avro.schema import Names
from schema_salad.schema import load_and_validate, load_schema
from schema_salad.validate import ValidationException
from .util import get_data
class TestErrors(unittest.TestCase):
def test_errors(self):
document_loader, avsc_names, schema_metadata, metaschema_loader = load_schema(
get_data(u"tests/test_schema/CommonWorkflowLanguage.yml"))
for t in ("test_schema/test1.cwl",
"test_schema/test2.cwl",
"test_schema/test3.cwl",
"test_schema/test4.cwl",
"test_schema/test5.cwl",
"test_schema/test6.cwl",
"test_schema/test7.cwl",
"test_schema/test8.cwl",
"test_schema/test9.cwl",
"test_schema/test10.cwl",
"test_schema/test11.cwl",
"test_schema/test15.cwl"):
with self.assertRaises(ValidationException):
try:
load_and_validate(document_loader, avsc_names,
six.text_type(get_data("tests/"+t)), True)
except ValidationException as e:
print("\n", e)
raise
@unittest.skip("See https://github.com/common-workflow-language/common-workflow-language/issues/734")
def test_errors_previously_defined_dict_key(self):
document_loader, avsc_names, schema_metadata, metaschema_loader = load_schema(
get_data(u"tests/test_schema/CommonWorkflowLanguage.yml"))
for t in ("test_schema/test12.cwl",
"test_schema/test13.cwl",
"test_schema/test14.cwl"):
with self.assertRaises(ValidationException):
try:
load_and_validate(document_loader, avsc_names,
six.text_type(get_data("tests/"+t)), True)
except ValidationException as e:
print("\n", e)
raise
def test_bad_schema(self):
self.assertEqual(1, schema_salad.main.main(
argsl=[get_data("tests/bad_schema.yml")]))
self.assertEqual(1, schema_salad.main.main(
argsl=["--print-avro", get_data("tests/bad_schema.yml")]))
def test_bad_schema2(self):
self.assertEqual(1, schema_salad.main.main(
argsl=[get_data("tests/bad_schema2.yml")]))
<file_sep>typing==3.6.4 ; python_version < "3.7"
ruamel.yaml>=0.12.4, <= 0.15.77
rdflib==4.2.2
rdflib-jsonld==0.4.0
mistune>=0.8.1,<0.9
CacheControl==0.11.7
lockfile==0.12.2
<file_sep>|Build Status| |Build status|
.. |Build Status| image:: https://img.shields.io/travis/common-workflow-language/schema_salad/master.svg?label=unix%20build
:target: https://travis-ci.org/common-workflow-language/schema_salad
.. |Build status| image:: https://img.shields.io/appveyor/ci/mr-c/schema-salad/master.svg?label=windows%20build
:target: https://ci.appveyor.com/project/mr-c/schema-salad/branch/master
.. |Code coverage| image:: https://codecov.io/gh/common-workflow-language/schema_salad/branch/master/graph/badge.svg
:target: https://codecov.io/gh/common-workflow-language/schema_salad
Schema Salad
------------
Salad is a schema language for describing JSON or YAML structured
linked data documents. Salad schema describes rules for
preprocessing, structural validation, and hyperlink checking for
documents described by a Salad schema. Salad supports rich data
modeling with inheritance, template specialization, object
identifiers, object references, documentation generation, code
generation, and transformation to RDF_. Salad provides a bridge
between document and record oriented data modeling and the Semantic
Web.
Usage
-----
::
$ pip install schema_salad
To install from source::
git clone https://github.com/common-workflow-language/schema_salad
cd schema_salad
python setup.py install
Commands
--------
Schema salad can be used as a command line tool or imported as a Python module::
$ schema-salad-tool
usage: schema-salad-tool [-h] [--rdf-serializer RDF_SERIALIZER]
[--print-jsonld-context | --print-rdfs | --print-avro | --print-rdf | --print-pre | --print-index | --print-metadata | --print-inheritance-dot | --print-fieldrefs-dot | --codegen language | --print-oneline]
[--strict | --non-strict] [--verbose | --quiet | --debug] [--version]
[schema] [document]
$ python
>>> import schema_salad
Validate a schema::
$ schema-salad-tool myschema.yml
Validate a document using a schema::
$ schema-salad-tool myschema.yml mydocument.yml
Get JSON-LD context::
$ schema-salad-tool --print-jsonld-context myschema.yml mydocument.yml
Convert a document to JSON-LD::
$ schema-salad-tool --print-pre myschema.yml mydocument.yml > mydocument.jsonld
Generate Python classes for loading/generating documents described by the schema::
$ schema-salad-tool --codegen=python myschema.yml > myschema.py
Display inheritance relationship between classes as a graphviz 'dot' file and render as SVG::
$ schema-salad-tool --print-inheritance-dot myschema.yml | dot -Tsvg > myschema.svg
Documentation
-------------
See the specification_ and the metaschema_ (salad schema for itself). For an
example application of Schema Salad see the Common Workflow Language_.
Rationale
---------
The JSON data model is an popular way to represent structured data. It is
attractive because of it's relative simplicity and is a natural fit with the
standard types of many programming languages. However, this simplicity comes
at the cost that basic JSON lacks expressive features useful for working with
complex data structures and document formats, such as schemas, object
references, and namespaces.
JSON-LD is a W3C standard providing a way to describe how to interpret a JSON
document as Linked Data by means of a "context". JSON-LD provides a powerful
solution for representing object references and namespaces in JSON based on
standard web URIs, but is not itself a schema language. Without a schema
providing a well defined structure, it is difficult to process an arbitrary
JSON-LD document as idiomatic JSON because there are many ways to express the
same data that are logically equivalent but structurally distinct.
Several schema languages exist for describing and validating JSON data, such as
JSON Schema and Apache Avro data serialization system, however none
understand linked data. As a result, to fully take advantage of JSON-LD to
build the next generation of linked data applications, one must maintain
separate JSON schema, JSON-LD context, RDF schema, and human documentation,
despite significant overlap of content and obvious need for these documents to
stay synchronized.
Schema Salad is designed to address this gap. It provides a schema language
and processing rules for describing structured JSON content permitting URI
resolution and strict document validation. The schema language supports linked
data through annotations that describe the linked data interpretation of the
content, enables generation of JSON-LD context and RDF schema, and production
of RDF triples by applying the JSON-LD context. The schema language also
provides for robust support of inline documentation.
.. _JSON-LD: http://json-ld.org
.. _Avro: http://avro.apache.org
.. _metaschema: https://github.com/common-workflow-language/schema_salad/blob/master/schema_salad/metaschema/metaschema.yml
.. _specification: http://www.commonwl.org/v1.0/SchemaSalad.html
.. _Language: https://github.com/common-workflow-language/common-workflow-language/blob/master/v1.0/CommandLineTool.yml
.. _RDF: https://www.w3.org/RDF/
| caf6639117cdbaa063ddd93b235f92934c80ce2a | [
"Python",
"Text",
"reStructuredText"
] | 3 | Python | genenetwork/schema_salad | eb85c3d49b99b7643e8a12248e2dc05504910c1e | e40619e1a70b4ecf2207eb2175296bf7c544e862 |
refs/heads/master | <file_sep>import cv2
import numpy as np
def transform(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
myFrom = np.float32([
[1042, 406],
[1299, 406],
[903, 791],
[356, 790],
])
sL = 40
tW = 2000
tH = 2000
myTo = np.float32([
[tW/2 - 3*sL, tH/2 - 20*sL],
[tW/2 + 3*sL, tH/2 - 20*sL],
[tW/2 + 3*sL, tH/2 + 20*sL],
[tW/2 - 3*sL, tH/2 + 20*sL],
])
tMat = cv2.getPerspectiveTransform(myFrom,myTo)
dst = cv2.warpPerspective(img, tMat, (tW, tH))
return (tMat, dst)
<file_sep>bokeh==0.12.11
Flask==0.12.2
numpy==1.13.3
<file_sep>import cv2
import os
import numpy as np
from transformation import transform
# import matplotlib.pyplot as plt
FRAMES_FOR_SPEED = 1
SPEED_SCALING_FACTOR = 0.06818181804 # miles per hour
MIN_CENTROID_Y = 0
MAX_CENTROID_Y = 800
MILES_PER_160_FEET = 0.030303
LANE_LINES = [880, 1000, 1120]
def calc_euclidean_distance(current_center, previous_center):
x1, y1 = current_center
x2, y2 = previous_center
return ((x1 - x2) ** 2 + (y2 - y1) ** 2) ** 0.5
def get_density_of_cars(centers):
return len(centers)/MILES_PER_160_FEET
def match_centers_across_frames(raw_current_frame_centers, raw_previous_frame_centers, transformed_current_frame_centers, transformed_previous_frame_centers):
# import ipdb; ipdb.set_trace()
if len(transformed_current_frame_centers) == 0 or len(transformed_previous_frame_centers) == 0 or len(raw_current_frame_centers) == 0:
return {}
numCurrent = len(transformed_current_frame_centers[0])
numPrev = len(transformed_previous_frame_centers[0])
center_correspondence_map = dict.fromkeys(range(numCurrent))
exhausted_centers = set([])
raw_parametrized_direction = None
transformed_parametrized_direction = None
for i in range(numCurrent):
# start distance at inf
curr_min_dist = float('inf')
exhausted_center_index = None
for j in range(numPrev):
if j != exhausted_center_index:
# get euclidean distance
distance = calc_euclidean_distance(transformed_current_frame_centers[0][i], transformed_previous_frame_centers[0][j])
if curr_min_dist > distance:
curr_min_dist = distance
exhausted_center_index = j
xRc, yRc = raw_current_frame_centers[0][i]
xRp, yRp = raw_previous_frame_centers[0][j]
raw_parametrized_direction = (xRc - xRp, yRc - yRp)
xTc, yTc = transformed_current_frame_centers[0][i]
xTp, yTp = transformed_previous_frame_centers[0][j]
transformed_parametrized_direction = (xTc - xTp, yTc - yTp)
if raw_parametrized_direction and transformed_parametrized_direction:
#TODO: Apply scaling factor to adjust speed
center_correspondence_map[i] = (raw_current_frame_centers[0][i], transformed_current_frame_centers[0][i], curr_min_dist * 30.0/FRAMES_FOR_SPEED * SPEED_SCALING_FACTOR, raw_parametrized_direction, transformed_parametrized_direction) # this is the speed in pixels per second
# remove the center from the remaining previous_frame_center candidates
if exhausted_center_index:
# transformed_previous_frame_centers.pop(exhausted_center_index)
exhausted_centers.add(exhausted_center_index)
return center_correspondence_map
def transformToBirdsEye(raw_centers, transformation_matrix, preview = False):
# generate output canvas
# apply t_mat to the centers
if not raw_centers:
return []
transformed_centers = cv2.perspectiveTransform(np.array([raw_centers], dtype=float), transformation_matrix)
return transformed_centers
def main():
# Open the video
capture = cv2.VideoCapture('big_files/final.mp4')
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
# if the output mp4 already exists, delete it
try:
os.remove('outputs/output.mp4')
except:
pass
# create a new output mp4
video = cv2.VideoWriter('outputs/output.mp4', fourcc, 30.0, size)
fgbg = cv2.createBackgroundSubtractorMOG2(varThreshold=100, detectShadows=False)
detector = cv2.SimpleBlobDetector_create()
# background image we're doing right
background = cv2.imread('big_files/background.png', 0)
# background = cv2.cvtColor(background, cv2.COLOR_BGR2GRAY)
# open transformation calibration checkerboard image
checkerboard_image = cv2.imread('betterCheckb.png')
# calculate transformation matrix
transformation_matrix, _ = transform(checkerboard_image)
transformed_background = cv2.warpPerspective(background, transformation_matrix, (2000, 2000))
# draw lane lines on background
for l in LANE_LINES:
cv2.line(transformed_background, (l, 0), (l, 2000), (0, 0, 0), 3)
# keep a cache of the previous frame centers
transformed_previous_frame_centers = []
raw_previous_frame_centers = []
frame_count = 0
# preview settings
bird_eye_preview = True
blob_preview = False
# loop through frames of video
while True:
# capture current frame in video
ret, img = capture.read()
if ret == True:
if frame_count % FRAMES_FOR_SPEED == 0:
# birds-eye
if bird_eye_preview: transformed_output = transformed_background.copy()
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# transformed_image = transform(imgray)
# use the background subtractor
fgbg.apply(background)
fgmask = fgbg.apply(imgray)
# Pre processing, which includes blurring the image and thresholding
threshold = 10
fgmask = cv2.GaussianBlur(fgmask, (29, 29), 0)
ret, thresh = cv2.threshold(fgmask, threshold, 255, cv2.THRESH_BINARY)
if blob_preview: cv2.imshow('blobs', thresh)
# Get the contours for the thresholded image
im2, cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
blob_area_threshold = 700 # minimum size of blob in order to be considered a vehicle
raw_current_frame_centers = [] # will contain a list of the centroids of moving vehicles on raw footage
transformed_current_frame_centers = []
# loop over the contours
for c in cnts:
area = cv2.contourArea(c) # getting blob area to threshold
# compute the center of the contour
if area > blob_area_threshold:
# import ipdb; ipdb.set_trace()
M = cv2.moments(c)
# prevent divide by zer0
if M["m00"] != 0.0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
centers_xy_coordinates = (cX, cY)
transformed_xy_coordinates = transformToBirdsEye([centers_xy_coordinates], transformation_matrix)
# import ipdb; ipdb.set_trace()
tX, tY = transformed_xy_coordinates[0][0]
if tX >= LANE_LINES[0] and tX <= LANE_LINES[-1] and tY > 100 and tY < 1900:
raw_current_frame_centers.append(centers_xy_coordinates)
transformed_current_frame_centers.append([tX, tY])
# draw the contour and center of the shape on the image
cv2.drawContours(img, [c], -1, (0, 0, 204), 2)
cv2.circle(img, (cX, cY), 7, (0, 0, 204), -1)
transformed_current_frame_centers = np.array([transformed_current_frame_centers])
# birds-eye
if bird_eye_preview and len(transformed_current_frame_centers) > 0:
for x, y in transformed_current_frame_centers[0]:
cv2.circle(transformed_output, (int(x), int(y)), 10, (0, 0, 0), -1)
car_map = match_centers_across_frames([raw_current_frame_centers],
[raw_previous_frame_centers],
transformed_current_frame_centers,
transformed_previous_frame_centers) # need to return velocities of vehicles (speed + direction)
# put velocities on the original image
for key in car_map:
if car_map[key] == None: continue
raw_center, transformed_center, speed, raw_parametrized_direction, transformed_parametrized_direction = car_map[key]
r_cX, r_cY = raw_center
r_Dx, r_Dy = raw_parametrized_direction
t_cX, t_cY = transformed_center
t_Dx, t_Dy = transformed_parametrized_direction
if speed != float('inf'):
cv2.putText(img, "{0} mph".format(round(speed)), (r_cX - 20, r_cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 100), 2)
cv2.arrowedLine(img, (r_cX, r_cY), (int(r_cX + r_Dx), int(r_cY + r_Dy)), (0,0,100),2)
# birds-eye
if bird_eye_preview: cv2.arrowedLine(transformed_output, (int(t_cX), int(t_cY)), (int(t_cX + t_Dx), int(t_cY + t_Dy)), (0,0,0),2)
transformed_previous_frame_centers = transformed_current_frame_centers
raw_previous_frame_centers = raw_current_frame_centers
cv2.imshow("original footage with blob/centroid", img)
# birds-eye
if bird_eye_preview: cv2.imshow('birds-eye', transformed_output)
frame_count += 1
if (cv2.waitKey(27) != -1):
break
capture.release()
video.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
<file_sep>from bokeh.plotting import figure
class LineGraph():
"""
LineGraph
A simple wrapper for creating a plot and drawing lines on it.
title - title of the graph
xlabel - x axis label
ylabel - y axis label
width - width of the graph
height - height of the graph
"""
def __init__(self, title="", xlabel="", ylabel="", width=700, height=600):
self.plot = figure(plot_width=width, plot_height=height)
def drawLine(self, xdata, ydata, color='black'):
self.plot.line(xdata, ydata, line_width=2)
def draw(self):
return self.plot
<file_sep>import plotly as py
import plotly.graph_objs as go
import pickle
import numpy as np
from scipy import interpolate
def plot_logs():
try:
log_attributes = pickle.load(open("log_attributes_finished.p", "rb"))
except:
log_attributes = pickle.load(open("log_attributes.p", "rb"))
flow_y = list(range(0, len(log_attributes["flow_timestamps"])))
#TODO: Figure out how to add titles to the graphs
# 2d plot
densities = go.Scatter(
x=log_attributes["timestamps"],
y=log_attributes["num_vehicles"],
name="Density"
)
# 2d plot
flow = go.Scatter(
x=log_attributes["flow_timestamps"],
y=flow_y,
xaxis='x2',
yaxis='y2',
name="Flow"
)
# 3d plot processing
time_vs_offset_vs_speed_data = go.Scatter3d(
x=log_attributes['timestamps'], y=log_attributes['average_offset'], z=log_attributes['average_speed'],
marker=dict(
size=5,
color=log_attributes['average_speed'],
colorscale='Viridis', # choose a colorscale
opacity=0.8
),
scene='scene1',
# surfaceaxis=2,
# surfacecolor='red'
name="Offset vs Speed"
)
time_vs_offset_vs_density_data = go.Scatter3d(
x=log_attributes['timestamps'], y=log_attributes['average_offset'], z=log_attributes['num_vehicles'],
marker=dict(
size=5,
color=log_attributes['num_vehicles'],
# colorscale='Viridis', # choose a colorscale
opacity=0.8
),
scene='scene2',
# surfaceaxis=2,
# surfacecolor='red',
name="Offset vs Density"
)
data = [flow, densities, time_vs_offset_vs_speed_data, time_vs_offset_vs_density_data] #, time_vs_speed_vs_density_data]
layout = go.Layout(
xaxis=dict(
domain=[0, 0.45],
title='Time (s)'
),
yaxis=dict(
domain=[0, -0.45],
title='Number of Flowed Cars'
),
xaxis2=dict(
domain=[0.55, 1],
title='Time (s)'
),
yaxis2=dict(
domain=[0, -0.45],
anchor='x2',
title='Density of Cars (160ft)'
),
scene1=dict(
domain=dict(
x=[0, 0.45],
y=[0.45, 0],
),
xaxis=dict(
title='Time (s)'),
yaxis=dict(
title='Offset (ft)'),
zaxis=dict(
title='Speed (mph)'),
),
scene2=dict(
domain=dict(
x=[-1, -1],
y=[1, 0],
),
xaxis=dict(
title='Time (s)'),
yaxis=dict(
title='Offset (ft)'),
zaxis=dict(
title='Density (vehicles/160 ft)'),
)
)
fig = go.Figure(data=data, layout=layout)
py.offline.plot(fig, filename='density_offset_graphs.html')
plot3d('timestamps', 'average_offset', 'average_speed', log_attributes, 'speed_vs_offset')
plot3d('timestamps', 'num_vehicles', 'average_speed', log_attributes, 'speed_vs_density')
def plot3d(x_label, y_label, z_label, log_attributes, outputname):
x = log_attributes[x_label]
y = log_attributes[y_label]
z = log_attributes[z_label]
# import ipdb; ipdb.set_trace()
x = np.round(np.asarray(x))
y = np.round(np.asarray(y))
z = np.asarray(z)
z_data_func = interpolate.interp2d(x, y, z, kind='cubic')
xnew = np.arange(0, max(x), 1)
ynew = np.arange(0, max(y), 1)
znew = z_data_func(xnew, ynew)
data = [
go.Surface(
z=znew
)
]
layout = go.Layout(
title=outputname,
autosize=False,
width=500,
height=500,
margin=dict(
l=0,
r=0,
b=0,
t=0
),
scene=dict(
xaxis=dict(
title=x_label
),
yaxis=dict(
title=y_label
),
zaxis = dict(
title=z_label
)
)
)
time_vs_offset_vs_speed_data = go.Figure(data=data, layout=layout)
# py.offline.plot(time_vs_offset_vs_speed_data)
py.offline.plot(time_vs_offset_vs_speed_data, filename='{0}.html'.format(outputname))
def main():
pass
if __name__ == '__main__':
plot_logs()
<file_sep>import numpy as np
from background_subtractor import SPEED_SCALING_FACTOR, FRAMES_FOR_SPEED, calc_euclidean_distance
from statistics import stdev, mean, median
SPEED_SCALING_FACTOR = 0.06818181804
FRAMES_FOR_SPEED = 1
EXIT_LINE = 1800
# FLOW_TRANSFORMED_LINES = np.array([1800, 1300])
class Car:
def __init__(self, car_id, raw_center, transformed_center, contour):
self.transformed_velocities = [] # (speed, previous_position, current_position)
self.raw_velocities = []
self.raw_centers = [raw_center] # (rX, rY)
self.transformed_centers = [transformed_center] # (tX, tY)
self.car_id = car_id # #
self.contours = [contour] # contour object from opencv
self.updated = True
def get_latest_transformed_velocity(self):
'''
:return: (speed, previous_center, current_center) tuple of transformed velocities palatable for drawing arrows
'''
return self.transformed_velocities[-1] if self.transformed_velocities else (-1, None, None)
def get_latest_raw_velocity(self):
'''
:return: (speed, previous_center, current_center) tuple of raw velocities palatable for drawing arrows
'''
return self.raw_velocities[-1] if self.raw_velocities else (-1, None, None)
def get_latest_raw_center(self):
'''
:return: (x, y) of the latest raw center of a car
'''
return self.raw_centers[-1] if self.raw_centers else (-1, -1)
def get_latest_transformed_center(self):
'''
:return: (x, y) of the latest transformed center of a car
'''
return self.transformed_centers[-1] if self.transformed_centers else (-1, -1)
def get_latest_contour(self):
'''
:return: OpenCV object containing the latest contour of the car
'''
return self.contours[-1] if self.contours else None
def update_contour(self, contour):
'''
:param contour: Newest contour
:return: None
'''
self.contours.append(contour)
def update_raw_and_transformed_positions(self, raw_center, transformed_center): # (x, y)
'''
Updates raw centers, transformed, centers, and latest transformed velocities
:param raw_center: (x, y) of the newest raw center
:param transformed_center: (x, y) of the newest transformed center
:return: None
'''
# add position to positions and add velocities
real_speed = self._calculate_speed(self.transformed_centers[-1], transformed_center)
average_speed = self._calculate_interpolated_speed(real_speed)
previous_transformed_center = self.transformed_centers[-1]
previous_raw_center = self.raw_centers[-1]
self.transformed_velocities.append((average_speed, previous_transformed_center, transformed_center))
self.raw_velocities.append((average_speed, previous_raw_center, raw_center))
self.transformed_centers.append(transformed_center)
self.raw_centers.append(raw_center)
def _calculate_speed(self, center_1, center_2):
return calc_euclidean_distance(center_1, center_2) * 30.0/FRAMES_FOR_SPEED * SPEED_SCALING_FACTOR # speed in mph
def _calculate_interpolated_speed(self, real_speed, NUM_STANDARD_DEVIATIONS=1):
if len(self.transformed_velocities) >= 10:
last_few_velocities = [tv[0] for tv in self.transformed_velocities[-10:]]
last_few_velocities.append(real_speed)
std = stdev(last_few_velocities)
avg = mean(last_few_velocities)
average_velocity = median([speed for speed in last_few_velocities if
(avg + NUM_STANDARD_DEVIATIONS * std) > speed > (
avg - NUM_STANDARD_DEVIATIONS * std)])
return average_velocity
else:
return real_speed
def get_car_id(self):
return self.car_id
### For Logging ###
def log_details(self):
'''
:return: str((car_id, transformed_centers (feet), transformed_velocities (mph))) tuple to be used for visualizations.
All values are in real world units.
'''
transformed_centers_in_feet = [(x/10, y/10) for x,y in self.transformed_centers]
return self.car_id, transformed_centers_in_feet, self.transformed_velocities
def __repr__(self):
return 'ID: {0}\nPositions\n\t{1}\nVelocities\n\t{2}'.format(self.car_id,
[(round(x), round(y))for x,y in self.transformed_centers],
[round(v[0]) for v in self.transformed_velocities])
<file_sep>import cv2
img = cv2.imread('big_files/HFOUG.jpg',cv2.IMREAD_GRAYSCALE)
_,img = cv2.threshold(img,0,255,cv2.THRESH_OTSU)
h, w = img.shape[:2]
contours0, hierarchy, _ = cv2.findContours( img.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
moments = [cv2.moments(cnt) for cnt in contours0]
# Nota Bene: I rounded the centroids to integer.
centroids = []
for m in moments:
if m['m00'] != 0:
centroids.append((int(round(m['m10']/m['m00'])),int(round(m['m01']/m['m00']))))
# centroids = [( int(round(m['m10']/m['m00'])),int(round(m['m01']/m['m00'])) ) for m in moments]
print('cv2 version:', cv2.__version__)
print('centroids:', centroids)
for c in centroids:
# I draw a black little empty circle in the centroid position
cv2.circle(img,c,5,(0,0,0))
cv2.imshow('image', img)
0xFF & cv2.waitKey(27)
cv2.destroyAllWindows()
<file_sep>
# import plotly
# from plotly.graph_objs import Scatter, Layout
# plotly.offline.plot({
# "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
# "layout": Layout(title="hello world")
# })
import pandas as pd
import plotly
import plotly.graph_objs as go
# Read data from a csv
z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv')
data = [
go.Surface(
z=z_data.as_matrix()
)
]
layout = go.Layout(
title='Mt Bruno Elevation',
autosize=False,
width=500,
height=500,
margin=dict(
l=65,
r=50,
b=65,
t=90
)
)
# plotly.offline.plot({
# "data": [Scatter(x=[1, 2, 3, 4], y=[4, 3, 2, 1])],
# "layout": Layout(title="hello world")
# })
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='elevations-3d-surface')<file_sep># image-processing-sci
GT Smart City Infrastructure's Image Processing Team (Docker)
This repository contains our code for processing the videos provided by the Smart City Infrastructure team.
Note: This repository doesn't contain any proprietary information/videos. For those, please email Cibi, Dr. Tsai, or Anirban
# Getting Started
1) Clone this repository (note if you're using ssh you should set up your keys by following the directions [here](https://help.github.com/articles/connecting-to-github-with-ssh/))
`git clone git@github.com:image-processing-sci/image-processing-sci.git` or `git clone https://github.com/image-processing-sci/image-processing-sci.git`
2) Open up the repository in terminal.
3) Create folder called `big_files`.
4) Place a video called `final.mp4` in `big_files` and the `background.png` image.
5) In the root of the folder, use the following command to get up and running
`python3 traffic_params.py`
Voila, you should see some windows of the processed videos.
6) To stop the video, simply hit the space bar. The script will autogenerate html pages to display the results. Since these pages are stored on the drive, you can also see them without having to run the main script every time. For this, use the following command:
`python3 graphview/graphview.py`
# Contributing
We follow the standard industry process of contribution. If you make a change to a file, and want to merge it, you will need to open up a pull request.
Here's how to do it:
1) Make a change to a file
2) `git add .`
3) `git commit -m "<your commit message>"`
4) `git push origin master:YOUR_BRANCH_NAME`
5) Navigate back to the github page, link [here](https://github.com/image-processing-sci/image-processing-sci) for convenience.
6) You should see an option to open up a pull request. Use that button and write in some details about what you changed.
7) After submitting the pull request, we run a few tests to ensure that what is being merged onto master is good. Hence we have required a Travis integration test and code cov test. If you want to see progress of this, or when a teammate opens up a PR, join the #ip_build channel on slack.
8) We also require one reviewer who is not the committer to approve the changes. Hence please ask a teammate to review, potentially offer feedback, and then approve your code. After this you will be able to merge.
# TODOs
1) Identify roadway assets, i.e signboards, cones.
2) Detect roadway pavement markings from a moving camera.
3) Categorize vehicles by type.
<file_sep>Flask
Redis
tensorflow
numpy
opencv-python
tensorflow-gpu
<file_sep>import cv2
import pickle
import numpy as np
from transformation import transform
from car import Car
from graphview.graphview import plot_logs
import argparse
log_attributes = {'num_vehicles': [], 'timestamps': [], 'flow_timestamps': [], 'average_speed': [], 'average_offset': []}
def calc_euclidean_distance(current_center, previous_center):
x1, y1 = current_center
x2, y2 = previous_center
return ((x1 - x2) ** 2 + (y2 - y1) ** 2) ** 0.5
def transformToBirdsEye(raw_center, transformation_matrix, preview = False):
if not raw_center:
return []
# apply t_mat to the centers
transformed_center = cv2.perspectiveTransform(np.array([raw_center], dtype=float), transformation_matrix)
return transformed_center
def match_center_to_car(transformed_center, visible_cars):
if not visible_cars:
return None
# match transformed xy coordinates, visible_cars
min_dist = float('inf')
matched_car_id = None
for car_id, vehicle in visible_cars.items():
# haven't used this vehicle
if not vehicle.updated:
curr_dist = calc_euclidean_distance(vehicle.get_latest_transformed_center(), transformed_center)
if curr_dist < min_dist:
min_dist = curr_dist
matched_car_id = car_id
# return the (car_id, vehicle) that matches best
return (matched_car_id, visible_cars[matched_car_id])
def log_flow_timestamp(timestamp):
log_attributes['flow_timestamps'].append(timestamp)
def log_car_details(vehicle):
pass
def log_density_and_avg_speed_or_offset(num_vehicles, avg_speed, avg_offset, timestamp):
log_attributes['num_vehicles'].append(num_vehicles)
log_attributes['timestamps'].append(timestamp)
log_attributes['average_speed'].append(avg_speed)
log_attributes['average_offset'].append(avg_offset)
def main():
parser = argparse.ArgumentParser()
# preview settings
bird_eye_preview = False
blob_preview = False
retain_trajectories = False
parser.add_argument("-bird_eye_preview", action='store_true', help="birds_eye_preview is true")
parser.add_argument("-blob_preview", action='store_true', help="blob_preview is true")
parser.add_argument("-retain_trajectories", action='store_true', help="retain_trajectories is true")
args = parser.parse_args()
if args.bird_eye_preview:
bird_eye_preview = True
if args.blob_preview:
blob_preview = True
if args.retain_trajectories:
retain_trajectories = True
# Open the video
capture = cv2.VideoCapture('big_files/final.mp4')
# background subtraction
fgbg = cv2.createBackgroundSubtractorMOG2(varThreshold=100, detectShadows=False)
# background image we're doing right
background = cv2.imread('big_files/background.png', 0)
FRAMES_PER_SECOND = 30
FRAMES_FOR_SPEED = 1
LANE_LINES = [880, 1000, 1120]
LANE_CENTERS = [940, 1060]
ENTRANCE_RANGE = [200, 250]
EXIT_RANGE= [1950, 2000]
BACKGROUND_DIFFERENCE_THRESHOLD = 10
BLOB_AREA_THRESHOLD = 7000 # minimum size of blob in order to be considered a vehicle
# open transformation calibration checkerboard image
checkerboard_image = cv2.imread('betterCheckb.png')
# calculate transformation matrix
transformation_matrix, _ = transform(checkerboard_image)
transformed_background = cv2.warpPerspective(background, transformation_matrix, (2000, 2000))
# draw lane lines on background
for l in LANE_LINES:
cv2.line(transformed_background, (l, 0), (l, 2000), (0, 0, 0), 3)
for hg in ENTRANCE_RANGE + EXIT_RANGE:
cv2.line(transformed_background, (0, hg), (2000, hg), (0, 0, 0), 3)
# keep a cache of the previous frame centers
frame_count = 0
visible_cars = {}
vehicle_id = 0
# transformed_output = transformed_background
first_t_plot = True
# loop through frames of video
while True:
# capture current frame in video
ret, img = capture.read()
if ret == True:
if frame_count % FRAMES_FOR_SPEED == 0:
# birds-eye
if bird_eye_preview and first_t_plot:
transformed_output = transformed_background.copy()
if retain_trajectories: first_t_plot = False
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# use the background subtractor
fgbg.apply(background)
fgmask = fgbg.apply(imgray)
# Pre processing, which includes blurring the image and thresholding
fgmask = cv2.GaussianBlur(fgmask, (29, 29), 0)
ret, thresh = cv2.threshold(fgmask, BACKGROUND_DIFFERENCE_THRESHOLD, 255, cv2.THRESH_BINARY)
if blob_preview: cv2.imshow('blobs', thresh)
# Get the contours for the thresholded image
im2, cnts, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# loop over the contours
cnts = [(c, cv2.contourArea(c)) for c in cnts]
cnts.sort(key=lambda c: c[1], reverse=True)
for i, contour_pairing in enumerate(cnts):
c, area = contour_pairing
# compute the center of the contour
if area > BLOB_AREA_THRESHOLD:
M = cv2.moments(c)
# prevent divide by zer0
if M["m00"] != 0.0:
r_cX = int(M["m10"] / M["m00"])
r_cY = int(M["m01"] / M["m00"])
raw_center = (r_cX, r_cY)
transformed_center = transformToBirdsEye([raw_center], transformation_matrix)
t_cX, t_cY = transformed_center[0][0]
t_cX += 33 # assume a car is 6.6 feet wide, shift point over by half of the width (3.3 feet = 33 px in transformed plane)
if t_cX >= LANE_LINES[0] and t_cX <= LANE_LINES[-1] and t_cY > ENTRANCE_RANGE[0] and t_cY < EXIT_RANGE[1]:
if t_cY < ENTRANCE_RANGE[1]:
print("new vehicle", vehicle_id, transformed_center[0][0])
# VEHICLE ENTERED
visible_cars[vehicle_id] = Car(vehicle_id, (r_cX, r_cY), (t_cX, t_cY), c)
vehicle_id += 1
# flow log here
log_flow_timestamp(frame_count / FRAMES_PER_SECOND)
elif visible_cars and i <= len(visible_cars):
# VEHICLE PREVIOUSLY VISIBLE: match with previous entry in visible_cars
car_id, vehicle = match_center_to_car(transformed_center[0][0], visible_cars)
vehicle.updated = True
print('matched updated', car_id)
# add new raw and transformed position
vehicle.update_raw_and_transformed_positions(raw_center, (t_cX, t_cY))
vehicle.update_contour(c)
else:
# the rest of the blobs do not meet our minimum threshold
break
# loop through cars to log those which have dissappeared and then log/remove them
for car_id, vehicle in visible_cars.items():
if not vehicle.updated:
log_car_details(vehicle)
print('{0} has exited'.format(car_id))
# log the car information
visible_cars = {car_id: vehicle for (car_id, vehicle) in visible_cars.items() if vehicle.updated}
speed_sum = 0
offset_sum = 0
num_valid_vehicles = 0
# display information for cars that are still visible
for car_id, vehicle in visible_cars.items():
# reset vehicle to not updated
vehicle.updated = False
# raw position, speed and velocity vectors
current_raw_center = vehicle.get_latest_raw_center()
speed, previous_raw_center, _ = vehicle.get_latest_raw_velocity()
if not current_raw_center or not previous_raw_center: continue
num_valid_vehicles += 1
r_cX, r_cY = current_raw_center
r_pX, r_pY = previous_raw_center
contour = vehicle.get_latest_contour()
# transformed position, speed and velocity vectors
current_transformed_center = vehicle.get_latest_transformed_center()
_, previous_transformed_center, _ = vehicle.get_latest_transformed_velocity()
t_cX, t_cY = current_transformed_center
t_pX, t_pY = previous_transformed_center
# update average speed and offset sums
speed_sum += speed
offset = min([abs(t_cX - lc) for lc in LANE_CENTERS]) / 10
offset_sum += offset
# annotate raw image with contour, centroid
cv2.drawContours(img, [contour], -1, (0, 0, 204), 2)
cv2.circle(img, (r_cX, r_cY), 7, (0, 0, 204), -1)
cv2.putText(img, "{0} mph".format(round(speed, 1)), (r_cX - 20, r_cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 100), 2)
cv2.arrowedLine(img, (r_pX, r_pY), (r_cX, r_cY), (0,0,100),2)
if bird_eye_preview:
cv2.circle(transformed_output, (int(t_cX), int(t_cY)), 3, (0, 0, 0), -1)
cv2.line(transformed_output, (int(t_cX), int(t_cY)), (int(t_pX), int(t_pY)), (0,0,0),2)
if num_valid_vehicles != 0:
avg_speed = speed_sum / num_valid_vehicles
avg_offset = offset_sum / num_valid_vehicles
log_density_and_avg_speed_or_offset(num_valid_vehicles, avg_speed, avg_offset, frame_count / FRAMES_PER_SECOND)
cv2.imshow("original footage with blob/centroid", img)
# birds-eye
if bird_eye_preview: cv2.imshow('birds-eye', transformed_output)
frame_count += 1
if (cv2.waitKey(27) != -1): # space button
# save your vars
pickle.dump(log_attributes, open("log_attributes.p", "wb"))
plot_logs()
break
pickle.dump(log_attributes, open("log_attributes_finished.p", "wb"))
plot_logs()
capture.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
<file_sep>import cv2
import numpy as np
def transform(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# pixel coordinates of calibration checkerbox corners in original picture
myFrom = np.float32([
[1042, 406],
[1299, 406],
[903, 791],
[356, 790],
])
# side length of a square
sL = 40
# width and height of output transformed image
tW = 2000
tH = 2000
# pixel coordinates of the calibration checkerbox corners in output transformed image
myTo = np.float32([
[tW/2 - 3*sL, tH/2 - 20*sL],
[tW/2 + 3*sL, tH/2 - 20*sL],
[tW/2 + 3*sL, tH/2 + 20*sL],
[tW/2 - 3*sL, tH/2 + 20*sL],
])
# Get transformation matrix
tMat = cv2.getPerspectiveTransform(myFrom,myTo)
# warp input image with transformation matrix (use this to warp detected centroids)
dst = cv2.warpPerspective(img, tMat, (tW, tW))
return (tMat, dst)
def main():
img = cv2.imread('betterCheckb.png')
transformationMatrix, sampleTransform = transform(img)
cv2.imshow("transformed", sampleTransform)
cv2.waitKey()
if __name__ == '__main__':
main() | e05936bcb7898e33e82e74ef9935fbb20d4d791c | [
"Markdown",
"Python",
"Text"
] | 12 | Python | image-processing-sci/image-processing-sci | 5a78bbb0163df4fa4754c1744a6af0fe64d6959b | 97de5effa1eaded1446e3682241d702a14a2b5d7 |
refs/heads/master | <repo_name>huysh3/SB_Webpack<file_sep>/notebook.js
const UglifyPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: './src/index.js',
// loader,将其他格式文件转换为js代码,方便打包运行
rules: [
{
test: /\.jsx?/, //匹配jsx文件
includes: [
path.resolve(__dirname, 'src') // 指定该路径下文件需要该loader处理
],
use: 'babel-loader', // 指定loader
},
],
// plugin, 用于处理更多其他的一些构建任务。
// 代码转换由loader执行,其他所有plugin可以全包
// 如uglify
// 以及定义环境变量的DefinePlugin, 生成CSS文件的ExtractTextWebpackPlugin等
plugins: [
new UglifyPlugin()
],
// output,输出,可配置文件名和路径等
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
}
// 配置等同于
module.exports = {
entry: {
main: './src/index.js'
}
}
// 多入口
module.exports = {
entry: {
foo: './src/foo.js',
bar: './src/bar.js',
},
output: {
path: __dirname + '/dist',
filename: '[name].[hash].js', // 可加版本号等
}
}
// 数组多文件打包
module.exports = {
entry: {
main: [
'./src/foo.js',
'./src/bar.js'
]
}
} | f34a9d18ae2afb8c17d932fbcce4b538b551ac89 | [
"JavaScript"
] | 1 | JavaScript | huysh3/SB_Webpack | b50068a8cd89793d0abee3e8833eab5587b4df5f | 1549e8f482d7a1592babd6774921eadad538af40 |
refs/heads/master | <file_sep>import React from "react";
import { Typography, Grid, Paper } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
padding: "2%",
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
alignItems: "center",
height: 185,
},
number: {
color: "#2e0412",
textAlign: "center",
},
title: {
textAlign: "center",
},
}));
const Box = ({ title, number, subtitle }) => {
const classes = useStyles();
return (
<div className={classes.root}>
<Typography className={classes.title} variant="h5" gutterBottom>
{title}
</Typography>
<div>
{" "}
<Typography className={classes.number} variant="h3" gutterBottom>
{number}
</Typography>
<Typography variant="h6" gutterBottom>
{subtitle}
</Typography>
</div>
</div>
);
};
export default Box;
<file_sep>import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import AccountCircle from "@material-ui/icons/AccountCircle";
import IconButton from "@material-ui/core/IconButton";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import PriorityHighIcon from "@material-ui/icons/PriorityHigh";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";
import NotificationsActiveIcon from "@material-ui/icons/NotificationsActive";
import PersonIcon from "@material-ui/icons/Person";
import { MenuData } from "./top-bar";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
appBar: {
backgroundColor: "#131b31",
height: "40px",
justifyContent: "flex-end",
},
userName: {
margin: "1rem",
},
}));
export default function TopBar() {
const classes = useStyles();
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);
const handleClose = () => {
setAnchorEl(null);
};
const handleMenu = (event) => {
setAnchorEl(event.currentTarget);
};
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar className={classes.appBar}>
<IconButton
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleMenu}
color="inherit"
>
<AccountCircle />{" "}
<Typography className={classes.userName} variant="overline">
<NAME>
</Typography>
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={open}
onClose={handleClose}
>
{MenuData.map((menu) => (
<MenuItem key={menu.id} onClick={handleClose}>
<ListItemIcon>
{menu.icon === "PersonIcon" ? (
<PersonIcon fontSize="small" />
) : menu.icon === "NotificationsActiveIcon" ? (
<NotificationsActiveIcon fontSize="small" />
) : menu.icon === "ExitToAppIcon" ? (
<ExitToAppIcon fontSize="small" />
) : null}
</ListItemIcon>
<Typography variant="inherit">{menu.title}</Typography>
</MenuItem>
))}
</Menu>
</Toolbar>
</AppBar>
</div>
);
}
<file_sep>import React from "react";
import Dash from "components/app/routes/main/dash";
import { Switch, Route } from "react-router-dom";
import Auth from "./routes/auth";
const App = () => {
return (
<div className="App">
<Switch>
<Route exact path="/" component={Auth} />
<Route path="/dash" component={Dash} />
</Switch>
</div>
);
};
export default App;
<file_sep>export { default } from "./comments-clean.jsx";
<file_sep>export const Menu = [
{
id: 0,
title: "Tableau de bord",
link: "/",
state: "TBD",
},
{
id: 2,
title: "Clusters",
link: "/Clusters",
state: "Clusters",
},
{
id: 1,
title: "Métriques",
link: "/Metriques",
state: "Metriques",
},
];
<file_sep>import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import { Paper, TextField, Typography, Button } from "@material-ui/core";
import { useHistory } from "react-router-dom";
const useStyles = makeStyles((theme) => ({
root: {
backgroundColor: "#efefef",
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center",
},
paper: {
margin: theme.spacing(1),
width: "50%",
height: "65%",
backgroundColor: "#1a2930",
display: "flex",
flexDirection: "column",
alignItems: "center",
padding: theme.spacing(4),
},
title: {
color: "white",
},
form: {
marginTop: 25,
width: "100%",
justifyContent: "flex-start",
display: "flex",
color: "white",
flexDirection: "column",
},
textField: {
backgroundColor: "white",
},
btn: {
marginTop: 50,
backgroundColor: "white",
width: 250,
fontSize: "22px",
},
}));
const Auth = () => {
const classes = useStyles();
let history = useHistory();
const [userName, setUserName] = useState("");
const handleSubmit = () => {
if (userName === "yacine") {
history.push("/dash");
} else {
alert("erreur");
}
};
console.log(userName);
const handleChangeUsername = (event) => {
console.log(event.target.value);
setUserName(event.target.value);
};
return (
<section className={classes.root}>
<Paper className={classes.paper} elevation={3}>
<Typography className={classes.title} variant="h3" gutterBottom>
Authentification
</Typography>
<div className={classes.form}>
<Typography className={classes.title} variant="h5" gutterBottom>
Nom d'utilisateur :
</Typography>
<TextField
name="userName"
onClick={handleChangeUsername}
id="outlined-basic"
label="Nom d'utilisateur"
variant="outlined"
className={classes.textField}
/>
</div>
<div className={classes.form}>
<Typography className={classes.title} variant="h5" gutterBottom>
Mot de passe :
</Typography>
<TextField
className={classes.textField}
type="password"
id="outlined-basic"
label="Mot de passe"
variant="outlined"
/>
</div>
<Button
onClick={handleSubmit}
className={classes.btn}
variant="contained"
>
S'authentifier
</Button>
</Paper>
</section>
);
};
export default Auth;
//#efefef
<file_sep>import React from "react";
import { Typography, Grid, Paper } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";
import Box from "components/common/box";
import { Line } from "react-chartjs-2";
const useStyles = makeStyles((theme) => ({
root: {
padding: "2%",
},
paper: {
marginTop: 15,
minHeight: 225,
},
chart: {
padding: "2%",
marginTop: 25,
height: 230,
},
canvas: {
height: 350,
},
}));
const Metrique = (props) => {
// Nombre total de donnée dans le dataset.
// nombre total de clusters.
// dernière récupération de données.
// Nombre total de commentaires positifs/négatifs/neutres
// Nombre total de postes
//total 24184 , >0 8599, <0 7033 =0 8552
const classes = useStyles();
const data = {
labels: ["03-10", "10-10", "17-10", "24-10", "31-10", "6-11"],
datasets: [
{
label: "Nbr de j'aime",
data: [632958, 634415, 635125, 639985, 641356, 643356],
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.2)",
},
],
};
const options = {
scales: {
yAxes: 630000,
},
};
const data2 = {
labels: ["03-10", "10-10", "17-10", "24-10", "31-10", "6-11"],
datasets: [
{
label: "Nbr de j'aime",
data: [632958, 634415, 635125, 639985, 641356, 643356],
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.2)",
},
],
};
const options2 = {
scales: {
yAxes: 630000,
},
};
return (
<section className={classes.root}>
<Typography variant="h3" gutterBottom>
Métriques :
</Typography>
<Paper className={classes.chart}>
<Typography className={classes.title} variant="h5" gutterBottom>
Développements des j'aimes{" "}
</Typography>
<Line data={data} height={50} options={options} />
</Paper>
</section>
);
};
export default Metrique;
<file_sep>import React, { useState } from "react";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
const MenuDisplay = props => {
const [anchorEl, setAnchorEl] = useState(null);
const open = Boolean(anchorEl);
const handleClose = () => {
setAnchorEl(null);
};
return (
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: "top",
horizontal: "right"
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right"
}}
open={open}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Notification</MenuItem>
<MenuItem onClick={handleClose}>Disconnect</MenuItem>
</Menu>
);
};
export default MenuDisplay;
<file_sep>export { default } from "./comments.jsx";
<file_sep>export { default } from "./comments-raw.jsx";
| 25c3a0c06652b78aa289b60a3e97369fda1ef157 | [
"JavaScript"
] | 10 | JavaScript | YacineFerhat/AT | 9a3fe3a3721f1aaee5489143dd9b3af1083ffa28 | d8579596779e294cd8aada9357c05017e4b815cd |
refs/heads/master | <repo_name>denaagr/react-workshop<file_sep>/src/index.js
import ReactDOM from "react-dom";
import "bootstrap/dist/css/bootstrap.css";
import DataTable from "./DataTable";
ReactDOM.render(<DataTable/>, document.getElementById("root"));<file_sep>/src/Table.js
import React from 'react';
//import './Table.css';
const TableHeader = () => {
return (
<thead>
<tr>
<th style={ {color: 'red'} }>Id</th>
<th className={'test'}>firstName</th>
<th className={'test'}>lastName</th>
<th className={'test'}>age</th>
<th>Details</th>
</tr>
</thead>
);
}
const TableAction = () => {
return (<button type="button" className="btn btn-danger">Details</button>);
};
const TableRow = () => {
return (
<tbody>
<tr>
<td>1</td>
<td>Mehrdad</td>
<td>Javan</td>
<td><TableAction /></td>
</tr>
<tr>
<td>2</td>
<td>Fredrik</td>
<td>Odin</td>
<td><TableAction /></td>
</tr>
</tbody>
);
}
const Table = () => {
return (
<div className="container">
<table className="table">
<TableHeader />
<TableRow />
</table>
</div>
);
};
export default Table; | b07171f99ded3e048b1a1a9499962092f85950f5 | [
"JavaScript"
] | 2 | JavaScript | denaagr/react-workshop | a2fe29d35e463688f0195c9500209e4f7c874bce | c1044794788ac07b89da24ac5af6a5ac5fc9a1b5 |
refs/heads/master | <repo_name>wbuchwalter/k8s-ml-demo<file_sep>/1-simple-gpu-job/Dockerfile
# wbuchwalter/k8s-ml-demo:simple-gpu-job
FROM tensorflow/tensorflow:latest-gpu-py3
COPY ./main.py /app/main.py<file_sep>/README.md
# k8s-ml-demo<file_sep>/1-simple-gpu-job/main.py
import tensorflow as tf
print(tf.Session()) | c5ccc2b321663b5318bb39d705e06b0ea854b9aa | [
"Markdown",
"Python",
"Dockerfile"
] | 3 | Dockerfile | wbuchwalter/k8s-ml-demo | aef9c97adb7437ee29a0621a794376b3b6d56a8a | 94c8a05bea325b2b990227f74ae0c4a9e3f3af53 |
refs/heads/master | <file_sep># METAL -- Meta analysis
## Description
This workflow performs a meta analysis of association results using the [METAL software](http://csg.sph.umich.edu/abecasis/metal/)
### Authors
This workflow is produced and maintained by the [Manning Lab](https://manning-lab.github.io/). Contributing authors include:
* <NAME> (<EMAIL>)
* <NAME> (<EMAIL>).
## Dependencies
### Workflow execution
* [WDL](https://software.broadinstitute.org/wdl/documentation/quickstart)
* [Chromwell](http://cromwell.readthedocs.io/en/develop/)
### METAL (included in Docker image)
* [Metal - generic distribution](http://csg.sph.umich.edu/abecasis/metal/download/)
### R packages
* [data.table](https://cran.r-project.org/web/packages/data.table/index.html)
* [qqman](https://cran.r-project.org/web/packages/qqman/index.html)
### Docker images
* [Bioconductor](https://hub.docker.com/r/robbyjo/r-mkl-bioconductor/) - by <NAME> (<EMAIL>)
* [METAL](https://hub.docker.com/r/tmajarian/metal/)
## Main Functions
### runMetal
This function generates the metal input script, processes each input results file, and runs the meta analysis
Inputs:
* assoc_files : an array of association results files, like those generated in the single variant association pipeline, must have a column labeled "MAF" (Array[File], .csv or .tsv)
* marker_column : column name in assoc_files with variant identifiers (string, default = snpID)
* sample_column : column name in assoc_files for weighting of variants (string, default = n)
* allele_effect_column : column name in assoc_files with effect allele (string, default = alt)
* allele_non_effect_column : column name in assoc_files with non effect allele (string, default = ref)
* pval_column : column in assoc_files with variant p-value (string, default = Score.pval)
* effect_column : column in assoc_files with variant effect (string, default = Score.Stat)
* out_pref : prefix for output filename (string)
* separator : character that separates each input result file (string, default = COMMA [WHITESPACE, TAB])
* analyze_arg : optional argument for other types of analyses (string, default = ZSCORE)
Outputs:
* result_file : results per variant for all variants tested (.TBL)
* metal_script : script that was generated as input to METAL (script.txt)
* log_file : log file capturing standard error of running METAL (.log)
* info_file : description of results_file columns, input files
### metalSummary
This function generates the metal input script, processes each input results file, and runs the meta analysis
Inputs:
* marker_column : column name in assoc_files with variant identifiers (string, default = snpID)
* pval_column : column in assoc_files with variant p-value (string, default = Score.pval)
* sample_column : column in assoc_files with number of samples (string, default = n)
* out_pref : prefix for output filename (string)
* metal_file : output of runMetal task (File)
* assoc_files : an array of association results files, like those generated in the
Outputs:
* csv : a comma separated file of results including METAL results and "cols_tokeep" from each input results file (.csv)
* plots : quantile-quantile and manhattan plots subset by MAF (all, <5%, >=5%) for meta-analysis p-values (.png)
## Other workflow inputs
* this_memory : amount of memory in GB for each execution of a task (int)
* this_disk : amount of disk space in GB to allot for each execution of a task (int)
<file_sep>### summaryCSVMetal.R
# Description: This function generates the metal input script, processes each input results file, and runs the meta analysis
# Inputs:
# marker.column : column name in results_files with variant identifiers (string)
# freq.column : column in results_files with variant frequency (string)
# pval.column : column in results_files with variant p-value (string)
# sample.column : column in results_files with number of samples (string)
# cols.tokeep : comma separated list of columns in each association results file (string)
# out.pref : prefix for output filename (string)
# metal.file : output of runMetal task (File)
# Outputs:
# csv : a comma separated file of results including METAL results and "cols_tokeep" from each input results file (.csv)
# plots : quantile-quantile and manhattan plots subset by MAF (all, <5%, >=5%) for meta-analysis p-values (.png)
# Load packages
lapply(c("qqman","data.table","tools","RColorBrewer"), library, character.only = TRUE)
# Parse inputs
input_args <- commandArgs(trailingOnly=T)
metal.file <- input_args[1]
out.pref <- input_args[2]
pval.thresh <- as.numeric(input_args[3])
freq.column <- "MAF"
######### test inputs #################
# marker.column <- "snpID"
# pval.column <- "Score.pval"
# sample.column <- "n"
# out.pref <- "demo"
# metal.file <- "demo1.tsv"
# pval.thresh <- 0.05
#####################################
# load metal results
metal.data <- fread(metal.file,data.table=F,stringsAsFactors = F)
# write top results out to file
fwrite(metal.data[which(metal.data[,"P-value"] < pval.thresh),], file = paste0(out.pref,".METAL.top.assoc.csv"), sep=",")
## Plotting ##
# calculate genomic control
lam = function(x,p=.5){
x = x[!is.na(x)]
chisq <- qchisq(1-x,1)
round((quantile(chisq,p)/qchisq(p,1)),2)
}
# qq plot
qqpval2 = function(x, main="", col="black"){
x<-sort(-log(x[x>0],10))
n<-length(x)
plot(x=qexp(ppoints(n))/log(10), y=x, xlab="Expected", ylab="Observed", main=main ,col=col ,cex=.8, bg= col, pch = 21)
abline(0,1, lty=2)
}
# qq without identity line
qqpvalOL = function(x, col="blue"){
x<-sort(-log(x[x>0],10))
n<-length(x)
points(x=qexp(ppoints(n))/log(10), y=x, col=col, cex=.8, bg = col, pch = 21)
}
# get the right colors
cols <- brewer.pal(8,"Dark2")
# qq plot
png(filename = paste0(out.pref,".plots.png"),width = 11, height = 11, units = "in", res=400)#, type = "cairo")
layout(matrix(c(1,2,3,3),nrow=2,byrow = T))
qqpval2(metal.data[,"P-value"], col=cols[8])
legend('topleft',c(paste0('GC = ',lam(metal.data[,"P-value"]))),col=c(cols[8]),pch=c(21))
qqpval2(metal.data[metal.data$total_maf >= 0.05, "P-value"],col=cols[1])
qqpvalOL(metal.data[metal.data$total_maf < 0.05, "P-value"],col=cols[2])
legend('topleft',c(paste0('GC (MAF >= 5%) = ',lam(metal.data[metal.data$total_maf >= 0.05, "P-value"])),
paste0('GC (MAF < 5%) = ',lam(metal.data[metal.data$total_maf < 0.05, "P-value"]))),
col=c(cols[1],cols[2]),pch=c(21,21))
manhattan(metal.data,chr="chr",bp="pos",p="P-value", main="All variants")
dev.off()
<file_sep>### metal_summary.R
# Description: This function generates the metal input script, processes each input results file, and runs the meta analysis
# Inputs:
# marker.column : column name in results_files with variant identifiers (string)
# freq.column : column in results_files with variant frequency (string)
# pval.column : column in results_files with variant p-value (string)
# sample.column : column in results_files with number of samples (string)
# cols.tokeep : comma separated list of columns in each association results file (string)
# assoc.names : comma separated list of association analysis names, one corresponding to each input result file (string)
# out.pref : prefix for output filename (string)
# metal.file : output of runMetal task (File)
# result.files : comma separated list of result files to summarize, these are the csv outputs of the single variant association pipeline (string)
# Outputs:
# csv : a comma separated file of results including METAL results and "cols_tokeep" from each input results file (.csv)
# plots : quantile-quantile and manhattan plots subset by MAF (all, <5%, >=5%) for meta-analysis p-values (.png)
# Load packages
lapply(c("qqman","data.table","tools","RColorBrewer"), library, character.only = TRUE)
# Parse inputs
input_args <- commandArgs(trailingOnly=T)
marker.column <- input_args[1]
pval.column <- input_args[2]
sample.column <- input_args[3]
out.pref <- input_args[4]
metal.file <- input_args[5]
assoc.files <- unlist(strsplit(input_args[6],","))
pval.thresh <- as.numeric(input_args[7])
freq.column <- "MAF"
######### test inputs #################
# marker.column <- "snpID"
# pval.column <- "Score.pval"
# sample.column <- "n"
# out.pref <- "demo"
# metal.file <- "demo1.tsv"
# assoc.files <- c("demo.1.assoc.csv","demo.2.assoc.csv")
# pval.thresh <- 0.05
#####################################
# define names for each input analysis
assoc.names <- unlist(lapply(assoc.files, function(x) file_path_sans_ext(basename(x)) ))
# load metal results
metal.data <- fread(metal.file,data.table=F)
# names to keep later on
names.to.keep <- names(metal.data)
# load individual results and merge
for (f in seq(1,length(assoc.files))){
assoc.data <- fread(assoc.files[f],data.table=F)
names(assoc.data)[names(assoc.data) != marker.column] = paste(names(assoc.data)[names(assoc.data) != marker.column], assoc.names[f], sep = ".")
metal.data <- merge(metal.data, assoc.data, by.x = "MarkerName", by.y = marker.column, all.x=TRUE)
}
# get the position and chromosome columns for manhatten
if (length(assoc.files) > 1){
metal.data$pos <- unlist(apply(metal.data[,names(metal.data)[startsWith(names(metal.data), "pos")]], 1, function(x) unique(x[!is.na(x)])[1]))
metal.data$chr <- unlist(apply(metal.data[,names(metal.data)[startsWith(names(metal.data), "chr")]], 1, function(x) unique(x[!is.na(x)])[1]))
} else {
metal.data$pos <- unlist(lapply(metal.data[,names(metal.data)[startsWith(names(metal.data), "pos")]], function(x) unique(x[!is.na(x)])[1]))
metal.data$chr <- unlist(lapply(metal.data[,names(metal.data)[startsWith(names(metal.data), "chr")]], function(x) unique(x[!is.na(x)])[1]))
}
# remove unneeded columns
names.to.keep <- c(names.to.keep, "pos", "chr", names(metal.data)[startsWith(names(metal.data),pval.column)], names(metal.data)[startsWith(names(metal.data),"minor.allele")])
metal.data <- metal.data[,names(metal.data)[names(metal.data) %in% names.to.keep]]
# order based on meta pvalue
metal.data <- metal.data[order(metal.data[,"P-value"]),]
# calculate full sample mac for each variant
# all_mac <- c()
# for (n in assoc.names){
# all_mac <- cbind(all_mac, 2 * metal.data[,paste(sample.column,".",n,sep="")] * metal.data[,paste(freq.column,".",n,sep="")] )
# }
# metal.data$total_maf <- rowSums(all_mac)/(2*metal.data$Weight)
# change marker sep
# metal.data$MarkerName <- gsub("-",":",metal.data$MarkerName)
## Plotting ##
# calculate genomic control
lam = function(x,p=.5){
x = x[!is.na(x)]
chisq <- qchisq(1-x,1)
round((quantile(chisq,p)/qchisq(p,1)),2)
}
# qq plot
qqpval2 = function(x, main="", col="black"){
x<-sort(-log(x[x>0],10))
n<-length(x)
plot(x=qexp(ppoints(n))/log(10), y=x, xlab="Expected", ylab="Observed", main=main ,col=col ,cex=.8, bg= col, pch = 21)
abline(0,1, lty=2)
}
# qq without identity line
qqpvalOL = function(x, col="blue"){
x<-sort(-log(x[x>0],10))
n<-length(x)
points(x=qexp(ppoints(n))/log(10), y=x, col=col, cex=.8, bg = col, pch = 21)
}
# get the right colors
cols <- brewer.pal(8,"Dark2")
# qq plot
png(filename = paste0(out.pref,".plots.png"),width = 11, height = 11, units = "in", res=400)#, type = "cairo")
layout(matrix(c(1,2,3,3),nrow=2,byrow = T))
qqpval2(metal.data[,"P-value"], col=cols[8])
legend('topleft',c(paste0('GC = ',lam(metal.data[,"P-value"]))),col=c(cols[8]),pch=c(21))
qqpval2(metal.data[metal.data$Freq1 >= 0.05, "P-value"],col=cols[1])
qqpvalOL(metal.data[metal.data$Freq1 < 0.05, "P-value"],col=cols[2])
legend('topleft',c(paste0('GC (MAF >= 5%) = ',lam(metal.data[metal.data$Freq1 >= 0.05, "P-value"])),
paste0('GC (MAF < 5%) = ',lam(metal.data[metal.data$Freq1 < 0.05, "P-value"]))),
col=c(cols[1],cols[2]),pch=c(21,21))
manhattan(metal.data,chr="chr",bp="pos",p="P-value", main="All variants")
dev.off()
# make ref/alt cols if we can
if(lengths(regmatches(metal.data$MarkerName[1], gregexpr("-", metal.data$MarkerName[1]))) == 3){
ref_alt <- do.call(rbind, strsplit(metal.data$MarkerName, "-"))
metal.data$ref <- ref_alt[,3]
metal.data$alt <- ref_alt[,4]
metal.data <- metal.data[,c("MarkerName", "chr", "pos", "ref", "alt", "Freq1", "P-value", "Allele1", "Allele2", "Weight", "Zscore", "Direction")]
names(metal.data) <- c("MarkerName", "chr", "pos", "ref", "alt", "maf", "pvalue", "allele1", "allele2", "weight", "zscore","direction")
} else {
metal.data <- metal.data[,c("MarkerName", "chr", "pos", "Allele1", "Allele2", "Freq1", "P-value", "Weight", "Zscore", "Direction")]
names(metal.data) <- c("MarkerName", "chr", "pos","allele1", "allele2", "maf", "pvalue", "weight", "zscore","direction")
}
# write results out to file
fwrite(metal.data[which(metal.data[,"pvalue"] < pval.thresh),], file = paste0(out.pref,".METAL.top.assoc.csv"), sep=",")
fwrite(metal.data, file = paste0(out.pref,".METAL.assoc.csv"), sep=",")
<file_sep>FROM r-base:3.5.0
MAINTAINER <NAME> (<EMAIL>)
RUN apt-get update
RUN apt-get install -y build-essential zlib1g-dev git
RUN cd /bin
# COPY generic-metal-2011-03-25.tar.gz ./
RUN wget -O generic-metal-2011-03-25.tar.gz http://csg.sph.umich.edu/abecasis/Metal/download/generic-metal-2011-03-25.tar.gz
RUN tar -xzf ./generic-metal-2011-03-25.tar.gz && rm generic-metal-2011-03-25.tar.gz && cd generic-metal && make all && mv executables/metal /bin && cd /
RUN echo 'install.packages(c("qqman","data.table","tools","RColorBrewer"),repos="http://cran.us.r-project.org")' > install.R && \
Rscript --vanilla install.R && \
rm install.R
RUN git clone https://github.com/manning-lab/metal.git && \
echo hola
RUN apt-get update & apt-get -y install dstat | a1c088124d01b535d19e4a306a0ff2b8cf79b59d | [
"Markdown",
"R",
"Dockerfile"
] | 4 | Markdown | manning-lab/metal | 5e3c6efa7017e37b4565223351d13addba40689c | d16e8a36b19db4536d9fd2c4fad36c56115a6012 |
refs/heads/master | <repo_name>nbald/HandyQuest<file_sep>/arduino/arduino.ino
int sensorPin = A0;
int sensorValue = 0;
int flashPin = A1;
const int numReadings = 10;
int readings[numReadings];
int index = 0;
int total;
int average;
int mini=999;
boolean has_already_flashed=false;
void setup() {
pinMode(flashPin, OUTPUT);
digitalWrite(flashPin, LOW);
delay(1000);
Serial.begin(9600);
Serial.println("AT$SS=CACA");
resetAverage();
}
void resetAverage() {
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 999;
total = 999*numReadings;
average = 999;
}
void loop() {
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(sensorPin);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;
// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
if (average < mini) mini=average;
if (average < 180 && !has_already_flashed) {
digitalWrite(flashPin, HIGH);
delay(10);
digitalWrite(flashPin, LOW);
has_already_flashed=true;
}
if (average > 200 && has_already_flashed) {
delay(2000); // must delay because sigfox gets jammed by the flash
char tmp[10];
sprintf(tmp, "AT$SS=%04x", mini);
Serial.println(tmp);
resetAverage();
has_already_flashed=false;
mini=999;
delay(8000);
}
delay(1);
}
<file_sep>/serveur/sigfox-push.php
<?php
ini_set('display_errors', 1);
$startup=false;
if ($_GET['data'] == "caca") {
$startup=true;
} else {
$height = base_convert("0x{$_GET['data']}", 16, 10);
$height = round(-15.04*log($height)+84.54);
}
$signal = $_GET['avgSignal'];
$time = date("H:i:s", $_GET['time']+3600);
require('Pusher.php');
$app_id = '*****';
$app_key = '*******';
$app_secret = '*********';
if (!$startup) {
$pusher = new Pusher( $app_key, $app_secret, $app_id );
$pusher->trigger( 'handyquest', 'lift', array('height'=>$height, 'time'=>$time) );
}
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "************",
'oauth_access_token_secret' => "***********",
'consumer_key' => "**********",
'consumer_secret' => "************"
);
/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$requestMethod = 'POST';
/** POST fields required by the URL above. See relevant docs as above **/
if ($startup) {
$postfields = array(
'status' => 'Cendrillon vient d\'allumer ses chaussures magiques... (#sigfox '.$signal.'dB / '.$time.') #hackcess'
);
} else {
$postfields = array(
'status' => 'Oups : un obstacle de '.$height.'cm ! (#sigfox '.$signal.'dB / '.$time.') #hackcess'
);
}
/** Perform a POST request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest(); | a946a7ad1c5ce9009124cc67a0f9f337a69dd1f2 | [
"C++",
"PHP"
] | 2 | C++ | nbald/HandyQuest | 6a6252713549890756992811e8918efb9f502cbd | 1fa60e566ed7c455a322ffc1f0ea3e285ca130f9 |
refs/heads/main | <file_sep># Plotly
The purpose of this project was to create a website where test participants can look up their ID and see their results in multiple charts.
<file_sep>//reading in json data into a js file
// d3.json("samples.json").then(function(data){console.log(data);
// });
// to extract wfreq from each volunteer in the json directory
// d3.json("samples.json").then(function(data){
// wfreq = data.metadata.map(person => person.wfreq);
// console.log(wfreq);
// });
// // now adding sort in descending order
// d3.json("samples.json").then(function(data){
// wfreq = data.metadata.map(person =>
// person.wfreq).sort((a,b) => b - a);
// console.log(wfreq);
// });
// lastly, removing null values
// d3.json("samples.json").then(
// function(data){
// wfreq = data.metadata.map(person => person.wfreq).sort((a,b) => b - a);
// filteredWfreq = wfreq.filter(element => element != null);
// console.log(filteredWfreq);
// });
// printing the metadata for the first person in the data set
d3.json("samples.json").then(function(data){
firstPerson = data.metadata[0];
Object.entries(firstPerson).forEach(([key, value]) =>
{console.log(key + ': ' + value);});
});<file_sep>d3.json('/static/cancerData/data.json').then( (data) => {
var cancerData = {
x: data.organ,
y: data.survival,
type : "box",
name : "<NAME>",
boxpoints : "all"
}
var objectsToPlot = [cancerData]
Plotly.newPlot("cancerPlot",objectsToPlot)
});<file_sep>#%%
from flask import Flask, render_template
#%%
app = Flask(__name__)
#%%
@app.route("/")
def home():
return render_template('index.html')
@app.route("/corsExample")
def corsExample():
return render_template('corsExample.html')
@app.route("/piApproximation")
def piApproximation():
return render_template('piApproximation.html')
@app.route("/uniformApproximation")
def uniformApproximation():
return render_template('uniformApproximation.html')
@app.route("/dashboard")
def dashboard():
return render_template('dashboard.html') <file_sep>// //Plotly.newPlot("plotArea", [{x: [1, 2, 3], y: [10, 20, 30]}]);
// // for the newPlot() syntax, you put the id name first, then the values are next within an array
// Plotly.newPlot("plot", [{x: [1, 12, 33], y: [11, 20, 5]}]);
// var trace = {
// x: ['burrito', 'pizza', 'chicken'],
// y: [10, 18, 5],
// type: 'bar'
// };
// var layout = {
// title: 'Luncheon Survey',
// xaxis: {title: 'Food Option'},
// yaxis: {title: 'Number of Respondents'}
// };
// Plotly.newPlot('plotArea', [trace], layout); //the bar graph info is given as a variable within an array
// var drink_data = {
// x: ["nonalcoholic beer", "nonalcoholic wine", "nonalcoholic martini", "nonalcoholic margarita", "ice tea", "nonalcoholic rum & coke", "nonalcoholic mai tai", "nonalcoholic gin & tonic"],
// y: [22.7, 17.1, 9.9, 8.7, 7.2, 6.1, 6.0, 4.6],
// type: 'bar'
// };
// var drink_layout = {
// title: "'Bar' Chart",
// xaxis: {title: 'Drinks'},
// yaxis: {title: '% of Drinks Ordered'}
// };
// Plotly.newPlot('drinkBar', [drink_data], drink_layout);
// var pie = {
// }
// var drink_pie = {
// labels: ["nonalcoholic beer", "nonalcoholic wine", "nonalcoholic martini", "nonalcoholic margarita",
// "ice tea", "nonalcoholic rum & coke", "nonalcoholic mai tai", "nonalcoholic gin & tonic"],
// values: [22.7, 17.1, 9.9, 8.7, 7.2, 6.1, 6.0, 4.6],
// type: 'pie'
// };
// //pie charts use 'labels' and 'values' instead of X and Y axis
// var pie_data = [drink_pie];
// var pie_layout = {
// title: "'Pie' Chart",
// };
// Plotly.newPlot("drinkPie", pie_data, pie_layout);
// // Scatter plot
// var scatter_data = {
// x: ["nonalcoholic beer", "nonalcoholic wine", "nonalcoholic martini", "nonalcoholic margarita",
// "ice tea", "nonalcoholic rum & coke", "nonalcoholic mai tai", "nonalcoholic gin & tonic"],
// y: [22.7, 17.1, 9.9, 8.7, 7.2, 6.1, 6.0, 4.6],
// mode: 'markers',
// type: 'scatter'
// };
// var scatter_layout = {
// title: "Scatter Chart",
// xaxis: {title: 'Drinks'},
// yaxis: {title: '% of Drinks Ordered'}
// };
// Plotly.newPlot('drinkScatter', [scatter_data], scatter_layout);
// var numbers = [1,2,3,4,5]
// var doubled = numbers.map(function(num){
// return num * 2;
// });
// //console.log(doubled);
// var triple = numbers.map(x => x ** 3); //same as above except it's a fat arrow function (remember, similar to a python lambda function)
// console.log(triple);
// var words = ['cats', 'dogs', 'aliens', 'mice']
// var caps = words.map( i => i.toUpperCase());
// console.log(caps);
// var arrowNum = numbers.map(i => i + 5);
// console.log(arrowNum);
// var cities = [
// {
// "Rank": 1,
// "City": "San Antonio ",
// "State": "Texas",
// "Increase_from_2016": "24208",
// "population": "1511946"
// },
// {
// "Rank": 2,
// "City": "Phoenix ",
// "State": "Arizona",
// "Increase_from_2016": "24036",
// "population": "1626078"
// },
// {
// "Rank": 3,
// "City": "Dallas",
// "State": "Texas",
// "Increase_from_2016": "18935",
// "population": "1341075"
// }
// ];
// // var cityNames = cities.map(i => i.population);
// // console.log(cityNames);
// var numbers = [1,2,3,4,5];
// var larger = numbers.filter(function(num){
// return num > 1;
// });
// console.log(larger);
// //fat arrow
// var numbers = [1,2,3,4,5];
// var larger = numbers.filter(i => i > 1);
// console.log(larger);
// var words = ['seal', 'dog', 'scorpion', 'orangutan', 'salamander'];
// var sWords = words.filter(i => i[0] === 's');
// console.log(sWords);
//using sort
// var familyAge = [3,2,39,37,9];
// var sortedAge = familyAge.sort((a,b) => a - b);
// console.log(sortedAge);
//Slice
var integers = [0,1,2,3,4,5]
var slice1 = integers.slice(0,2); //this only returns the first 2 elements of the array
console.log(slice1);
var words = ['seal', 'dog', 'scorpion', 'orangutan', 'salamander'];
var slice2 = words.slice(-1);
console.log(slice2);<file_sep>// Now take a moment to plan our next steps. We will need to:
// Sort the cities in descending order of population growth.
// Select only the top five cities in terms of growth.
// Create separate arrays for the city names and their population growths.
// Use Plotly to create a bar chart with these arrays.
// //console.log(cityGrowths);
var sortedCities = cityGrowths.sort((a, b) => a.Increase_from_2016 - b.Increase_from_2016).reverse();
var topFiveCities = sortedCities.slice(0, 5);
var topFiveCityNames = topFiveCities.map(city => city.City);
var topFiveCityGrowths = topFiveCities.map(city => parseInt(city.Increase_from_2016)); //parseInt turns the array of numbers from strings into ints
var trace = {
x: topFiveCityNames,
y: topFiveCityGrowths,
type: 'bar'
};
var data = [trace];
var layout = {
title: 'Most Rapidly Growing Cities',
xaxis: {title: 'City'},
yaxis: {title: 'Population Growth, 2016-2017'}
};
Plotly.newPlot('bar-plot', data, layout);
var sortedPopCities = cityGrowths.sort((a,b) => a.population - b.population).reverse();
var topSevenCities = sortedPopCities.slice(0, 7);
var topSevenCityNames = topSevenCities.map(city => city.City);
var topSevenCityPop = topSevenCities.map(city => parseInt(city.population)); //parseInt turns the array of numbers from strings into ints
var tracePop = {
x: topSevenCityNames,
y: topSevenCityPop,
type: 'bar'
};
var dataPop = [tracePop];
var layoutPop = {
title: 'Most Populous Cities',
xaxis: {title: 'City'},
yaxis: {title: 'Population'}
};
Plotly.newPlot('pop-plot', dataPop, layoutPop);
console.log('hello'); | 4a148a1c061321da1065d01fd2691273af259aa2 | [
"Markdown",
"Python",
"JavaScript"
] | 6 | Markdown | jdwrhodes/Plotly | bdf3a0cbe932736935b270a9a65d0324a9195449 | f2a15ff5e691f20d8712c09336cbf689863f4c96 |
refs/heads/master | <repo_name>IvanMendoz/PROYECTO-DPWEB-DIVISAS<file_sep>/PHP/tblpaises/Insertar.php
<html>
<head>
<title>Insertar datos de tabla con MySQL</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
</head>
<body >
<h1>Insertando registros en la Base de Datos</h1>
<?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
$nombre = $_POST["txtNombre"];
//creando la consulta para insertar el registro
$consulta = "call CrearPais('$nombre');";
echo ($consulta);
$EjecutarConsulta=mysqli_query( $conexion, $consulta ) or die ( "No se pudo insertar el registro");
if ($EjecutarConsulta)
{
echo
'<script>
swal({
title: "Buena trabajo",
text: "datos insertados correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "Mostra.php";
});
</script>';
}
else
{
'<script>
swal({
title: "Algo salio mal",
text: "datos no insertados!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "Mostra.php";
});
</script>';
}
//liberando recursos y cerrando la BD;
mysqli_close($conexion);
?>
<br><br><a href="index.html">Home</a>
<br><br>
</body>
</html>|
<file_sep>/PHP/tblpaises/almacenarmodificar.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Almacenando y modificando</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
</head>
<body>
<?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$misql = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($misql,"utf8");
$Id_pais = $_POST["txtId_pais"];
$nombre = $_POST["txtNombre"];
$query = "call ModificarPais('$Id_pais ', '$nombre');";
//echo $query;
$consulta=$misql->query($query);
if($consulta){
echo
'<script>
swal({
title: "Buena trabajo",
text: "Registro modificado correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "Mostra.php";
});
</script>';
}
else{
echo
'<script>
swal({
title: "ERROR!",
text: "No se pudo modificar .",
type: "error"
}).then(function() {
window.location = "Mostra.php";
});
</script>';
}
?>
</body>
</html><file_sep>/PHP/tblpaises/modificar.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="CSS/estilos.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<!-- SCRIPTS PARA SWEETALERT -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<title>Modificando pais</title>
</head>
<body>
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<span class="fondo"></span><a href="../../index.html"> <img src="../../IMAGES/divisas7.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button onclick="location.href ='../../index.html'" class="dropdown-btn">Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
<a href="../conversiones/conversion.php" class="">Realizar conversion <i class="fas fa-dollar-sign"></i></a>
<a href="../../integrantes.html" class="">Lista de integrantes <i class="fas fa-users"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button style="background:#000;" class="dropdown-btn activee" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="./InsertarRegistro.html" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="./Mostra.php" class="" >Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="./Mostra.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="./Mostra.php" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="../tblMonedas/insertarMoneda.php" class="">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="../createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="../dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- <a href="" class="btn">Realizar conversion <i class="fas fa-trash-alt"></i></a>
<a href="" class="btn">Mantenimiento Paises <i class="fas fa-globe-americas"></i><a>
<a href="" class="btn">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></a> -->
</div>
</nav>
<?php
//capturar el codigo a modificar
$Id_pais = $_REQUEST['Id_pais'];
//cargar la conexion y octener la conexion activa $mysql
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
$query="call MostrarPaisPorId('$Id_pais');";
$consulta=$conexion->query($query);
$row=$consulta->fetch_assoc();
mysqli_close($conexion);
?>
<div class="containeer-contenido">
<div class="form-box">
<form method = "post" name="frmvalor" action="almacenarmodificar.php" id="form">
<h2>Informacion del registro seleccionado</h2>
<div class="">
<input type="text" name="txtId_pais" value="<?php echo $row['Id_pais'];?>" autocomplete="off" disabled required><br><br>
<input type="text" name="txtId_pais" style="display:none;" value="<?php echo $row['Id_pais'];?>" autocomplete="off">
<label for="">Id pais</label>
</div>
<div class="">
<input type="text" name="txtNombre" minlength="3" value="<?php echo $row['nombre'];?>" autocomplete="off" required><br><br>
<label for="">Nombre pais</label>
</div>
<button onclick="f1()" class="btn" >Modificar</button>
</form>
</div>
<div class="form-info">
<div class="">
<h2><span style="color:rgb(19, 23, 82);">Actualice registros</span> de manera rapida.</h2>
<p style="font-size:19px; font-weight:bold">Almacene el nombre de cada pais para poder utilizarlos al momento de ingresar nuevas monedas y realizar conversiones.</p>
</div>
<p style="color:#000; font-weight:500" class="alerta"><span style="color:red; font-weight:bold">NOTA:</span> De preferencia escriba correctamente el nombre del pais <br> de esta manera se evitaran problemas. </p>
<div class="">
<img style="fill: none;" src="../../IMAGES/mundos.gif" alt="">
</div>
</div>
</div>
</div>
</body>
<script>
var f=document.getElementById("form");
function f1(){
swal({
title: 'Esta seguro que quiere borra estos datos?',
text: 'No los podrá recuperar!',
type: 'warning',
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: 'SI!',
cancelButtonText: 'No!',
closeOnConfirm: false,
closeOnCancel: false
}).then(function() {
f.submit();
});
}
</script>
</html><file_sep>/PHP/tblMonedas/eliminarMoneda.php
<DOCTYPE! html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="CSS/estilos.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<title>Eliminar registro</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
</head>
<body >
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<a href="index.html"> <img src="../../IMAGES/divisas9.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button onclick="location.href ='../../index.html'" class="dropdown-btn" >Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="#" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="#" class="">Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="#" class="">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="#" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button style="background:#000;" class="dropdown-btn active" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="#" class="">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="./MostrarMoneda.php" class="">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="./ModificarMoneda.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="#" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="PHP/createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="PHP/dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- <a href="" class="btn">Realizar conversion <i class="fas fa-trash-alt"></i></a>
<a href="" class="btn">Mantenimiento Paises <i class="fas fa-globe-americas"></i><a>
<a href="" class="btn">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></a> -->
</div>
</nav>
<?php
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($connecction,"utf8");
$idMoneda = $_REQUEST['id_moneda'];
$query = "call EliminarMoneda('$idMoneda');";
$runQuery=mysqli_query( $connecction, $query ) ;
if ($runQuery)
{
echo
'<script>
swal({
title: "Éxito",
text: "Se eliminó correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
else
{
echo
'<script>
swal({
title: "ERROR!",
text: "No se Elimino nada en la Base",
type: "error",
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
//liberando recursos y cerrando la BD;
mysqli_close($connecction);
?>
<br><br>
</div>
</body>
</html>|
<file_sep>/PHP/tblpaises/eliminar.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<title>Eliminar registro</title>
</head>
<body>
<?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
if(isset($_REQUEST['cf'])){
$Idpais=$_REQUEST['Id_pais'];
$resultado=mysqli_query( $conexion, "select id_moneda from tblmonedas where id_pais=".$Idpais.";");
if($fila=mysqli_fetch_row($resultado)){
$idmone=$fila[0];
$consulta="call EliminarMoneda($idmone);";
$resultado=mysqli_query( $conexion, $consulta );
}
$consulta="call EliminarPais($Idpais);";
//echo($consulta);
$resultado=mysqli_query( $conexion, $consulta ) or die ( "No se puede eliminar el registro");
if($resultado)
{
echo ("El registo fue eliminado de forma satisfactoria.<br>");
header("Location:Mostra.php");
}
else
{
echo ("Surgio un problema al momento de eliminar el registro.<br>");
echo ("El problema es:.<br>");
echo ("Codigo del error.<br>".mysql_errno()."</br><br>");
echo ("Descripcion del error.<br>".mysql_error()."</br><br>");
}
}else if(isset($_REQUEST['Id_pais'])){
echo
'<script>
swal({
title: "Esta seguro que quiere borra estos datos?",
text: "No los podrá recuperar!",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "SI!",
cancelButtonText: "No!",
closeOnConfirm: false,
closeOnCancel: false
}).then(function() {
window.location = "eliminar.php?Id_pais='.$_REQUEST['Id_pais'].'&cf=1";
}).catch(function() {
window.location = "Mostra.php";
});
</script>';
}
// cerrar conexión de base de datos
mysqli_close( $conexion );
?>
</body>
</html><file_sep>/JS/main.js
window.onload = () => {
console.log("Js esta funcionando0000");
const newLocal = "ffrgrgggrgg";
console.log(newLocal);
let conversion = () =>{
console.log("hols")
}
console.log(conversion);
conversion();
}
<file_sep>/PHP/dropDB.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="CSS/style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<title>DROP DB</title>
</head>
<body>
<?php
include("../include/config.inc");
$connection = mysqli_connect($server, $user, $password, $DB);
mysqli_set_charset($connection, "utf8");
$query = "DROP DATABASE IF EXISTS BasePaises";
$runQuery = mysqli_query($connection, $query);
if ($runQuery) {
echo
'<script>
swal({
title: "Buen trabajo",
text: "La base de datos ha sido eliminada correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "../index.html";
});
</script>';
} else
{
echo
'<script>
swal({
title: "ERROR!",
text: "No hay ninguna base de datos, cree una.",
type: "error"
}).then(function() {
window.location = "../index.html";
});
</script>';
}
mysqli_close($conexion);
?>
<br>
<a class="btn btn-primary" href="../index.html">IR A LA PAGINA INICIAL</a>
</body>
</html>
<file_sep>/PHP/conversiones/conversion.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="../../plugins/animate.css/animate.css">
<link rel="stylesheet" href="../../plugins/sweetAlert2/sweetalert2.min.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<!-- AJAX -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="<KEY>8ycbRAkjPDc="
crossorigin="anonymous"></script>
<!-- SWEETALERT -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<title>Realizar conversion</title>
</head>
<body>
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<span class="fondo"></span><a href="../../index.html"> <img src="../../IMAGES/divisas7.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button style="background:#000;" onclick="location.href ='../../index.html'" class="dropdown-btn activee" >Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
<a href="./conversion.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Realizar conversion <i class="fas fa-dollar-sign"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="../tblpaises/insertarRegistro.html" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="../tblpaises/Mostra.php" class="">Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblpaises/Mostra.php" class="">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="../tblpaises/Mostra.php" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="../tblMonedas/insertarMoneda.php" class="">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="../createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="../dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
</div>
</div>
</nav>
<div class="containeer-contenido">
<div class="form-box" style="display: flex; flex-flow:column nowrap; align-items:center; justify-content: center;">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" class="" id="lista"><br><br>
<h2>Conversion de moneda</h2><br>
<div>
<h6 style="font-weight:initial;">
Seleccione la moneda a la cual desea convetir el valor:
</h6>
<select name="conversion" id="sele" required>
<option value="">Seleccione moneda...</option>
<?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
$query = "select nombre from tblMonedas;";
$runQuery = mysqli_query($conexion, $query);
while ($row = mysqli_fetch_array($runQuery)){
?>
<option style="color:#000;" value="<?php echo $row['nombre']?>">
<?php echo $row['nombre']?>
</option>
<?php
}
?>
</select>
</div>
</form>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>" class="" >
<div class="">
<input type="text" name="moneda" value="<?php if(isset($_POST['conversion'])){echo $_POST['conversion']; }?>" readonly required>
<label for="" style="position:absolute; left:25px;"></label>
</div>
<div class="">
<input type="radio" name="crb" checked style="margin-left:100px;" <?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
if(isset($_POST['conversion'])){
$vl=$_POST['conversion'];
//$query = "select nombre from tblMonedas;";
$query = "select val_dolar from tblMonedas where nombre='$vl'";
$runQuery = mysqli_query($conexion, $query);
if($row = mysqli_fetch_array($runQuery)){
echo "value=".$row['val_dolar']."";
}
}
//
?> id="rb1">
<label for="" style="position:absolute; left:25px;" id="lbl1">Dolar a <?php if(isset($_POST['conversion'])){echo $_POST['conversion']; }?></label>
</div>
<div class="">
<input type="radio" name="crb" style="margin-left:100px;" <?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
if(isset($_POST['conversion'])){
$vl=$_POST['conversion'];
//$query = "select nombre from tblMonedas;";
$query = "select val_local from tblMonedas where nombre='$vl'";
$runQuery = mysqli_query($conexion, $query);
if($row = mysqli_fetch_array($runQuery)){
echo "value=".$row['val_local']."";
}
}
//
?> id="rb2">
<label for="" style="position:absolute; left:25px;" id="lbl2"><?php if(isset($_POST['conversion'])){echo $_POST['conversion']; }?> a Dolar</label>
</div>
<div class="">
<input type="number" name="cantidad" min="0.01" step=".01" id="cantidad" required>
<label for="" style="position:absolute; left:25px;" >Cantidad a convertir</label>
</div>
<div class="buttons">
<input type="submit" style="width:110px" value="Convertir" name=submit class="" id="btn">
</div>
<input type="text" name="texto" id="texto" style="display:none;" value="Dolar a <?php if(isset($_POST['conversion'])){echo $_POST['conversion']; }?>">
</form>
<!-- FIN DEL FORM-BOX -->
</div>
<div class="form-info">
<h1>CONVERSIONES <span style="color:rgb(150, 90, 193);"> AL INSTANTE</span></h1>
<div class="infa" style=" background:rgba(0,0,0,0.6); border:2px solid #000; box-shadow: 4px 4px 4px rgba(0, 0, 0, .0.6);">
<script>
var s =document.getElementById("sele");
var f =document.getElementById("lista");
var texto =document.getElementById("texto");
var rb1 =document.getElementById("rb1");
var rb2 =document.getElementById("rb2");
var lbl1 =document.getElementById("lbl1");
var lbl2 =document.getElementById("lbl2");
s.addEventListener("change",()=>{
f.submit();
})
rb1.addEventListener("change",()=>{
texto.value=lbl1.textContent;
//console.log(texto.textContent)
})
rb2.addEventListener("change",()=>{
texto.value=lbl2.textContent;
//console.log(texto.textContent)
})
</script>
<?php
if(isset($_POST['submit'])){
if($_POST['moneda']==""){
echo
'<script>
swal({
title: "ERROR!",
text: "Seleccione una moneda primero.",
type: "error"
}).then(function() {
});
</script>';
}else{
$valor=$_POST['cantidad']*$_POST['crb'];
/*echo "<script>
alert(".$valor.")
</script>";*/
echo '<p style="font-size:75px;color:#fff;" >'.$_POST['cantidad']." de ".$_POST['texto'].' son:</p>';
echo '<p style="font-size:75px;color:#fff;">'.$valor.'</p>';
}
}
?>
</div>
</div>
</div>
</body>
</html><file_sep>/PHP/tblMonedas/insertarMoneda.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- CDN DE ESTILOS PROPIOS -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="CSS/estilos.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<title>Insertar Moneda</title>
</head>
<body>
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<span class="fondo"></span><a href="../../index.html"> <img src="../../IMAGES/divisas7.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button onclick="location.href ='../../index.html'" class="dropdown-btn">Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
<a href="../conversiones/conversion.php" class="">Realizar conversion <i class="fas fa-dollar-sign"></i></a>
<a href="../../integrantes.html" class="">Lista de integrantes <i class="fas fa-users"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="../tblpaises/insertarRegistro.html" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="../tblpaises/Mostra.php" class="">Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblpaises/Mostra.php" class="">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="../tblpaises/Mostra.php" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button class="dropdown-btn activee" style="background:#000;" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="./insertarMoneda.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="./MostrarMoneda.php" class="">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="./MostrarMoneda.php" class="">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="./MostrarMoneda.php" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="../createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="../dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
<!-- </div>
<a href="" class="btn">Realizar conversion <i class="fas fa-trash-alt"></i></a>
<a href="" class="btn">Mantenimiento Paises <i class="fas fa-globe-americas"></i><a>
<a href="" class="btn">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></a>
</div> -->
</nav>
<div class="containeer-contenido">
<div class="form-box">
<form action="InsertarMone.php" method="post">
<h2>Ingrese la informacion</h2>
<div class="">
<input type="text" name="txtNombreM" minlength="3" required autocomplete="off">
<label class="" style="position:absolute; left:20px;">Nombre moneda</label>
</div>
<div class="">
<input type="number" name="VL" step=".01" min="0" required autocomplete="off">
<label class="" style="position:absolute; left:20px;">Valor local</label>
</div>
<div class="">
<input type="number" name="VD" step=".01" min="0" required autocomplete="off">
<label class="" style="position:absolute; left:20px;">Valor en dolar</label>
</div>
Seleccione el pais: <select name="slpais" id="" required>
<option value="">Seleccione...</option>
<?php
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
+mysqli_set_charset($connecction,"utf8");
$query = "select nombre from tblpaises;";
$runQuery=mysqli_query( $connecction, $query );
while ($row=mysqli_fetch_array($runQuery))
{
?>
<option style="color:#000" value="<?php echo $row['nombre']?>"><?php echo $row['nombre']?></option>
<?php
}
?>
</select>
<?php
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($connecction,"utf8");
mysqli_close($connecction);
?>
<div style="margin-top:1em;">
<input style="margin-bottom:0;" type="submit" value="Enviar">
<input style="margin-bottom:0; border-bottom: 2px solid rgb(102, 157, 219)" type="reset" value="Cancelar">
</div>
</form>
</div>
<div class="form-info">
<div class="">
<h2><span style="color:rgb(19, 23, 82);">Realice ahora</span> el cambio.</h2>
<p style="font-size:19px; font-weight:bold">Solo almancene el valor de la equivalencia de cualquier moneda y cualquiera pais,<br>y uselas para siempre!!!.</p>
</div>
<p style="color:#000; font-weight:500" class="alerta"><span style="color:red; font-weight:bold">NOTA:</span> el valor local y el valor en dolar solo acepta 2 numeros maximo como decimal por cada moneda.<br>Para ingresar la moneda de un pais debe haber registrado previamente dicho pais. </p>
<div class="">
<img style="fill: none;" src="../../IMAGES/mundos.gif" alt="">
</div>
<!-- <div id="carouselExampleIndicators slide" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="3"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="../../IMAGES/monedas1.jpg" class="d-block w-100" alt="DIVISAS">
</div>
<div class="carousel-item">
<img src="../../IMAGES/monedas3.jpg" class="d-block w-100" alt="DIVISAS">
</div>
<div class="carousel-item">
<img src="../../IMAGES/monedas4.png" class="d-block w-100" alt="DIVISAS">
</div>
<div class="carousel-item">
<img src="../../IMAGES/monedas5.jpg" class="d-block w-100" alt="DIVISAS">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div> -->
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html><file_sep>/PHP/tblpaises/Mostra.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="CSS/estilos.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<title>Mostrando paises</title>
</head>
<body>
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<a href="../../index.html"> <img src="../../IMAGES/divisas7.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button onclick="location.href ='../../index.html'" class="dropdown-btn">Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
<a href="../conversiones/conversion.php" class="">Realizar conversion <i class="fas fa-dollar-sign"></i></a>
<a href="../../integrantes.html" class="">Lista de integrantes <i class="fas fa-users"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button style="background:#000;" class="dropdown-btn activee" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="./InsertarRegistro.html" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="./Mostra.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="./Mostra.php" class="">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="./Mostra.php" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="../tblMonedas/insertarMoneda.php" class="">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="../tblMonedas/MostrarMoneda.php" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="../createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="../dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- <a href="" class="btn">Realizar conversion <i class="fas fa-trash-alt"></i></a>
<a href="" class="btn">Mantenimiento Paises <i class="fas fa-globe-americas"></i><a>
<a href="" class="btn">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></a> -->
</div>
</nav>
<p>
<span class="antes"></span><span class="despues"></span>
<h1 style="text-align: center; margin:1em 0; font-weight:bold; color:#000;"> <span style="color:rgba(29, 3, 70, 0.8);"> Listado de paises almacenados</span> hasta este momento. <i class="fas fa-book"></i></h1>
</p>
<?php
include($_SERVER['DOCUMENT_ROOT'].'/DIVISAS/include/config.inc');
$conexion = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($conexion,"utf8");
$query="call MostrarPais();";
$runQuery=mysqli_query( $conexion, $query ) or die ( "No se pueden mostrar los registros");
echo"<table width='100%' border='1' align='center'>";
echo "<tr>";
echo "<th>Id País</th><th>Nombre</th><th>Eliminar</th><th>Modificar</th>";
echo "</tr>";
while ($row=mysqli_fetch_array($runQuery))
{
echo "<tr>";
echo "<td>",$row['Id_pais'],"</td>";
echo "<td>",$row['nombre'],"</td>";
echo "<td>"."<a class='btn' href='./eliminar.php?Id_pais=".$row['Id_pais']."'>Eliminar <i class='fas fa-trash-alt'></i></a>"."</td>";
echo "<td>"."<a class='btn' href='./modificar.php?Id_pais=".$row['Id_pais']."'>Modificar <i class='fas fa-edit'></i></a>"."</td>";
echo "</tr>";
}
echo "</table>";
// cerrar conexión de base de datos
mysqli_close( $conexion );
?>
<div class="santa">
<img class="" src="../../IMAGES/navidad.gif" alt="">
</div>
</div>
</body>
</html><file_sep>/JS/sweetalert.js
Swal.fire({
type: 'success',
title: 'Éxito',
text: '¡Perfecto!',
});<file_sep>/PHP/tblMonedas/InsertarMone.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Insertando...</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<style>
body{
background:#6EA7F5;
}
</style>
</head>
<body >
<?php
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($connecction,"utf8");
$nombre = $_POST["txtNombreM"];
$ValorLocal = $_POST["VL"];
$ValorDollar = $_POST["VD"];
$Pais = $_POST["slpais"];
$id="";
$query="select id_pais from tblpaises where nombre='$Pais'";
$runQuery=mysqli_query( $connecction, $query);
if ($runQuery)
{
while ($row=mysqli_fetch_array($runQuery))
{
$id=$row['id_pais'];
}
}
else
{
echo ("Surgio problema para Mostrar los registros.<br>");
echo ("El problema es: .<br>");
echo ("Codigo de error: .<b>".mysql_errno ()."</b><br>");
echo ("Descripcion de error: <b>".mysql_error ()."</b><br>");
}
$consulta="call CrearMoneda('$nombre','$ValorLocal','$ValorDollar','$id');";
$resultado=mysqli_query( $connecction, $consulta);
if ($resultado)
{
echo
'<script>
swal({
title: "Éxito",
text: "Se inserto correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
else
{
echo
'<script>
swal({
title: "ERROR!",
text: "No se Inserto nada en la Base",
type: "error",
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
//liberando recursos y cerrando la BD;
mysqli_close($connecction);
?>
<br><br>
</body>
</html><file_sep>/PHP/tblMonedas/MonedaUpdate.php
<html>
<head>
<title>Mostrar datos de tabla con MySQL</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<style>
body{
background:#6EA7F5;
}
</style>
</head>
<body >
<?php
//capturar el codigo a modificar
//cargar la connecction y octener la connecction activa $mysql
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($connecction,"utf8");
$idMoneda=$_POST['id_moneda2'];
$nombre = $_POST['txtnombre'];
$ValorLocal = $_POST['txtVL'];
$ValorDolar = $_POST['txtVD'];
$idPais = $_POST['slpais'];
$id="";
$query="select id_pais from tblpaises where nombre='$idPais';";
$runQuery=mysqli_query( $connecction, $query);
if ($runQuery)
{
while ($row=mysqli_fetch_array($runQuery))
{
$id=$row['id_pais'];
}
}
else
{
echo ("Surgio problema para Mostrar los registros.<br>");
echo ("El problema es: .<br>");
echo ("Codigo de error: .<b>".mysql_errno ()."</b><br>");
echo ("Descripcion de error: <b>".mysql_error ()."</b><br>");
}
$query = "call ModificarMonedas('$idMoneda','$nombre','$ValorLocal','$ValorDolar','$id')";
$runQuery=mysqli_query( $connecction, $query );
if ($runQuery)
{
echo
'<script>
swal({
title: "Éxito",
text: "Se Modificó correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
else
{
echo
'<script>
swal({
title: "ERROR!",
text: "No se Modificó nada en la Base",
type: "error",
}).then(function() {
window.location = "MostrarMoneda.php";
});
</script>';
}
mysqli_close($connecction);
?>
</body>
</html>|<file_sep>/PHP/createDB.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src='https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.11.4/sweetalert2.all.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<title>CREATE DB</title>
</head>
<body>
<?php
// Ejemplo de conexión a base de datos MySQL con PHP.
// Datos de la base de datos
$server = "localhost";
$user = "root";
$password = "";
$DB = "test";
// creación de la conexión a la base de datos con mysql_connect()
$conexion = mysqli_connect( $server, $user, $password) or die ("No se ha podido conectar al server de Base de datos");
// Selección de la base de datos a utilizar
$db = mysqli_select_db( $conexion, $DB ) or die ( "Upps! Pues no se ha podido conectar a la base de datos" );
//Realizando la query para crear una BD si es que no existe
$query="CREATE DATABASE BasePaises";
$runQuery = mysqli_query( $conexion, $query );
//Verificando si la BD se creo.
if ($runQuery)
echo
'<script>
swal({
title: "Buena trabajo",
text: "La base de datos ha sido creada correctamente!",
type: "success",
confirmButtonText: "Continuar"
}).then(function() {
window.location = "../index.html";
});
</script>';
else
{
echo
'<script>
swal({
title: "ERROR!",
text: "ya existe la base de datos.",
type: "error"
}).then(function() {
window.location = "../index.html";
});
</script>';
}
$DB = "BasePaises";
$db = mysqli_select_db($conexion, $DB) or die("Upps! no se ha podido conectar a la nueva Base de Datos");
//Realizando la query para crear la tabla Alumno si es que no existe
$query="CREATE TABLE tblpaises (
Id_pais INT PRIMARY KEY AUTO_INCREMENT,
nombre varchar(50)
)";
$runQuery = mysqli_query($conexion, $query) or die("no se pudo crear la tabla tblpaises");
//Verificando si la tabla se creo.
if ($runQuery)
echo ("La tabla tblpaises fue creada de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear la tblpaises.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>".mysql_error()."</b><br>");
echo ("Descripcion de error: <b>".mysql_error ()."</b><br>");
}
//Realizando la query para crear la tabla Alumno si es que no existe
$query="CREATE TABLE tblMonedas (
id_moneda INT PRIMARY KEY AUTO_INCREMENT,
nombre varchar(20),
val_local float,
val_dolar float,
id_pais int,
foreign key(id_pais) references tblpaises(Id_pais)
)";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear la tabla tblMonedas");
//Verificando si la tabla se creo.
if ($runQuery)
echo ("La tabla tblMonedas fue creada de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear la tblMonedas.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE CrearPais
(
IN nom VARCHAR(50)
)
insert into tblpaises (nombre)
values (nom)";
$runQuery = mysqli_query($conexion, $query) ;
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP CrearPais fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP CrearPais.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE ModificarPais
(
IN par_idPais INT,
IN par_nombre VARCHAR(50)
)
update tblpaises set nombre = par_nombre where Id_pais = par_idPais";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP ModificarPais");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP ModificarPais fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP ModificarPais.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE EliminarPais
(
IN par_idPais INT
)
delete from tblpaises where Id_pais = par_idPais";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP EliminarPais");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP EliminarPais fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP EliminarPais.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE MostrarPais
(
)
SELECT * FROM tblpaises";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP MostrarPais");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP MostrarPais fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP MostrarPais.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error()."</b><br>");
}
$query="CREATE PROCEDURE MostrarPaisPorId
(
IN par_idpais INT
)
SELECT * FROM tblpaises
where id_pais = par_idpais;";
$runQuery = mysqli_query( $conexion, $query ) or die ( "No se pudo crear el procedimiento almacenado MostrarPaisPorId ");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP MostrarPaisPorId fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP MostrarPaisPorId.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error()."</b><br>");
}
$query="CREATE PROCEDURE CrearMoneda
(
IN nom VARCHAR(50),
IN val_l float,
IN val_d float,
IN id_pa int
)
insert into tblMonedas (nombre,val_local,val_dolar,id_pais)
values (nom,val_l,val_d,id_pa)";
$runQuery = mysqli_query($conexion, $query) ;
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP CrearMoneda fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP CrearMoneda.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE ModificarMonedas
(
IN par_idMoneda INT,
IN nom VARCHAR(50),
IN val_l float,
IN val_d float,
IN id_pa int
)
update tblMonedas set nombre = nom,val_local=val_l,val_dolar=val_d,id_pais=id_pa where id_moneda = par_idMoneda";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP ModificarMonedas");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP ModificarMonedas
fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP ModificarMonedas
.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE EliminarMoneda
(
IN par_idMoneda INT
)
delete from tblMonedas where id_moneda = par_idMoneda";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP EliminarMoneda");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP EliminarMoneda fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP EliminarMoneda.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error ()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error ()."</b><br>");
}
$query="CREATE PROCEDURE MostraMonedas
(
)
SELECT * FROM tblMonedas";
$runQuery = mysqli_query($conexion, $query) or die ("No se pudo crear el SP MostraMonedas");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP MostraMonedas fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP MostraMonedas.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error()."</b><br>");
}
$query="CREATE PROCEDURE MostraMonedasPorId
(
IN par_idMoneda INT
)
SELECT * FROM tblMonedas
where id_moneda = par_idMoneda;";
$runQuery = mysqli_query( $conexion, $query ) or die ( "No se pudo crear el procedimiento almacenado MostraMonedasPorId ");
//Verificando si el SP se creo.
if ($runQuery)
echo ("El SP MostraMonedasPorId fue creado de Forma satisfactoria.<br>");
else
{
echo ("Surgio problema para crear el SP MostraMonedasPorId.<br>");
echo ("El problema es: <br>");
echo ("Codigo de error: <b>". mysql_error()."</b><br>");
echo ("Descripcion de error: <b>". mysql_error()."</b><br>");
}
?>
</body>
</html>
<file_sep>/PHP/tblMonedas/MostrarMoneda.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CDN DE BOOTSTRAP -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CDN DE FONT AWESOME -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="<KEY> crossorigin="anonymous" />
<!-- HOJAS DE ESTILOS CREADAS PROPIAMENTE -->
<link rel="stylesheet" href="../../CSS/style.css">
<link rel="stylesheet" href="CSS/estilos.css">
<!-- LINKS DE REFERENCIA DE GOOGLE FONTS -->
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<title>Mostrando Monedas</title>
</head>
<div class="containeer">
<nav class="menu">
<div class="menu-logo">
<a href="../../index.html"> <img src="../../IMAGES/divisas7.png" alt="DIVISAS"> </a>
</div>
<div class="menu-button">
<!-- MENU DROPDOWN PARA CONVERSION DE DIVISAS -->
<div class="dropdown">
<button onclick="location.href ='../../index.html'" class="dropdown-btn">Pagina principal <i class="fas fa-home"></i></button>
<div class="dropdown-content">
<a href="../conversiones/conversion.php" class="">Realizar conversion <i class="fas fa-dollar-sign"></i></a>
<a href="../../integrantes.html" class="">Lista de integrantes <i class="fas fa-users"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA PAISES -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento Paises <i class="fas fa-globe-americas"></i></button>
<div class="dropdown-content">
<a href="../tblpaises/insertarRegistro.html" class="">Ingresar nuevo pais <i class="fas fa-table"></i></a>
<a href="../tblpaises/Mostra.php" class="">Ver pasies existentes <i class="fas fa-list-ol"></i></a>
<a href="../tblpaises/Mostra.php" class="">Modificar pais existente <i class="fas fa-edit"></i></a>
<a href="../tblpaises/Mostra.php" class="">Eliminar pais existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA TABLA MONEDAS -->
<div class="dropdown">
<button style="background:#000;" class="dropdown-btn activee" href="#">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></button>
<div class="dropdown-content">
<a href="./insertarMoneda.php" class="">Ingresar nueva moneda <i class="fas fa-table"></i></a>
<a href="./MostrarMoneda.php" class="" style="background:#3a3a3a; color:#fff;border-radius:9px;">Ver monedas existentes <i class="fas fa-list-ol"></i></a>
<a href="./MostrarMoneda.php" class="">Modificar moneda existente <i class="fas fa-edit"></i></a>
<a href="./MostrarMoneda.php" class="">Eliminar moneda existente <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- MENU DROPDOWN PARA MANTENIMIENTO DE LA BASE -->
<div class="dropdown">
<button class="dropdown-btn" href="#">Mantenimiento base de datos <i class="fas fa-database"></i></button>
<div class="dropdown-content">
<a href="../createDB.php" class="">Crear base de datos <i class="fas fa-database"></i></a>
<a href="../dropDB.php" class="">Eliminar base de datos <i class="fas fa-trash-alt"></i></a>
</div>
</div>
<!-- <a href="" class="btn">Realizar conversion <i class="fas fa-trash-alt"></i></a>
<a href="" class="btn">Mantenimiento Paises <i class="fas fa-globe-americas"></i><a>
<a href="" class="btn">Mantenimiento Monedas <i class="fab fa-bitcoin"></i></a> -->
</div>
</nav>
<p>
<span class="antes"></span><span class="despues"></span>
<h1 style="text-align: center; margin:1em 0; font-weight:bold; color:#000;"> <span style="color:rgba(29, 3, 70, 0.8);"> Listado de monedas almacenadas</span> hasta este momento. <i class="fas fa-book"></i></h1>
</p>
<?php
include('../../include/config.inc');
$connecction = mysqli_connect($server,$user,$password,$DB);
mysqli_set_charset($connecction,"utf8");
$consulta = "call MostraMonedas;";
$resultado=mysqli_query( $connecction, $consulta ) or die ( "No se puede Mostrar los registros");
if ($resultado)
{
echo"<table width='100%' border='1' align='center'>";
echo "<tr>";
echo "<th>id_moneda</th> <th>nombre</th> <th>valor local</th> <th>valor en dolar</th> <th>id_pais</th> <th>Eliminar<th/> Modificar";
echo "</tr>";
while ($row=mysqli_fetch_array($resultado))
{
echo "<tr>";
echo "<td>",$row['id_moneda'],"</td>";
echo "<td>",$row['nombre'],"</td>";
echo "<td>",$row['val_local'],"</td>";
echo "<td>","$".$row['val_dolar'],"</td>";
echo "<td>",$row['id_pais'],"</td>";
echo "<td>"."<a class='btn' href='./eliminarMoneda.php?id_moneda=".$row['id_moneda']."'>Eliminar <i class='fas fa-trash-alt'></i></a>"."</td>";
echo "<td>"."<a class='btn' href='./ModificarMoneda.php?id_moneda=".$row['id_moneda']."'>Modificar <i class='fas fa-edit'></i> </a>"."</td>";
echo "</tr>";
}
}
else
{
echo ("Surgio problema para Mostrar los registros.<br>");
echo ("El problema es: .<br>");
echo ("Codigo de error: .<b>".mysql_errno ()."</b><br>");
echo ("Descripcion de error: <b>".mysql_error ()."</b><br>");
}
echo ("</table>");
//liberando recursos y cerrando la BD;
mysqli_close($connecction);
?>
<div class="santa">
<img class="" src="../../IMAGES/navidad.gif" alt="">
</div>
</div>
</body>
</html> | c6da5e1129b5169587c959a86fbd54dd3060a43e | [
"JavaScript",
"PHP"
] | 15 | PHP | IvanMendoz/PROYECTO-DPWEB-DIVISAS | eb8737f30ae4c4bb802575f9f7bec8b2152ebbb5 | 20fb05b46d39c94221fbeabd10b7de2c228a63ac |
refs/heads/master | <file_sep>#!/bin/bash
###### 定义变量
server_install_log_path="/tmp/server_install.log"
date_show_str=`date '+%Y-%m-%d %H:%M:%S'`
install_php_path="/usr/local"
libmcryptp_tar_gz="libmcrypt-2.5.8.tar.gz"
libmcrypt_dir="libmcrypt-2.5.8"
libmcrypt_name="libmcrypt"
php_tar_gz="php-7.1.7.tar.gz"
php_dir="php-7.1.7"
php_name="php"
php_upload_config_path="php/www.conf"
php_opcache_path="php/opcache.txt"
install_php(){
###### 判断文件是否存在
if [ -e "${install_php_path}/${php_name}" ]
then
echo "${date_show_str} ----- php已经安装 -----"
echo "${date_show_str} ----- php已经安装 -----" >> ${server_install_log_path}
php_version=`php -v`
echo "${date_show_str} ----- php版本:${php_version} -----"
echo "${date_show_str} ----- php版本:${php_version} -----" >> ${server_install_log_path}
else
##### libmcrypt安装
if [ -e "${libmcryptp_tar_gz}" ]
then
echo "${date_show_str} ----- ${libmcryptp_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${libmcryptp_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${libmcryptp_tar_gz} -----"
echo "${date_show_str} ----- 解压${libmcryptp_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${libmcryptp_tar_gz}
cd ${libmcrypt_dir}
./configure
make && make install
echo "${date_show_str} ----- 成功安装libmcrypt -----"
echo "${date_show_str} ----- 成功安装libmcrypt -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
else
echo "${date_show_str} ----- 请先上传${libmcryptp_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${libmcryptp_tar_gz} -----" >> ${server_install_log_path}
fi
###### 判断文件是否存在
if [ -e ${php_tar_gz} ]
then
echo "${date_show_str} ----- ${php_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${php_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
##### PHP安装(fastcgi运行模式)
##### 安装相关库文件
echo "${date_show_str} ----- 安装相关库文件 -----"
echo "${date_show_str} ----- 安装相关库文件 -----" >> ${server_install_log_path}
yum -y install libmcrypt-devel mhash-devel libxslt-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel gcc gcc-c++
echo "${date_show_str} ----- 解压${php_tar_gz} -----"
echo "${date_show_str} ----- 解压${php_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${php_tar_gz}
cd ${php_dir}
echo "${date_show_str} ----- 执行配置 -----"
echo "${date_show_str} ----- 执行配置 -----" >> ${server_install_log_path}
./configure --prefix=${install_php_path}/${php_name} \
--with-curl \
--with-freetype-dir \
--with-gd \
--with-gettext \
--with-iconv-dir \
--with-kerberos \
--with-libdir=lib64 \
--with-libxml-dir \
--with-mysqli \
--with-openssl \
--with-pcre-regex \
--with-pdo-mysql \
--with-pdo-sqlite \
--with-pear \
--with-png-dir \
--with-xmlrpc \
--with-xsl \
--with-zlib \
--enable-fpm \
--enable-bcmath \
--enable-libxml \
--enable-inline-optimization \
--enable-gd-native-ttf \
--enable-mbregex \
--enable-mbstring \
--enable-opcache \
--enable-pcntl \
--enable-shmop \
--enable-soap \
--enable-sockets \
--enable-sysvsem \
--enable-xml \
--enable-zip \
--with-jpeg-dir \
--with-mcrypt \
--enable-exif
##### 执行安装
echo "${date_show_str} ----- 执行安装 -----"
echo "${date_show_str} ----- 执行安装 -----" >> ${server_install_log_path}
make && make install
##### 修改配置文件
cp -rf php.ini-development ${install_php_path}/${php_name}/lib/php.ini
cp -rf ${install_php_path}/${php_name}/etc/php-fpm.conf.default ${install_php_path}/${php_name}/etc/php-fpm.conf
##### cp /usr/local/php/etc/php-fpm.d/www.conf.default /usr/local/php/etc/php-fpm.d/www.conf
##### 开机启动
#### cp -Rf ./sapi/fpm/php-fpm /etc/init.d/php-fpm
cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
echo "${date_show_str} ----- 成功安装php -----"
echo "${date_show_str} ----- 成功安装php -----" >> ${server_install_log_path}
##### 设置变量环境
echo "${date_show_str} ----- 设置变量环境 -----"
echo "${date_show_str} ----- 设置变量环境 -----" >> ${server_install_log_path}
echo "PATH=$PATH:${install_php_path}/${php_name}/sbin" >> /etc/profile
export PATH=$PATH:${install_php_path}/${php_name}/sbin
echo "PATH=$PATH:${install_php_path}/${php_name}/bin" >> /etc/profile
export PATH=$PATH:${install_php_path}/${php_name}/bin
php_version=`php -v`
echo "${date_show_str} ----- php版本:${php_version} -----"
echo "${date_show_str} ----- php版本:${php_version} -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
cp -rf ${php_upload_config_path} ${install_php_path}/${php_name}/etc/php-fpm.d/www.conf
##### opcache 配置
cat ${php_opcache_path} >> ${install_php_path}/${php_name}/lib/php.ini
##### 启动
chmod +x /etc/init.d/php-fpm
echo "${date_show_str} ----- 启动php -----"
echo "${date_show_str} ----- 启动php -----" >> ${server_install_log_path}
/etc/init.d/php-fpm
else
echo "${date_show_str} ----- 请先上传${php_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${php_tar_gz}源码 -----" >> ${server_install_log_path}
fi
fi
}
##### 执行函数
install_php
<file_sep>#!/bin/bash
cat > test.log << EOF
#!/bin/bash
##### start #####
111
##### end #####
EOF
<file_sep><?php
system('./test.sh');
?>
<file_sep>#!/bin/bash
###### 定义变量
server_install_log_path="/tmp/server_install.log"
date_show_str=`date '+%Y-%m-%d %H:%M:%S'`
install_nginx_path="/usr/local"
pcre_tar_gz="pcre-8.35.tar.gz"
pcre_dir="pcre-8.35"
pcre_name="pcre-8.35"
nginx_tar_gz="nginx-1.12.0.tar.gz"
nginx_dir="nginx-1.12.0"
nginx_name="nginx"
nginx_upload_config_path="nginx/nginx.conf"
cut_nginx_log_upload_path="nginx/cut_nginx_log.sh"
cut_nginx_log_crontab="/var/spool/cron/root"
install_nginx(){
##### 一、安装编译工具及库文件
##### 二、首先要安装 PCRE
##### PCRE 作用是让 Ngnix 支持 Rewrite 功能。
###### 判断文件是否存在
if [ -e "${install_nginx_path}/${pcre_name}" ]
then
echo " ${date_show_str} ----- pcre已经安装 -----"
echo " ${date_show_str} ----- pcre已经安装 -----" >> ${server_install_log_path}
##### 查看版本 #####
pcre_version=`pcre-config --version`
echo "${date_show_str} ----- pcre版本:${pcre_version} -----"
echo "${date_show_str} ----- pcre版本:${pcre_version} -----" >> ${server_install_log_path}
else
###### 判断文件是否存在
if [ -e ${pcre_tar_gz} ]
then
echo "${date_show_str} ----- 安装编译工具及库文件 -----"
echo "${date_show_str} ----- 安装编译工具及库文件 -----" >> ${server_install_log_path}
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel
echo "${date_show_str} ----- ${pcre_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${pcre_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 开始安装pcre -----"
echo "${date_show_str} ----- 开始安装pcre -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${pcre_tar_gz} -----"
echo "${date_show_str} ----- 解压${pcre_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${pcre_tar_gz}
cd ${pcre_dir}
echo "${date_show_str} ----- 执行配置 -----"
echo "${date_show_str} ----- 执行配置 -----" >> ${server_install_log_path}
./configure
echo "${date_show_str} ----- 执行安装 -----"
echo "${date_show_str} ----- 执行安装 -----" >> ${server_install_log_path}
make && make install
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
mv ${pcre_dir} ${install_nginx_path}/${pcre_name}
echo "${date_show_str} ----- 成功安装pcre -----"
echo "${date_show_str} ----- 成功安装pcre -----" >> ${server_install_log_path}
##### 查看版本 #####
pcre_version=`pcre-config --version`
echo "${date_show_str} ----- pcre版本:${pcre_version} -----"
echo "${date_show_str} ----- pcre版本:${pcre_version} -----" >> ${server_install_log_path}
else
echo "${date_show_str} ----- 请先上传${pcre_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${pcre_tar_gz}源码 -----" >> ${server_install_log_path}
fi
fi
##### 三、安装nginx-1.12.0.tar.gz
###### 判断文件是否存在
if [ -e "${install_nginx_path}/${nginx_name}" ]
then
echo "${date_show_str} ----- nginx已经安装 -----"
echo "${date_show_str} ----- nginx已经安装 -----" >> ${server_install_log_path}
##### 查看版本 #####
nginx_version=`nginx -v`
echo "${date_show_str} ----- nginx版本:${nginx_version} -----"
echo "${date_show_str} ----- nginx版本:${nginx_version} -----" >> ${server_install_log_path}
else
###### 判断文件是否存在
if [ -e ${nginx_tar_gz} ]
then
echo "${date_show_str} ----- ${nginx_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${nginx_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 开始安装nginx -----"
echo "${date_show_str} ----- 开始安装nginx -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${nginx_tar_gz} -----"
echo "${date_show_str} ----- 解压${nginx_tar_gz} -----" >> ${server_install_log_path}
tar -zxvf ${nginx_tar_gz}
cd ${nginx_dir}
echo "${date_show_str} ----- 执行配置 -----"
echo "${date_show_str} ----- 执行配置 -----" >> ${server_install_log_path}
./configure --prefix=${install_nginx_path}/${nginx_name} --with-http_stub_status_module --with-stream --with-http_ssl_module --with-pcre=${install_nginx_path}/${pcre_name}
echo "${date_show_str} ----- 执行安装 -----"
echo "${date_show_str} ----- 执行安装 -----" >> ${server_install_log_path}
make && make install
##### 创建 Nginx 运行使用的用户 www
/usr/sbin/groupadd www
/usr/sbin/useradd -g www www
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
##### 修改配置
cp -rf ${nginx_upload_config_path} ${install_nginx_path}/${nginx_name}/conf/
##### 设置启动脚本
echo "${install_nginx_path}/${nginx_name}/sbin/nginx" >> /etc/rc.local
##### 启动nginx
echo "${date_show_str} ----- 启动nginx -----"
echo "${date_show_str} ----- 启动nginx -----" >> ${server_install_log_path}
${install_nginx_path}/${nginx_name}/sbin/nginx
##### 设置变量环境
echo "${date_show_str} ----- 设置变量环境 -----"
echo "${date_show_str} ----- 设置变量环境 -----" >> ${server_install_log_path}
echo "PATH=$PATH:${install_nginx_path}/${nginx_name}/sbin" >> /etc/profile
export PATH=$PATH:${install_nginx_path}/${nginx_name}/sbin
cut_nginx_log
echo "${date_show_str} ----- 成功安装nginx -----"
echo "${date_show_str} ----- 成功安装nginx -----" >> ${server_install_log_path}
##### 查看版本 #####
nginx_version=`nginx -v`
echo "${date_show_str} ----- nginx版本:${nginx_version} -----"
echo "${date_show_str} ----- nginx版本:${nginx_version} -----" >> ${server_install_log_path}
else
echo "----- 请先上传${nginx_tar_gz}源码 -----"
echo "----- 请先上传${nginx_tar_gz}源码 -----" >> ${server_install_log_path}
fi
fi
}
cut_nginx_log(){
echo "${date_show_str} ----- 安装nginx定时切割日志 -----"
echo "${date_show_str} ----- 安装nginx定时切割日志 -----" >> ${server_install_log_path}
##### 安装crond服务
yum -y install vixie-cron crontabs
cp -rf ${cut_nginx_log_upload_path} ${install_nginx_path}/${nginx_name}/sbin/
##### 赋予执行权限
chmod +x ${install_nginx_path}/${nginx_name}/sbin/cut_nginx_log.sh
##### 设置定时任务,每天00:00定时执行
##### crontab -e
##### 00 * * * /usr/local/nginx/sbin/cut_nginx_log.sh
echo "00 * * * ${install_nginx_path}/${nginx_name}/sbin/cut_nginx_log.sh" >> ${cut_nginx_log_crontab}
##### 启动crond服务
chkconfig crondon
service crond start
}
##### 执行函数
install_nginx
<file_sep>#!/bin/bash
###### php扩展安装
###### 定义变量
server_install_log_path="/tmp/server_install.log"
date_show_str=`date '+%Y-%m-%d %H:%M:%S'`
phpize_path="/usr/local/php/bin/phpize"
php_config_path="/usr/local/php/bin/php-config"
php_ini_path="/usr/local/php/lib/php.ini"
igbinary_tar_gz="igbinary-2.0.1.tgz"
igbinary_dir="igbinary-2.0.1"
igbinary_name="igbinary"
redis_server_tar_gz="redis-3.0.7.tar.gz"
redis_server_dir="redis-3.0.7"
redis_server_name="redis"
redis_server_path="/usr/local/redis"
local_pwd=`pwd`
redis_tar_gz="redis-3.1.2.tgz"
redis_dir="redis-3.1.2"
redis_name="redis"
ImageMagick_tar_gz="ImageMagick.tar.gz"
ImageMagick_dir="ImageMagick-6.8.9-7"
ImageMagick_name="ImageMagick"
imagick_tar_gz="imagick-3.4.3.tgz"
imagick_dir="imagick-3.4.3"
imagick_name="imagick"
##### igbinary安装
if [ -e "${igbinary_tar_gz}" ]
then
echo "${date_show_str} ----- ${igbinary_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${igbinary_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${igbinary_tar_gz} -----"
echo "${date_show_str} ----- 解压${igbinary_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${igbinary_tar_gz}
cd ${igbinary_dir}
##### phpize
${phpize_path}
./configure --with-php-config=${php_config_path}
make && make install
echo -e "\nextension=igbinary.so" >> ${php_ini_path}
echo "${date_show_str} ----- 成功安装igbinary -----"
echo "${date_show_str} ----- 成功安装igbinary -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
else
echo "${date_show_str} ----- 请先上传${igbinary_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${igbinary_tar_gz} -----" >> ${server_install_log_path}
fi
##### redis_server安装
if [ -e "${redis_server_tar_gz}" ]
then
echo "${date_show_str} ----- ${redis_server_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${redis_server_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${redis_server_tar_gz} -----"
echo "${date_show_str} ----- 解压${redis_server_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${redis_server_tar_gz}
cp -rf ${redis_server_dir} ${redis_server_path}
cd ${redis_server_path}
make && make install
cp -rf redis.conf /etc/
##### 将redis添加到自启动中
echo "/usr/local/bin/redis-server /etc/redis.conf &" >> /etc/rc.d/rc.local
##### 启动redis 先不要启动,还要修改配置才可以启动
##### redis-server /etc/redis.conf
echo "${date_show_str} ----- 成功安装redis_server -----"
echo "${date_show_str} ----- 成功安装redis_server -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ${local_pwd}
else
echo "${date_show_str} ----- 请先上传${redis_server_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${redis_server_tar_gz} -----" >> ${server_install_log_path}
fi
##### redis安装
if [ -e "${redis_tar_gz}" ]
then
echo "${date_show_str} ----- ${redis_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${redis_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${redis_tar_gz} -----"
echo "${date_show_str} ----- 解压${redis_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${redis_tar_gz}
cd ${redis_dir}
##### phpize
${phpize_path}
./configure --enable-redis-igbinary --with-php-config=${php_config_path}
make && make install
echo -e "\nextension=redis.so" >> ${php_ini_path}
echo "${date_show_str} ----- 成功安装redis -----"
echo "${date_show_str} ----- 成功安装redis -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
else
echo "${date_show_str} ----- 请先上传${redis_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${redis_tar_gz} -----" >> ${server_install_log_path}
fi
##### ImageMagick服务安装
if [ -e "${ImageMagick_tar_gz}" ]
then
echo "${date_show_str} ----- ${ImageMagick_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${ImageMagick_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${ImageMagick_tar_gz} -----"
echo "${date_show_str} ----- 解压${ImageMagick_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${ImageMagick_tar_gz}
cd ${ImageMagick_dir}
./configure --prefix=/usr/local/${ImageMagick_name}
make && make install
echo "${date_show_str} ----- 成功安装ImageMagick服务 -----"
echo "${date_show_str} ----- 成功安装ImageMagick服务 -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
else
echo "${date_show_str} ----- 请先上传${ImageMagick_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${ImageMagick_tar_gz} -----" >> ${server_install_log_path}
fi
##### imagick安装
if [ -e "${imagick_tar_gz}" ]
then
echo "${date_show_str} ----- ${imagick_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${imagick_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${imagick_tar_gz} -----"
echo "${date_show_str} ----- 解压${imagick_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${imagick_tar_gz}
cd ${imagick_dir}
##### phpize
${phpize_path}
./configure --with-imagick=/usr/local/${ImageMagick_name}/ --with-php-config=${php_config_path}
make && make install
echo -e "\nextension=imagick.so" >> ${php_ini_path}
echo "${date_show_str} ----- 成功安装imagick -----"
echo "${date_show_str} ----- 成功安装imagick -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ../
else
echo "${date_show_str} ----- 请先上传${imagick_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${imagick_tar_gz} -----" >> ${server_install_log_path}
fi
##### kill掉进程
pkill -9 -f "php-fpm" && /etc/init.d/php-fpm
##### 重新启动
##### /etc/init.d/php-fpm
<file_sep>#!/bin/bash
logs_path="/usr/local/nginx/logs/"
backup_path="/home/logs/"
mv ${logs_path}access.log ${backup_path}access_$(date +"%Y%m%d").log
mv ${logs_path}error.log ${backup_path}error_$(date +"%Y%m%d").log
/usr/local/nginx/sbin/nginx -s reopen<file_sep>#!/bin/bash
### »»×ª
chmod +x *.sh
dos2unix *.sh<file_sep>#!/bin/bash
###### redis服务安装 安装方法持别,所以放在最后
###### 定义变量 配置修改请查看redis/redis.txt
redis_server_tar_gz="redis-3.0.7.tar.gz"
redis_server_dir="redis-3.0.7"
redis_server_name="redis"
redis_server_path="/usr/local/redis"
local_pwd=`pwd`
##### redis_server安装
if [ -e "${redis_server_tar_gz}" ]
then
echo "${date_show_str} ----- ${redis_server_tar_gz}源码文件存在 -----"
echo "${date_show_str} ----- ${redis_server_tar_gz}源码文件存在 -----" >> ${server_install_log_path}
echo "${date_show_str} ----- 解压${redis_server_tar_gz} -----"
echo "${date_show_str} ----- 解压${redis_server_tar_gz} -----" >> ${server_install_log_path}
tar zxvf ${redis_server_tar_gz}
cp -r ${redis_server_dir} ${redis_server_path}
cd ${redis_server_path}
make && make install
cp redis.conf /etc/
##### 将redis添加到自启动中
echo "/usr/local/bin/redis-server /etc/redis.conf" >> /etc/rc.d/rc.local
##### 启动redis
redis-server /etc/redis.conf
echo "${date_show_str} ----- 成功安装redis_server -----"
echo "${date_show_str} ----- 成功安装redis_server -----" >> ${server_install_log_path}
##### 返回上一目录
echo "${date_show_str} ----- 返回上一目录 -----"
echo "${date_show_str} ----- 返回上一目录 -----" >> ${server_install_log_path}
cd ${local_pwd}
else
echo "${date_show_str} ----- 请先上传${redis_server_tar_gz}源码 -----"
echo "${date_show_str} ----- 请先上传${redis_server_tar_gz} -----" >> ${server_install_log_path}
fi<file_sep>#!/bin/bash
##### author:edgeto
##### 系统平台:CentOS
##### vim编辑器打开脚本, 运行::set ff?可以看到DOS或UNIX的字样. 使用set ff=unix把它强制为unix格式的, 然后存盘退出, 即可.
##### 网上也有很多的其他方法, 比如: 执行dos2unix 命令转换编码, 命令为: #dos2unix server.sh
##### 转换编码
./dos2unix.sh
##### 一键安装PHP7环境
##### 安装日志path
##### server_install_path="/tmp/server_install.log"
##### 一、安装nginx,详细看nginx.txt和nginx.sh
##### 引入nginx.sh
./nginx.sh
##### 二、安装php,详细看php.txt和php.sh
##### 引入php.sh
./php.sh
##### 三、安装php扩展
##### 引入php_extend.sh
./php_extend.sh
##### 四、安装mysql
##### 此处用开箱即用安装方法,不用源码安装,详情请看mysql.txt
<file_sep>## 根据自身需要写的一键安装php环境
## mysql用的是5.7,采用的是开箱即用版本,暂时没有写进脚本里面,详情在mysql/mysql.txt
+ 执行方法
+ 上传所有文件到linux服务器目录
+ 给dos2unix.sh加上执行权限
+ chmod +x dos2unix.sh
+ ./dos2unix.sh
+ 然后执行安装
+ ./server.sh
+ 安装日志在/tmp/server_install.log
| 17738df0468d5f9751a2c71df87e2ff5f5098b4b | [
"Markdown",
"PHP",
"Shell"
] | 10 | Shell | edgeto/oneKey | da0149f1e1d74c95a891e215cca7495f69120cdc | 6e86ff769081483d6135e145209ddc85f6761f2a |
refs/heads/master | <repo_name>high400/madlibgame<file_sep>/README.md
# madlibgame
code for madlib game
<file_sep>/madlibgame.py
color = input("Enter a color: ")
plural_noun = input("Enter a plural noun: ")
hero = input("Enter the name of a hero: ")
print("Swords are " + color)
print("Don't paint that " + plural_noun)
| e3407c4d229ef60a0e1cfedbad37d35a3b0394d8 | [
"Markdown",
"Python"
] | 2 | Markdown | high400/madlibgame | 7bba8afa6985fbe4c21e1d59355514429ba530c6 | caa1e59272baa67a5b3aadb9a164eea643bc7fad |
refs/heads/master | <repo_name>chirpy-io/chirpy-node<file_sep>/examples/track.js
/**
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Chirpy = require('../lib');
// Paste here your production token
var myProject = new Chirpy('token');
myProject.track('hey!', function(err) {
console.log(err);
});<file_sep>/lib/errors.js
/**
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var util = require('util');
var ApiError = exports.ApiError = function ChirpyError(statusCode, data) {
Error.call(this);
this.message = 'Status code: ' + statusCode;
this.errors = data && data.errors ? data.errors : {};
this.statusCode = statusCode;
};
util.inherits(ApiError, Error); | 7cb6d22e65375f0d4a64455d6a72b1e259c2e8e3 | [
"JavaScript"
] | 2 | JavaScript | chirpy-io/chirpy-node | 6457f36e4715a523b0bb0639fba50959885ae9ed | f74f8c304fafb8411638328ba8368e84aa5b37ed |
refs/heads/master | <file_sep>function isCydia() {
return navigator.userAgent.includes('Cydia');
}
function isLikelyIos() {
// iDevice matching in user agent string iPadOS 13+ loads desktop pages by default with macOS user agent IE pretends to be iOS sometimes
return (/iPhone|iPad|iPod/g.test(navigator.userAgent) || (navigator.platform == "MacIntel" && navigator.maxTouchPoints > 1)) && !window.MSStream;
}
document.addEventListener('DOMContentLoaded', () => {
if (isLikelyIos()) document.body.className = "";
}); | 54815302427a5d76c858558675fb56f82e5b1f82 | [
"JavaScript"
] | 1 | JavaScript | GlitchMasta47/repo | 678fe184fed7cad549931042ecb35e520222bc3e | 88584879c186242dd0021d80c0204ad6f8e2be72 |
refs/heads/main | <repo_name>TuuZzee/fe-storybook-cdk<file_sep>/src/index.ts
import Button from "./example/Button";
export { Button };<file_sep>/README.md
# fe-storybook-cdk
React component library using Storybook for Front-end projects.
Components can be published on `npm` and installed in other projects.
Build following [Creating a React component library using Storybook](https://prateeksurana.me/blog/react-component-library-using-storybook-6/#compiling-the-library-using-rollup) post.
### Installation
First clone the repository, then install the dependencies:
```sh
npm install
```
### Run Storybook
```sh
npm run storybook
``` | 2e4e856c62704dd8a6136bec6c9f061c4fdd2fd4 | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | TuuZzee/fe-storybook-cdk | d5878b7cf790ed85a8004cf284e1d389ba1a8ef4 | 73efb6cb6b2d6a2e7c083f5d7f0eff9323e73514 |
refs/heads/master | <file_sep>import org.junit.Assert;
import org.junit.jupiter.api.Test;
class CarTest {
@Test
void checkWinTest() {
Car car = new Car(12, 20);
car.finishX = 10;
car.finishY = 10;
car.round = 3;
//Tests round
Assert.assertTrue(car.checkWin());
//Tests, if checkWin increase round-number
Assert.assertNotEquals(car.round, 3);
//Tests if checkWin only returns True when rounds >2
car.round = 0;
Assert.assertFalse(car.checkWin());
}
@Test
void checkCheatWinTest() {
Car car = new Car(20, 20);
car.finishX = 10;
car.finishY = 10;
//Tests if checkCheatWin gets activated
Assert.assertFalse(car.checkCheatWin());
}
@Test
void checkCheat() {
Car car = new Car(156, 186);
//Tests if Car intersects with rectangle 1
Assert.assertFalse(car.checkCheat());
}
}<file_sep>
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ChooseCar {
private List<String> cars = new ArrayList<>();
public ChooseCar() {
String a = " ";
cars.add("images/Bugatti.png");
cars.add("images/Mercedes.png");
JFrame f = new JFrame();
f.setSize(1000,666);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BackgroundMenu bm = new BackgroundMenu();
int z = 400;
for (String car:cars) {
ImageIcon i = new ImageIcon(car);
JButton j = new JButton(a,i);
j.addActionListener(new ButtonListener(this,f));
f.add(j);
j.setSize(100,50);
j.setLocation(z,308);
z+=100;
a = a + " ";
}
f.add(bm);
}
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
}
<file_sep>import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FinishScreen extends JFrame{
private int width;
private int height;
public FinishScreen (int width, int height,double score) {
this.width=width;
this.height=height;
this.setSize(width, height);
this.setTitle("Finish");
this.setVisible(true);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lb = new JLabel();
this.add(lb,BorderLayout.NORTH);
String s = "Du hast "+score+" Sekunden gebraucht";
lb.setText(s);
BackgroundMenu bm =new BackgroundMenu();
this.add(bm,BorderLayout.CENTER);
JButton button = new JButton("Nochmal Spielen");
button.addActionListener(new ButtonListener(this));
this.add(button,BorderLayout.SOUTH);
}
}
| c296ecc00dffa06f1f5206b873565af3abec48bf | [
"Java"
] | 3 | Java | luedic/RoadRace | 67efc78079d0697949d38e8a3606e3e4b5d78242 | 1c7e25b49c10896ccc4920cc961803500e081c32 |
refs/heads/master | <file_sep>from client import TFTPClient
from socket import gethostname, gethostbyname
import os
def main():
try:
flag = True
buffer = []
host_name = gethostname()
addr = (gethostbyname(host_name), host_name)
(host, port) = input('Enter host:port --> ').split(':')
c = TFTPClient(host, port)
if c:
buffer.append('Connecting from host: {0} to host: {1}:{2}, mode: {3}'.format(addr, host, port, 'octet'))
for p in range(len(buffer)):
print(buffer.pop())
else:
flag = False
print("Could not create TFTPClient() with: {0}:{1}".format(host, port))
while flag:
method = input('\nEnter read/r, write/w, quit/q --> ').lower()
if method in ['quit', 'q']:
buffer.append("Flag off")
flag = False
else:
remote_file, local_file = input('Enter remote filename --> '), input('Enter local filename --> ')
if method in ['read', 'r']:
if not remote_file:
raise Exception("Remote file is invalid!");
else:
if not local_file:
local_file = remote_file
if c.read(remote_file, local_file):
if '.' in os.path.splitext(local_file)[-1]:
if os.path.isfile(local_file):
buffer.append("Successfully read file {0} from server {1}:{2} to path {3}/{4}".format(remote_file, host, port, os.getcwd(), local_file))
elif method in ['write', 'w']:
if not os.path.isfile(local_file):
raise Exception("File %s does not exist!" % local_file)
else:
if not remote_file:
remote_file = local_file
if c.write(local_file, remote_file):
buffer.append("Successfully wrote file {0} from path {1} to server {2}:{3}/{4}".format(local_file, os.getcwd(), host, port, remote_file))
for i in range(len(buffer)):
print(buffer.pop())
except Exception as err:
print("main.err: %s" % err)
finally:
print("Leaving. . .")
if __name__ == '__main__':
main()
<file_sep>import tkinter, os
from tkinter import *
from tkinter.filedialog import askopenfilename
from client import TFTPClient
class Tftp_gui(object):
def __init__(self, root):
self.host = tkinter.StringVar(root)
self.browse_value = tkinter.StringVar()
#labels
self._label1 = tkinter.LabelFrame(root, text = "Host:" )
self._label2 = tkinter.LabelFrame(root, text = "Port:" )
self._label3 = tkinter.LabelFrame(root, text = "Browse for file:" )
self._label4 = tkinter.LabelFrame(root, text = "Remote file name:" )
self._label5 = tkinter.LabelFrame(root, text = "Alternate file name:" )
#entry's
self._host = tkinter.Entry(self._label1, takefocus = 1, width = 30 )
self._port = tkinter.Entry(self._label2, width = 8 )
self.remote_file = tkinter.Entry(self._label4, width = 30 )
self.local_file = tkinter.Entry(self._label3, width = 30, textvariable=self.browse_value)
self.alt_filename = tkinter.Entry(self._label5, width = 30 )
#buttons
self.write = tkinter.Button(root, text = "Write", padx = 15, pady = 15, command = self.write_command )
self.read = tkinter.Button(root, text = "Read", padx = 15, pady = 15, command = self.read_command )
self.browse = tkinter.Button(self._label3, text = "Browse", command = self.browse_command)
#layout
self._label1.grid( in_ = root, column = 1, row = 1, columnspan = 1, rowspan = 1, sticky = "news", padx=5, pady=5)
self._label2.grid( in_ = root, column = 2, row = 1, columnspan = 1, rowspan = 1, sticky = "news", padx=5, pady=5 )
self._label3.grid( in_ = root, column = 1, row = 2, columnspan = 1, rowspan = 1, sticky = "news", padx=5, pady=5 )
self._label4.grid( in_ = root, column = 1, row = 3, columnspan = 1, rowspan = 1, sticky = "news", padx=5, pady=5 )
self._label5.grid( in_ = root, column = 1, row = 4, columnspan = 1, rowspan = 1, sticky = "news", padx=5, pady=5 )
self._host.grid( in_ = self._label1, column = 1, row = 1, columnspan = 1, padx = 5, pady = 5, rowspan = 1, sticky = "ew")
self._port.grid( in_ = self._label2, column = 1, row = 1, columnspan = 1, padx = 5, pady = 5, rowspan = 1, sticky = "ew" )
self.write.grid( in_ = root, column = 2, row = 2, columnspan = 1, padx = 5, pady = 5, rowspan = 1, sticky = "s" )
self.read.grid( in_ = root, column = 2, row = 3, columnspan = 1, padx = 5, pady = 5, rowspan = 1, sticky = "s" )
self.remote_file.grid( in_ = self._label4, column = 1, row = 1, padx = 5, pady = 5, columnspan = 1, rowspan = 1, sticky = "ew")
self.local_file.grid( in_ = self._label3, column = 1, row = 1, padx = 5, pady = 5, columnspan = 1, rowspan = 1, sticky = "ew")
self.browse.grid( in_ = self._label3, column = 1, row = 1, padx = 5, pady = 5, columnspan = 1, rowspan = 1, sticky = "e" )
self.alt_filename.grid( in_ = self._label5, column = 1, row = 1, columnspan = 1, padx = 5, pady = 5, rowspan = 1, sticky = "ew")
root.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
root.grid_rowconfigure(2, weight = 0, minsize = 73, pad = 0)
root.grid_rowconfigure(3, weight = 0, minsize = 25, pad = 0)
root.grid_rowconfigure(4, weight = 0, minsize = 25, pad = 0)
root.grid_columnconfigure(1, weight = 0, minsize = 100, pad = 0)
root.grid_columnconfigure(2, weight = 0, minsize = 15, pad = 0)
#root.grid_columnconfigure(3, weight = 0, minsize = 70, pad = 0)
self._label1.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label1.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label2.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label2.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label3.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label3.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label4.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label4.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label5.grid_rowconfigure(1, weight = 0, minsize = 40, pad = 0)
self._label5.grid_columnconfigure(1, weight = 0, minsize = 40, pad = 0)
def write_command(self):
c, file_name, alt_filename = TFTPClient(self._host.get(), self._port.get()), self.local_file.get(), self.alt_filename.get()
if not os.path.isfile(file_name):
raise Exception('File %s does not exist!' % file_name)
else:
if c.write(file_name, os.path.basename(file_name) if len(alt_filename) is 0 else alt_filename):
print('Success')
def read_command(self):
c,file_name, alt_filename = TFTPClient(self._host.get(), self._port.get()), self.remote_file.get(), self.alt_filename.get()
if c.read(file_name, file_name if len(alt_filename) is 0 else alt_filename):
if os.path.isfile(file_name):
print('Success')
def browse_command(self):
self.browse_value.set(askopenfilename())
def main():
try:
userinit()
except NameError:
pass
root = Tk()
window = Tftp_gui(root)
root.title('TftpClient')
root.resizable(width=FALSE, height=FALSE)
try:
run()
except NameError:
pass
root.protocol('WM_DELETE_WINDOW', root.quit)
root.mainloop()
if __name__ == '__main__':
main()
<file_sep>**************************************************
TFTP Client
**************************************************
author: <NAME><br>
email: <EMAIL><br>
website: https://olafurjohannsson.com<br>
Description:
Scripts and GUI that implements a client that Reads/Write's using the TFTP (Trivial File Transfer Protocol) desctribed in RFC 1350.
cmd.py is a command line script requires at least three arguments: host, command and filename. It also has two optional arguments, port and alternative name.
cmd2.py is a command line script that implements the same features, but instead of command line arguments it promts user for input.
gui.py is a gui version of the client. It can be initalized from the command line or by double clicking the gui.py file.
**************************************************
usage: cmd.py [-h] [-p PORT] [-a ALT_NAME] host command file_name
cmd.py tftp.example.com writes sample.txt
# Writes the file sample.txt to tftp.example.com
cmd.py tftp.example.com skrifar sample.txt -p 102 -a skra.txt
# Writes the file sample.txt to tftp.example.com on port 102 as skra.txt
cmd.py tftp.example.com reads sample.txt
# Reads the file sample.txt from tftp.example.com
cmd.py tftp.example.com lesa sample.txt -p 102 -a skra.txt
# Reads the file sample.txt from tftp.example.com on port 102 as skra.txt
**************************************************
Arguments:
positional arguments:
host the host to connect to
command enter command: read, write or quit
file_name name of the file to read/write
optional arguments:
-h, --help show this help message and exit
-p PORT, --port PORT use specific port
-a ALT_NAME, --alt_name ALT_NAME
read/write with an alternate name
**************************************************
Packages:
tftp.py # module that handles tftp packets, logging and testing
client.py # module that interacts with a tftp server.
cmd.py # module that takes in command line args and uses client.py
cmd2.py # module that takes input from a user and uses client.py
gui.py # module that loads a gui version of the client
**************************************************
| fd739c14fc021aa2aa17105ebfe403119df8d62a | [
"Markdown",
"Python"
] | 3 | Python | movaid7/tftp-client | b90edd6d23c26ae7d1015d434fc2bf99e96337e2 | 0c990a4b013ecc61a25d1208a7c7bba870734f89 |
refs/heads/master | <file_sep>###############################################################################
# Write a function that takes an integer flight_length (in minutes) and a list
# of integers movie_lengths (in minutes) and returns a boolean indicating whether
# there are two numbers in movie_lengths whose sum equals flight_length.
def matching_movies_to_flight(flight_length, movie_lengths):
# create a set
seen_movie_lengths = set()
# iterate through the list of movies lengths
for first_movie in movie_lengths:
# find matching second movie
second_movie = flight_length - first_movie
# if matching second movie in set
if second_movie in seen_movie_lengths:
return True
# add first movie length to set
seen_movie_lengths.add(first_movie)
# if no matches found
return False
# O(n) time & O(n) space
###############################################################################
# palindrome?
def is_palindrome(string):
# check to see if first & last letter are the same, move toward middle
for i,v in enumerate(string):
if v == string[-i-1]:
continue
else:
return False
return True
# O(n) runtime
# Permutation Palindrome
# check if string has palindrome permutation (ex. racecar, aaccerr)
def has_palindrome_permutation(string):
#create a set to hold letters of string
letters = set()
for char in string:
if char in letters:
letters.remove(char)
else:
letters.add(char)
# if length of string is even, set length should be zero
if len(string) % 2 == 0:
return len(letters) == 0
# if length of string is odd, set length should be one
else:
return len(letters) == 1
# O(n) runtime
<file_sep># *** MERGING MEETING TIMES ***
#Write a function merge_ranges() that takes a list of multiple meeting time
#ranges and returns a list of condensed ranges.
def merge_ranges(meetings):
# sort list of tuples
meetings_sorted = sorted(meetings)
# create new list
merged_meetings = [meetings_sorted[0]]
# iterate through list and unpack tuples
for current_start, current_end in meetings_sorted:
merged_start, merged_end = merged_meetings[-1]
if current_start <= merged_end:
merged_meetings[-1] = (merged_start, max(merged_end, current_end))
else:
merged_meetings.append((current_start, current_end))
return merged_meetings
# O(nlgn) time and O(n)O(n) space.
################################################################################
# *** REVERSE STRING IN PLACE ***
# Write a function that takes a list of characters and reverses the letters in-place
# swap lst[i] with lst[-i -1]
# swap lst[0] with lst[-0-1 = -1]
# swap lst[1] with lst[-1-1 = -2]
def reverse_list(lst):
# counter
i = 0
# swap up to midpoint
midpoint = len(lst)/2
# iterate through list
for item in range(midpoint):
temp = lst[i]
lst[i] = lst[-i-1]
lst[-i-1] = temp
i += 1
return lst
# Runtime: O(n), space O(1)
def reverse_characters(message):
left_index = 0
right_index = len(message) - 1
# Walk towards the middle, from both sides
while left_index < right_index:
# Swap the left char and right char
message[left_index], message[right_index] = \
message[right_index], message[left_index]
left_index += 1
right_index -= 1
################################################################################
# *** REVERSE WORDS ***
# Write a function reverse_words() that takes a message as a list of characters
# and reverses the order of the words in-place
# create helper function to reverse entire list
# iterate through reversed list
# find seperate words through ' '
# if index is len(lst) or lst[index] is ' '
# reverse characters
def reverse_words(lst):
# iterate through the list to reverse characters
def reverse_characters(lst, left_index, right_index):
while left_index < right_index:
lst[left_index], lst[right_index] = lst[right_index], lst[left_index]
left_index += 1
right_index -= 1
# use helper function to reverse list
reverse_characters(lst, 0, len(lst)-1)
current_index = 0
for i in range(len(lst) + 1):
if i == len(lst) or lst[i] == ' ':
reverse_characters(lst, current_index, i-1)
current_index = i + 1
print ''.join(lst)
# ['l', 'a', 'e', 't', 's', ' ', 'd', 'n', 'u', 'o', 'p', ' ', 'e', 'k', 'a', 'c']
# 0
# 1
# 2
# 3
# 4
# 5
# lst, current index, i-1 ['s', 't', 'e', 'a', 'l', ' ', 'd', 'n', 'u', 'o', 'p', ' ', 'e', 'k', 'a', 'c'] 0 4
# current index 6
# 6
# 7
# 8
# 9
# 10
# 11
# lst, current index, i-1 ['s', 't', 'e', 'a', 'l', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 'e', 'k', 'a', 'c'] 6 10
# current index 12
# 12
# 13
# 14
# 15
# 16
# lst, current index, i-1 ['s', 't', 'e', 'a', 'l', ' ', 'p', 'o', 'u', 'n', 'd', ' ', 'c', 'a', 'k', 'e'] 12 15
# current index 17
################################################################################
# *** MERGE SORTED ARRAYS ***
# Write a function to merge our lists of orders into one sorted list.
# create new list
# compare the two list:
# i = 0
# while len(my_item(i)) <= len(alice_item[i])
# if my_item < alice_item:
# add my item to new list
# add alice's item to list
# else:
# add alice's item
# add my item
# i += 1
# list.extend(my_list[i:])
# list.extend(alice_list[i:])
# return lst
def merge_sort(lst1, lst2):
merged = []
i = 0
while len(lst1) <= len(lst2) and i < len(lst1):
print i
if lst1[i] < lst2[i]:
merged.append(lst1[i])
merged.append(lst2[i])
else:
merged.append(lst2[i])
merged.append(lst1[i])
i += 1
merged.extend(lst1[i:])
merged.extend(lst2[i:])
return merged
# keep track of length of combined list
# create new list (merged_list)
# lst1_index
# lst2_index
# current_merged_index
# while current_merged_index < merge_list_size
# check to see if current index < len of lists
# lst1_exhausted = lst1_index >= len(lst1)
# lst2_exhausted = lst2_index >= len(lst2)
# if lst1 not exhausted and (lst2 IS exhausted or lst1[lst1_i] < lst2[lst2_i])
# merged_list[current_merged_i] = lst1[lst1_i]
# lst1_i += 1
# else
# merge_list[current_merged_i] = lst2[lst2_i]
# lst2_i += 1
# return merged_list
def merge_lists(lst1, lst2):
list_size = len(lst1) + len(lst2)
merged_list = [None] * list_size
lst1_i = 0
lst2_i = 0
merged_current_i = 0
while merged_current_i < list_size:
is_lst1_exhausted = lst1_i >= len(lst1)
is_lst2_exhausted = lst2_i >= len(lst2)
if not is_lst1_exhausted and (is_lst2_exhausted or lst1[lst1_i] < lst2[lst2_i]):
merged_list[merged_current_i] = lst1[lst1_i]
lst1_i += 1
else:
merged_list[merged_current_i] = lst2[lst2_i]
lst2_i += 1
merged_current_i += 1
return merged_list
################################################################################
# *** SINGLE RIFFLE SHUFFLE
# let's write a function to tell us if a full deck of cards shuffled_deck is a
# single riffle of two other halves half1 and half2.
# RECURSIVELY
def is_single_riffle(half1, half2, shuffled_deck):
# base case
if len(shuffled_deck) == 0:
return True
# if top of shuffled_deck is same as top of half1
if len(half1) and half1[0] == shuffled_deck[0]:
# remove top card off half1 & shuffled deck
return is_single_riffle(half1[1:], half2, shuffled_deck[1:])
# if top of shuffled_deck is same as top of half2
elif len(half2) and half2[0] == shuffled_deck[0]:
# remove top card off half2 & shuffled deck
return is_single_riffle(half1, half2[1:], shuffled_deck[1:])
# top card doesn't match top half1 or half2, not single riffle
else:
return False
# O(n) time & O(n) space
# ITERATIVELY
def is_single_riffle2(half1, half2, shuffled_deck):
half1_i = 0
half2_i = 0
half1_max = len(half1) - 1
half2_max = len(half2) - 1
for card in shuffled_deck:
if half1_i <= half1_max and card == half1[half1_i]:
half1_i += 1
elif half2_i <= half2_max and card == half2[half2_i]:
half2_i += 1
else:
return False
# all cards have been checked
return True
# O(n) time & O(1) space
################################################################################
# *** REVERSE A LINKED LIST ***
# Write a function for reversing a linked list. ↴ Do it in-place.
class LinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
def reverse_linked_list(head):
# identify current, previous, next
current = head
previous = None
next = None
while current:
# copy pointer to next element
next = current.next
# reverse next pointer
current.next = previous
# step forward in list
previous = current
current = next
return previous
# 1-2-3-4
# c = 1
# p = None
# n = None
# while head exists:
# next = 2
# current.next = (previous) None
# previous = 1
# current = 2
# ----
# next = 3
# current.next = 1
# previous = 2
# current = 3
# ----
# next = 4
# current.next = 2
# previous = 3
# current = 4
# ----
# next = None
# current.next = 3
# previous = 4
# current = None
# return previous
| 98d3e1d420f60867fc4133050af9c0c1ed1e119a | [
"Python"
] | 2 | Python | naho18/code-challenges | 9df5d825668adf05d87f82721a0c85225851eaa5 | 314967ff03e019f9a5d24750922f8db44034b83c |
refs/heads/master | <file_sep> <!-- DataTables -->
<link rel="stylesheet" href="<?= base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.css">
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<form method="POST" action="<?= base_url('user/delete_multiple'); ?>">
<div class="box">
<div class="box-header">
<h3 class="box-title"><?= $this->lang->line('user_all'); ?></h3>
<a href="<?= base_url('user/add.asp'); ?>"><button class="btn btn-primary btn-flat" title="<?= $this->lang->line('user_add'); ?>" type="button"><i class="fa fa-user-plus"></i></button></a>
<div class="pull-right">
<button class="btn btn-danger btn-flat" type="submit" title="<?= $this->lang->line('user_delete'); ?>" onclick="return confirm('Anda yakin akan menghapus pengguna terpilih ?');"><i class="fa fa-trash-o"></i></button>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th><input type="checkbox" id="user-all"></th>
<th>Status</th>
<th><?= $this->lang->line('name'); ?></th>
<th><?= $this->lang->line('email'); ?></th>
<th><?= $this->lang->line('level'); ?></th>
</tr>
</thead>
<tbody>
<?php
$no=1;
foreach ($users as $row)
{
?>
<tr>
<td><input type="checkbox" name="user[]" class="user" value="<?= $row->usr_email; ?>"></td>
<td align='center'>
<div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default"><?= ($row->usr_activated == 0) ? '<a href="'.base_url().'user/activated/1/' . $row->usr_email .'" title="active"><i class="fa fa-fw fa-times-circle-o"></i></a>' : '<a href="'.base_url().'user/activated/0/' . $row->usr_email .'" title="active"><i class="fa fa-fw fa-check-circle-o"></i></a>'; ?></button>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?= $this->lang->line('action'); ?>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="<?= base_url('user/profile'); ?>/<?= $row->usr_email; ?>" title="<?= $this->lang->line('profile'); ?>"><button type="button" class="btn btn-primary btn-flat btn-block"><i class="fa fa-fw fa-search-plus"></i> Profile</button></a></li>
<li><a href="#"><button type="button" class="btn btn-warning btn-flat btn-block"><i class="fa fa-fw fa-pencil-square-o"></i> Edit</button></a></li>
<li><a href="#"><button type="button" class="btn btn-danger btn-flat btn-block" data-toggle="modal" data-target="#exampleModal" data-user="<?= $row->usr_email; ?>" data-link="<?= $this->encryption_kay->encode($row->usr_email); ?>"><i class="fa fa-fw fa-trash-o" ></i> Delete</button></a></li>
</ul>
</div>
</div>
</td>
<td><?= $row->usr_name; ?></td>
<td><?= $row->usr_email; ?></td>
<td><?= $row->lvl_name; ?></td>
</tr>
<?php } ?>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</form>
</div>
<!-- col -->
</div>
<!-- row -->
</section>
<!-- section -->
<div class="modal modal-warning fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Delete Confirmation for <label id="title-confirm">Title Confirm</label></h4>
</div>
<div class="modal-body">
<center>Apakah anda yakin akan menghapus pengguna dengan email <label id="user-confirm">User Confirm</label></center>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="delete-user">Delete</button>
</div>
</div>
</div>
</div>
<!-- DataTables -->
<script src="<?= base_url(); ?>assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?= base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- page script -->
<script>
$(function () {
$('#example1').DataTable();
});
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var user = button.data('user') // Extract info from data-* attributes
var link = button.data('link') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('#title-confirm').text(user)
modal.find('#user-confirm').text(user)
modal.find('#delete-user').click(function() {
document.location.href='<?= base_url(); ?>user/delete/' + link;
});
});
$("#user-all").change(function(){
$(".user").prop('checked', $(this).prop("checked"));
});
</script><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Framekay_lib {
protected $CI;
public function __construct()
{
$this->CI =& get_instance();
}
public function filter()
{
$this->CI->load->library('session');
$this->CI->load->model('level_m');
$this->CI->load->model('user_m');
if ($this->CI->session->userdata('usr_id') == '') {
redirect('/user/login' . '?url=' . current_url());
}
if ($this->CI->level_m->get_plugin_permission(uri_string(), $this->CI->user_m->get_user_session()->usr_level) != '1') {
redirect('/sistem/forbidden');
}
}
public function active_menu($url, $url2='')
{
echo ($this->CI->uri->segment(1) == $url) ? 'active' : '' ;
echo (($this->CI->uri->segment(1) == $url2) && ($url2 != '')) ? 'active' : '' ;
}
public function gap_date($start, $end)
{
$datetime1 = new DateTime($start);
$datetime2 = new DateTime($end);
$difference = $datetime1->diff($datetime2);
return $difference->days;
}
public function add_date($time='', $day='', $format='Y-m-d')
{
$date = new DateTime($time);
$date->add(new DateInterval('P' . $day .'D'));
return $date->format($format);
}
}<file_sep><?php
class Sistem extends CI_Controller {
public function index()
{
$this->load->model('electric_m');
$data['page'] = 'sistem/dashboard';
$data['electrics'] = $this->electric_m->get_electric();
$this->load->view('themes/admin_lte/backend_collapse_layout', $data);
}
}<file_sep><body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="<?= base_url(); ?>"><b>Frame</b>KAY</a>
</div>
<?php
echo (isset($notif)) ? '<div style="padding:10px;">' . $notif . '</div>' : '' ;
echo ($this->session->flashdata('notif') != '') ? '<div style="padding:10px;">' . $this->session->flashdata('notif') . '</div>' : '' ;
?>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Hi, <b><?= $user->usr_name; ?></b> change your password</p>
<form action="<?= base_url('user/update_password'); ?>" method="POST" id="block-validate">
<input type="hidden" name="usr_email" value="<?= $user->usr_email; ?>">
<div class="form-group has-feedback">
<input type="<PASSWORD>" name="usr_password" class="form-control" id="usr_password" placeholder="<PASSWORD>" REQUIRED>
<span class="fa fa-unlock-alt form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="<PASSWORD>" name="usr_password_confirm" class="form-control" id="usr_password_confirm" placeholder="Re-<PASSWORD>" REQUIRED>
<span class="fa fa-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block btn-flat">Save Password</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
<center><a href="<?= base_url(); ?>">Back to home</a></center>
</div>
<!-- /.login-box -->
<!-- validation -->
<script src="<?= base_url(); ?>assets/plugins/validationengine/js/jquery.validationEngine.js"></script>
<script src="<?= base_url(); ?>assets/plugins/validationengine/js/languages/jquery.validationEngine-en.js"></script>
<script src="<?= base_url(); ?>assets/plugins/jquery-validation-1.11.1/dist/jquery.validate.min.js"></script>
<script type="text/javascript">
function formValidation() {
"use strict";
/*----------- BEGIN validationEngine CODE -------------------------*/
$('#block-validate').validate({
rules: {
usr_password: {
required: true,
minlength: 4
},
usr_password_confirm: {
required: true,
minlength: 4,
equalTo: "#usr_password"
}
},
errorClass: 'help-block',
errorElement: 'span',
highlight: function (element, errorClass, validClass) {
$(element).parents('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents('.form-group').removeClass('has-error').addClass('has-success');
}
});
/*----------- END validate CODE -------------------------*/
}
$(function () { formValidation(); });
</script>
<file_sep><?php
$PATH = base_url('application/views/themes/admin_lte');
?>
<!-- Jasny Bootstrap -->
<script src="<?= $PATH . '/assets/plugins/jasny-bootstrap/js/jasny-bootstrap.min.js'; ?>"></script>
<!-- FastClick -->
<script src="<?= $PATH . '/assets/plugins/fastclick/fastclick.js'; ?>"></script>
<!-- AdminLTE App -->
<script src="<?= $PATH . '/assets/admin-lte/js/app.min.js'; ?>"></script>
<!-- SlimScroll 1.3.0 -->
<script src="<?= $PATH . '/assets/plugins/slimScroll/jquery.slimscroll.min.js'; ?>"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?= $PATH . '/assets/admin-lte/js/demo.js'; ?>"></script>
<!-- PACE -->
<script src="<?= $PATH . '/assets/plugins/pace/pace.min.js'; ?>"></script>
<script type="text/javascript">
$(document).ajaxStart(function() { Pace.restart(); });
</script>
</body>
</html><file_sep><?php
// judul
$lang['form_new_user'] = 'Formulir Pengguna Baru';
$lang['user'] = 'Pengguna';
// navigasi
$lang['user_all'] = 'Semua Pengguna';
$lang['user_add'] = 'Tambah Pengguna';
$lang['user_delete'] = 'Hapus Pengguna';
// nama field
$lang['no'] = 'No';
$lang['username'] = 'Username';
$lang['password'] = '<PASSWORD>';
$lang['password_confirm'] = '<PASSWORD>';
$lang['name'] = 'Nama';
$lang['email'] = 'Email';
$lang['level'] = 'Level';
$lang['activated'] = 'Aktifasi';
$lang['action'] = 'Aksi';
// tombol
$lang['profile'] = 'Profil';
$lang['save'] = 'Simpan';
$lang['cancel'] = 'Batal';
//teks
$lang['i_agree'] = 'Saya setuju';
$lang['terms_agreement'] = 'Syarat dan ketentuan';
//notification
$lang['success_add']= 'berhasil ditambahkan';
$lang['duplicate_user'] = 'Email telah terdaftar sebelumnya. Gunakan akun lain atau gunakan lupa password jika anda pemiliknya';
?><file_sep><?php
$this->load->view('themes/admin_lte/head'); //call head resource
$this->load->view('themes/admin_lte/header_boxed'); //call header layout
$this->load->view('themes/admin_lte/breadcrumb'); //call header layout
echo (isset($notif)) ? '<div style="padding:10px;">' . $notif . '</div>' : '' ;
echo ($this->session->flashdata('notif') != '') ? '<div style="padding:10px;">' . $this->session->flashdata('notif') . '</div>' : '' ;
$this->load->view('themes/admin_lte/section_left'); //call section left layout
?>
<!-- Main content -->
<section class="content">
<?php $this->load->view($page); //call section left layout ?>
<!-- </section> -->
<?php
$this->load->view('themes/admin_lte/footer'); //call footer layout
$this->load->view('themes/admin_lte/foot'); //call foot resource
?>
<file_sep><!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<?= (empty($this->uri->segment(1))) ? 'Dashboard' : ucfirst($this->uri->segment(1)); ?>
<small><?= (empty($this->uri->segment(2))) ? 'index' : $this->uri->segment(2); ?></small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li class="active"><?= (empty($this->uri->segment(1))) ? 'Dashboard' : ucfirst($this->uri->segment(1)); ?></li>
</ol>
</section><file_sep> <!-- DataTables -->
<link rel="stylesheet" href="<?= base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.css">
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Semual Level</h3>
<div class="pull-right">
<a href="<?= base_url('user/add.asp'); ?>"><button class="btn btn-primary btn-flat" title="<?= $this->lang->line('user_add'); ?>"><i class="fa fa-user-plus"></i></button></a>
</div>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Level Code</th>
<th>Level Name</th>
<th>Total</th>
<th><?= $this->lang->line('action'); ?></th>
</tr>
</thead>
<tbody>
<?php
$no=1;
foreach ($levels as $row)
{
?>
<tr>
<td><?= $row->lvl_code; ?></td>
<td><?= $row->lvl_name; ?></td>
<td><?= $this->level_m->get_level_count($row->lvl_code); ?></td>
<td align='center'>
<a href="#" title="<?= $this->lang->line('profile'); ?>"><button class='btn btn-primary btn-flat'><i class="fa fa-fw fa-list"></i></button></a>
<a href="<?= base_url('level/permissions'); ?>/<?= $row->lvl_code; ?>"><button class='btn btn-warning btn-flat'><i class="fa fa-fw fa-cogs"></i></button></a>
<button class='btn btn-danger btn-flat' data-toggle="modal" data-target="#exampleModal" data-user="" data-link=""><i class="fa fa-fw fa-trash-o"></i></button>
</td>
</tr>
<?php } ?>
</tfoot>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- col -->
</div>
<!-- row -->
</section>
<!-- section -->
<div class="modal modal-warning fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Delete Confirmation for <label id="title-confirm">Title Confirm</label></h4>
</div>
<div class="modal-body">
<center>Apakah anda yakin akan menghapus pengguna dengan email <label id="user-confirm">User Confirm</label></center>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="delete-user">Delete</button>
</div>
</div>
</div>
</div>
<!-- DataTables -->
<script src="<?= base_url(); ?>assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?= base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- page script -->
<script>
$(function () {
$('#example1').DataTable();
});
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var user = button.data('user') // Extract info from data-* attributes
var link = button.data('link') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('#title-confirm').text(user)
modal.find('#user-confirm').text(user)
modal.find('#delete-user').click(function() {
document.location.href='<?= base_url(); ?>user/delete/' + link;
});
});
</script><file_sep>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<!-- Horizontal Form -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title"><?= $this->lang->line('form_new_user'); ?></h3>
<div class="pull-right">
<a href="<?= base_url('user.asp'); ?>"><button class="btn btn-primary btn-flat" title="<?= $this->lang->line('user_all'); ?>"><i class="fa fa-table"></i></button></a>
</div>
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal" method="POST" id="block-validate" action="<?= base_url('user/save'); ?>">
<div class="box-body">
<div class="form-group">
<label class="col-sm-5 control-label"><?= $this->lang->line('name'); ?></label>
<div class="col-sm-4">
<input type="text" id="usr_name" class="form-control" name="usr_name" value="<?= (isset($_POST['usr_name'])) ? $_POST['usr_name'] : '' ; ?>" placeholder="<?= $this->lang->line('name'); ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label"><?= $this->lang->line('email'); ?></label>
<div class="col-sm-4">
<input type="email" class="form-control" id="usr_email" name="usr_email" value="<?= (isset($_POST['usr_email'])) ? $_POST['usr_email'] : '' ; ?>" placeholder="<?= $this->lang->line('email'); ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label"><?= $this->lang->line('password'); ?></label>
<div class="col-sm-5">
<input type="password" id="usr_password" class="form-control" name="usr_password" placeholder="<?= $this->lang->line('password'); ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label"><?= $this->lang->line('password_confirm'); ?></label>
<div class="col-sm-5">
<input type="password" id="usr_password_confirm" name="usr_password_confirm" class="form-control" placeholder="<?= $this->lang->line('password_confirm'); ?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label"><?= $this->lang->line('level'); ?></label>
<div class="col-sm-4">
<select class="form-control" name="usr_level" placeholder="select level">
<?php
foreach ($levels as $row) {
?>
<option value="<?= $row->lvl_id; ?>"><?= $row->lvl_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" id="agree" name="agree"> <?= $this->lang->line('i_agree'); ?> <a href="#"><?= $this->lang->line('terms_agreement'); ?></a>
</label>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<a href="<?= base_url(); ?>"><button type="button" class="btn btn-danger"><i class="fa fa-undo"></i> <?= $this->lang->line('cancel'); ?></button></a>
<button type="submit" class="btn btn-primary pull-right"><i class="fa fa-save"></i> <?= $this->lang->line('save'); ?></button>
</div>
<!-- /.box-footer -->
</form>
</div>
<!-- /.box -->
</div>
</div>
</section>
<!-- validation -->
<script src="<?= base_url(); ?>assets/plugins/validationengine/js/jquery.validationEngine.js"></script>
<script src="<?= base_url(); ?>assets/plugins/validationengine/js/languages/jquery.validationEngine-en.js"></script>
<script src="<?= base_url(); ?>assets/plugins/jquery-validation-1.11.1/dist/jquery.validate.min.js"></script>
<script type="text/javascript">
function formValidation() {
"use strict";
/*----------- BEGIN validationEngine CODE -------------------------*/
$('#block-validate').validate({
rules: {
usr_password: {
required: true,
minlength: 4
},
usr_password_confirm: {
required: true,
minlength: 4,
equalTo: "#usr_password"
},
usr_name: {
required: true,
minlength: 2
},
usr_email: {
required: true,
email: true
},
agree: "required"
},
errorClass: 'help-block',
errorElement: 'span',
highlight: function (element, errorClass, validClass) {
$(element).parents('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents('.form-group').removeClass('has-error').addClass('has-success');
}
});
/*----------- END validate CODE -------------------------*/
}
$(function () { formValidation(); });
</script><file_sep><?php
class Example extends CI_Controller {
public function index()
{
$data['page'] = 'example/Example_v';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function dashboard()
{
$data['page'] = 'example/dashboard';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function dashboard2()
{
$data['page'] = 'example/dashboard2';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function widgets()
{
$data['page'] = 'example/widgets';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function calendar()
{
$data['page'] = 'example/calendar';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function layout_top()
{
$data['page'] = 'layout/top_nav';
$this->load->view('themes/admin_lte/frontend_layout', $data);
}
public function layout_boxed()
{
$data['page'] = 'layout/boxed';
$this->load->view('themes/admin_lte/backend_boxed_layout', $data);
}
public function layout_fixed()
{
$data['page'] = 'layout/fixed';
$this->load->view('themes/admin_lte/backend_fixed_layout', $data);
}
public function layout_collapse()
{
$data['page'] = 'layout/collapse';
$this->load->view('themes/admin_lte/backend_collapse_layout', $data);
}
}<file_sep> </div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<!-- <div class="pull-right hidden-xs">
<b>Version</b> 2.3.3
</div> -->
<strong>Copyright © 2017 <a href="https://www.cyberkay.com/" target="blank">Cyberkay Dev</a>.</strong> All rights
reserved.
</footer>
<?php $this->load->view('themes/admin_lte/section_right'); //call section left layout ?>
</div>
<!-- ./wrapper -->
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.5.4.1deb2ubuntu2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 14, 2017 at 09:12 AM
-- Server version: 5.7.16-0ubuntu0.16.04.1
-- PHP Version: 7.0.8-0ubuntu0.16.04.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `emon_db`
--
-- --------------------------------------------------------
--
-- Table structure for table `kay_electric`
--
CREATE TABLE `kay_electric` (
`el_id` int(11) NOT NULL,
`el_source` varchar(11) NOT NULL,
`i` float NOT NULL DEFAULT '0',
`v` float NOT NULL DEFAULT '0',
`o` float NOT NULL DEFAULT '0',
`kwh` int(11) NOT NULL DEFAULT '1000',
`el_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `kay_electric`
--
INSERT INTO `kay_electric` (`el_id`, `el_source`, `i`, `v`, `o`, `kwh`, `el_time`) VALUES
(8, 'R01', 5, 1.5, 0, 1000, '2017-01-12 18:21:37'),
(9, 'R01', 10, 3.5, 0, 1000, '2017-01-13 18:21:37'),
(10, 'R01', 4, 35, 0, 1000, '2017-01-13 19:00:06');
-- --------------------------------------------------------
--
-- Table structure for table `kay_source`
--
CREATE TABLE `kay_source` (
`sc_id` int(11) NOT NULL,
`sc_code` varchar(12) NOT NULL,
`sc_name` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `kay_source`
--
INSERT INTO `kay_source` (`sc_id`, `sc_code`, `sc_name`) VALUES
(1, 'R01', 'Room No 1 - Kiki Kiswanto'),
(2, 'R02', 'Room No 2 - Lela Nurlaela Sari');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `kay_electric`
--
ALTER TABLE `kay_electric`
ADD PRIMARY KEY (`el_id`),
ADD KEY `el_source` (`el_source`);
--
-- Indexes for table `kay_source`
--
ALTER TABLE `kay_source`
ADD PRIMARY KEY (`sc_id`),
ADD UNIQUE KEY `sc_code` (`sc_code`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `kay_electric`
--
ALTER TABLE `kay_electric`
MODIFY `el_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `kay_source`
--
ALTER TABLE `kay_source`
MODIFY `sc_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `kay_electric`
--
ALTER TABLE `kay_electric`
ADD CONSTRAINT `kay_electric_ibfk_1` FOREIGN KEY (`el_source`) REFERENCES `kay_source` (`sc_code`);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
class Level_m extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_level_all()
{
$query = $this->db->get('kay_level');
return $query->result();
}
public function get_level_available()
{
$this->db->where('lvl_id !=', 1);
$query = $this->db->get('kay_level');
return $query->result();
}
public function get_level_by_code($id)
{
$this->db->where('lvl_code', $id);
$query = $this->db->get('kay_level');
return $query->row();
}
public function get_level_count($id)
{
$this->db->where('usr_level', $id);
$query = $this->db->get('kay_user');
return $query->num_rows();
}
public function get_plugin_all()
{
$query = $this->db->get('kay_plugin');
return $query->result();
}
public function get_plugin_uri($id)
{
$this->db->where('plg_id', $id);
$query = $this->db->get('kay_plugin_uri');
return $query->result();
}
public function get_plugin_permission($uri, $lvl)
{
$this->db->where('uri_link', $uri);
$this->db->where('lvl_id', $lvl);
$this->db->join('kay_plugin_uri', 'kay_plugin_uri.uri_id = kay_plugin_permission.uri_id');
$query = $this->db->get('kay_plugin_permission');
$query = $query->num_rows();
if ($query < 1) {
return 1;
} else {
return 0;
}
}
public function get_plugin_permission_by_id($uri, $lvl)
{
$this->db->where('uri_id', $uri);
$this->db->where('lvl_id', $lvl);
$query = $this->db->get('kay_plugin_permission');
$query = $query->num_rows();
if ($query < 1) {
return 1;
} else {
return 0;
}
}
public function insert_plugin_permission($uri_id, $lvl_id)
{
$this->uri_id = $uri_id;
$this->lvl_id = $lvl_id;
$query = $this->db->insert('kay_plugin_permission', $this);
return $query;
}
public function delete_plugin_permission($uri_id, $lvl_id)
{
$this->db->where('uri_id', $uri_id);
$this->db->where('lvl_id', $lvl_id);
$query = $this->db->delete('kay_plugin_permission');
return $query;
}
public function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}
?><file_sep><?php
class User_m extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_user_all()
{
$this->db->join('kay_level', 'kay_level.lvl_id = kay_user.usr_level');
$query = $this->db->get('kay_user');
return $query->result();
}
public function get_user_login()
{
$usr_email = $this->input->post('email');
$password = $this->input->post('password');
$usr_password = md5($password);
$this->db->where('usr_email', $usr_email);
$this->db->where('usr_password', $<PASSWORD>);
$this->db->where('usr_activated', 1);
$query = $this->db->get('kay_user');
return $query->row();
}
public function get_user_session()
{
$sess_id = $this->session->userdata('usr_id');
$this->db->select('usr_id, usr_name, lvl_name, usr_level, usr_photo, usr_created');
$this->db->from('kay_user');
$this->db->where('usr_id', $sess_id);
$this->db->join('kay_level', 'kay_level.lvl_id = kay_user.usr_level');
$query = $this->db->get();
return $query->row();
}
public function get_user_by_email($id)
{
$this->db->select('*');
$this->db->from('kay_user');
$this->db->where('usr_email', $id);
$this->db->join('kay_level', 'kay_level.lvl_id = kay_user.usr_level');
$query = $this->db->get();
return $query->row();
}
public function get_user_by_validation($id)
{
$this->db->select('*');
$this->db->from('kay_user');
$this->db->where('usr_validation', $id);
$this->db->join('kay_level', 'kay_level.lvl_id = kay_user.usr_level');
$query = $this->db->get();
return $query->row();
}
public function get_user_count()
{
$this->db->join('kay_level', 'kay_level.lvl_id = kay_user.usr_level');
$query = $this->db->get('kay_user');
return $query->num_rows();
}
public function insert_user()
{
$this->usr_name = $this->input->post('usr_name');
$this->usr_email = $this->input->post('usr_email');
$password = $this->input->post('usr_<PASSWORD>');
$this->usr_password = md5($password);
$this->usr_level = $this->input->post('usr_level');
$query = $this->db->insert('kay_user', $this);
return $query;
}
public function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
public function update_activated($value, $id)
{
$this->usr_activated = $value;
$this->db->where('usr_email', $id);
$query = $this->db->update('kay_user', $this);
return $query;
}
public function update_password($new, $id)
{
$this->usr_password = md5($new);
$this->usr_activated = 1;
$this->db->where('usr_email', $id);
$query = $this->db->update('kay_user', $this);
return $query;
}
public function update_validation($key, $id)
{
$this->usr_validation = $key;
$this->db->where('usr_email', $id);
$query = $this->db->update('kay_user', $this);
return $query;
}
public function delete_user($id)
{
$this->db->where('usr_email', $id);
$query = $this->db->delete('kay_user');
return $query;
}
public function delete_user_multiple($id)
{
$this->db->where_in('usr_email', $id);
$query = $this->db->delete('kay_user');
return $query;
}
}
?><file_sep><?php
$this->load->view('themes/admin_lte/head'); //call head resource
$this->load->view('themes/admin_lte/foot'); //call foot resource
$this->load->view($page); //content
<file_sep><!DOCTYPE html>
<?php
$PATH = base_url('application/views/themes/admin_lte');
?>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Energy Monitor v1.0 Beta</title>
<link rel="shortcut icon" type="text/css" href="<?= base_url(); ?>assets/images/logo.ico">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?= $PATH . '/assets/bootstrap/css/bootstrap.min.css'; ?>">
<!-- Font Awesome -->
<link rel="stylesheet" href="<?= $PATH . '/assets/plugins/font-awesome/css/font-awesome.css'; ?>">
<!-- Ionicons -->
<link rel="stylesheet" href="<?= $PATH . '/assets/plugins/ionicons/css/ionicons.min.css'; ?>">
<!-- Theme style -->
<link rel="stylesheet" href="<?= $PATH . '/assets/admin-lte/css/AdminLTE.min.css'; ?>">
<!-- AdminLTE Skins. Choose a skin from the css/skins
folder instead of downloading all of them to reduce the load. -->
<link rel="stylesheet" href="<?= $PATH . '/assets/admin-lte/css/skins/_all-skins.min.css'; ?>">
<!-- jQuery 2.2.0 -->
<script src="<?= $PATH . '/assets/plugins/jQuery/jQuery-2.2.0.min.js'; ?>"></script>
<!-- Bootstrap 3.3.6 -->
<script src="<?= $PATH . '/assets/bootstrap/js/bootstrap.min.js'; ?>"></script>
<!-- DataTables -->
<link rel="stylesheet" href="<?= $PATH . '/assets/plugins/datatables/dataTables.bootstrap.css'; ?>">
<!-- System Shortcut -->
<script src="<?= $PATH . '/assets/js/shortcut.js'; ?>"></script>
<!-- Jasny-Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?= $PATH . '/assets/plugins/jasny-bootstrap/css/jasny-bootstrap.min.css'; ?>">
<!-- Jasny Bootstrap -->
<script src="<?= $PATH . '/assets/plugins/jasny-bootstrap/js/jasny-bootstrap.min.js'; ?>"></script>
</head><file_sep><?php
class Electric extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('electric_m');
}
public function cost()
{
echo "<b>COST</b> <br>
Today : Rp " . number_format(ceil($this->electric_m->get_cost(date("Y-m-d")))) . "<br>
Monthly : Rp " . number_format(ceil($this->electric_m->get_cost(date("Y-m")))) . "<br>
Years : Rp " . number_format(ceil($this->electric_m->get_cost(date("Y")))) . "
";
}
public function power()
{
echo "<b>POWER</b> <br>
Today : " . number_format($this->electric_m->get_power(date("Y-m-d"))) . " W<br>
Monthly : " . number_format($this->electric_m->get_power(date("Y-m"))) . " W<br>
Years : " . number_format($this->electric_m->get_power(date("Y"))) . " W
";
}
public function current()
{
echo "<b>CURRENT</b> <br>
Today : " . number_format($this->electric_m->sum_electric('i', date('Y-m-d'))->i) . " A<br>
Monthly : " . number_format($this->electric_m->sum_electric('i', date('Y-m'))->i) . " A<br>
Years : " . number_format($this->electric_m->sum_electric('i', date('Y'))->i) . " A
";
}
public function volt()
{
echo "<b>VOLT</b> <br>
Today : " . number_format($this->electric_m->sum_electric('v', date('Y-m-d'))->v) . " V<br>
Monthly : " . number_format($this->electric_m->sum_electric('v', date('Y-m'))->v) . " V<br>
Years : " . number_format($this->electric_m->sum_electric('v', date('Y'))->v) . " V
";
}
public function list()
{
$data['electrics'] = $this->electric_m->get_electric();
$this->load->view('ajax_list', $data);
}
public function insert($source='', $i='', $v='')
{
if ($this->electric_m->insert($source, $i, $v)) {
echo "accepted";
} else {
echo "rejected";
}
}
}<file_sep> <!-- DataTables -->
<link rel="stylesheet" href="<?= base_url(); ?>assets/plugins/datatables/dataTables.bootstrap.css">
<!-- Main content -->
<section class="content">
<form method="POST" action="<?= base_url('level/permissions_update'); ?>">
<div class="row">
<div class="col-lg-12">
<?= $level->lvl_name; ?>
<input type="hidden" name="lvl_id" value="<?= $level->lvl_id; ?>">
<div class="pull-right"><button type="submit" class="btn btn-primary pull-right"><i class="fa fa-save"></i> <?= $this->lang->line('save'); ?></button></div></div>
</div>
<br>
<?php foreach ($plugins as $row) { ?>
<div class="col-xs-4">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title"><?= $row->plg_name; ?></h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<?php foreach ($this->level_m->get_plugin_uri($row->plg_id) as $uri) {
?>
<div class="row">
<div class="col-xs-12">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary <?= ($this->level_m->get_plugin_permission($uri->uri_link, $level->lvl_id) == 1) ? "active" : "" ; ?>">
<input type="radio" name="<?= $uri->uri_id; ?>" value="allow" <?= ($this->level_m->get_plugin_permission($uri->uri_link, $level->lvl_id) == 1) ? "CHECKED" : "" ; ?>> Allow
</label>
<label class="btn btn-primary <?= ($this->level_m->get_plugin_permission($uri->uri_link, $level->lvl_id) == 1) ? "" : "active" ; ?>">
<input type="radio" name="<?= $uri->uri_id; ?>" value="deny" <?= ($this->level_m->get_plugin_permission($uri->uri_link, $level->lvl_id) == 1) ? "" : "CHECKED" ; ?>> Deny
</label>
</div>
<?= $uri->uri_name; ?>
</div>
</div>
<br/>
<?php } ?>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<?php } ?>
</form>
</section>
<!-- section --><file_sep>
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>Architecture HMVC you'll find it located at:</p>
<code>
application/modules/{yourmodule}/controllers/{yourcontroller}.php <- Controller<br/>
application/modules/{yourmodule}/models/{yourmodel}.php <- Model<br/>
application/modules/{yourmodule}/views/{yourviews}.php <- Views<br/>
</code>
<p>Example implemet to example module:</p>
<code>
application/modules/example/controllers/Example.php <- Controller<br/>
application/modules/example/models/Example_m.php <- Model<br/>
application/modules/example/views/Example_v.php <- Views<br/>
</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->lang->load('user', 'indonesia');
$this->load->model('level_m');
$this->load->model('user_m');
$this->load->library('framekay_lib');
}
public function index()
{
$this->framekay_lib->filter();
$data['page'] = 'user/all';
$data['users'] = $this->user_m->get_user_all();
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function profile($id)
{
$this->framekay_lib->filter();
$data['page'] = 'user/profile';
$data['user'] = $this->user_m->get_user_by_email($id);
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function add()
{
$this->framekay_lib->filter();
$data['levels'] = $this->level_m->get_level_available();
$data['page'] = 'user/add';
$this->load->view('themes/admin_lte/application_layout', $data);
}
public function save()
{
$this->framekay_lib->filter();
$new_user = $this->input->post('usr_name');
if ($this->user_m->insert_user()) {
$this->session->mark_as_flash('notif');
$this->session->set_flashdata('notif', '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Pengguna <b>' . $new_user . '</b> berhasil ditambahkan.
</div>');
redirect('/user/');
} else {
$data['notif'] = '<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
. $this->lang->line('duplicate_user') .
'</div>';
$data['page'] = 'user/add';
$data['levels'] = $this->level_m->get_level_available();
$data['users'] = $this->user_m->get_user_all();
$this->load->view('themes/admin_lte/application_layout', $data);
}
}
public function delete($id)
{
$this->framekay_lib->filter();
$usr_email = $this->encryption_kay->decode($id);
if ($this->user_m->delete_user($usr_email)) {
$this->session->mark_as_flash('notif');
$this->session->set_flashdata('notif', '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Pengguna <b>' . $usr_email . '</b> berhasil dihapus.
</div>');
redirect('/user/');
} else {
$data['notif'] = '<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
. 'tidak ada yang bisa dihapus' .
'</div>';
redirect('/user/');
}
}
public function delete_multiple()
{
var_dump($this->input->post('user'));
$usr_email = $this->input->post('user');
$jumlah = count($usr_email);
$this->framekay_lib->filter();
if ($this->user_m->delete_user_multiple($usr_email)) {
$this->session->mark_as_flash('notif');
$this->session->set_flashdata('notif', '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<b>' . $jumlah . '</b> Pengguna berhasil dihapus.
</div>');
redirect('/user/');
} else {
$data['notif'] = '<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
. 'tidak ada yang bisa dihapus' .
'</div>';
redirect('/user/');
}
}
public function activated($value, $id)
{
$this->framekay_lib->filter();
if ($this->user_m->update_activated($value, $id)) {
$this->session->mark_as_flash('notif');
$this->session->set_flashdata('notif', '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Pengguna <b>' . $id . '</b> re-aktivasi.
</div>');
redirect('/user/');
} else {
$this->session->set_flashdata('notif', '<div class="callout callout-danger">
<h4><i class="icon fa fa-bug"></i> Kesalahan sistem</h4>
Sepertinya ada masalah di sistem kami, laporkan kesalahan <a href="#">disini</a>
</div>');
redirect('/user/');
}
}
public function forgot_password()
{
$data['page'] = 'user/forgot_password';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
public function login()
{
$data['page'] = 'user/login';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
public function logout()
{
$this->session->sess_destroy();
redirect('/');
}
public function auth()
{
if ($this->input->get('url') != NULL) {
$url = $this->input->get('url');
} else {
$url = base_url();
}
$get_user = $this->user_m->get_user_login();
if ($get_user != NULL) {
echo "please wait...";
$this->session->mark_as_flash('notif');
$this->session->set_flashdata('notif', '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Anda berhasil login sebagai <b>' . $get_user->usr_name . '</b>.
</div>');
$this->session->set_userdata('usr_id', $get_user->usr_id);
echo '<meta http-equiv="refresh" content="0;URL=' . $url . '" />';
} else {
$this->session->set_flashdata('notif', '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Email dan password yang anda masukkan tidak cocok.
</div>');
$data['page'] = 'user/login';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
}
public function reset_password()
{
$usr_email = $this->input->post('email');
$key = str_shuffle('<KEY>');
$get_user = $this->user_m->get_user_by_email($usr_email);
if ($get_user != NULL) {
echo "please wait...";
$data['key'] = $key;
$data['email'] = $get_user->usr_email;
$data['name'] = $get_user->usr_name;
if(!$this->user_m->update_validation($key, $usr_email)){
$this->session->set_flashdata('notif', '<div class="callout callout-danger">
<h4><i class="icon fa fa-bug"></i> Kesalahan sistem</h4>
Sepertinya ada masalah di sistem kami, laporkan kesalahan <a href="#">disini</a>
</div>');
} elseif(!$this->sendmail_reset_password($data)){
$this->session->set_flashdata('notif', '<div class="callout callout-danger">
<h4><i class="icon fa fa-bug"></i> Gagal Mengirim email</h4>
Hi, <b>' . $get_user->usr_name . '</b><br/>Mohon maaf atas ketidak nyamanannya, Sistem kami tidak dapat mengirim email ke <b>' . $get_user->usr_email . '</b><br/>silahkan coba lagi nanti atau hubungi kami <a href="#">disini</a>
</div>');
} else {
$this->session->set_flashdata('notif', '<div class="callout callout-info">
<h4><i class="icon fa fa-info"></i> Password Recovery</h4>
Hi, <b>' . $get_user->usr_name . '</b><br/>Password berhasil di reset. kami telah mengirimkan link untuk mengisi password baru ke email <b>' . $get_user->usr_email . '</b><br/>silahkan periksa inbox atau spam email anda dan klik tautan
</div>');
}
redirect('/user/send_password_recovery');
} else {
$this->session->set_flashdata('notif', '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Email tidak terdaftar.
</div>');
$data['page'] = 'user/forgot_password';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
}
public function update_password()
{
$usr_email = $this->input->post('usr_email');
$usr_password = $this->input->post('usr_password');
$key = str_shuffle('<KEY>');
$url = base_url();
$update = $this->user_m->update_password($usr_password, $usr_email);
if ($update) {
echo "please wait...";
if(!$this->user_m->update_validation($key, $usr_email)){
$this->session->set_flashdata('notif', '<div class="callout callout-danger">
<h4><i class="icon fa fa-bug"></i> Kesalahan sistem</h4>
Sepertinya ada masalah di sistem kami, laporkan kesalahan <a href="#">disini</a>
</div>');
} else {
$this->session->set_flashdata('notif', '<div class="callout callout-info">
<h4><i class="icon fa fa-info"></i> Password Changed</h4>
Hi, akun <b>' . $usr_email . '</b><br/>
Anda telah berhasil mengganti password dengan yang baru.
</div>');
}
echo '<meta http-equiv="refresh" content="0;URL=' . base_url() . 'user/login.asp?url=' . $url . '" />';
} else {
$this->session->set_flashdata('notif', '<div class="callout callout-danger">
<h4><i class="icon fa fa-bug"></i> Kesalahan sistem</h4>
Sepertinya ada masalah di sistem kami, laporkan kesalahan <a href="#">disini</a>
</div>');
$data['page'] = 'commons/page_blank';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
}
public function send_password_recovery()
{
$data['page'] = 'commons/page_blank';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
public function recovery_password($key)
{
$get_user = $this->user_m->get_user_by_validation($key);
if ($get_user != NULL) {
$data['user'] = $get_user;
$data['page'] = 'user/recovery_password';
$this->load->view('themes/admin_lte/blank_layout', $data);
} else {
$data['notif'] = '<div class="callout callout-danger">
<h4><i class="icon fa fa-ban"></i> Token Invalid</h4>
Ups, token sudah tidak berlaku.
</div>';
$data['page'] = 'commons/page_blank';
$this->load->view('themes/admin_lte/blank_layout', $data);
}
}
public function sendmail_reset_password($data)
{
$mail = $this->sendmail();
$message = 'Hi, ' . $data['name'] . '<br/>' .
'Please follow this link for create new password<br/>'
. base_url('user/recovery_password') . '/' . $data['key'] .
'<br/>Sender <a href="http://cyberkay.xyz" target="blank">Cyberkay</a>';
$mail->email->to($data['email']);// change it to yours
$mail->email->subject('Password recovery from cyberkay');
$mail->email->message($message);
if($mail->email->send())
{
return true;
}
else
{
return false;
}
}
public function sendmail()
{
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'mx1.idhostinger.com',
'smtp_port' => 2525,
'smtp_user' => '<EMAIL>', // change it to yours
'smtp_pass' => '<PASSWORD>', // change it to yours
'mailtype' => 'html',
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from('<EMAIL>', 'Cyberkay Inc'); // change it to yours
return $this;
}
}<file_sep><?php
$PATH = base_url('application/views/themes/admin_lte');
?>
<div class="row">
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-green"><i class="fa fa-money"></i></span>
<div class="info-box-content" id="cost">
<b>COST</b> <br>
Today : Rp <?= number_format(ceil($this->electric_m->get_cost(date("Y-m-d")))); ?> <br>
Weekly : Rp <?= number_format(ceil($this->electric_m->get_cost(date("Y-m")))); ?> <br>
Monthly : Rp <?= number_format(ceil($this->electric_m->get_cost(date("Y")))); ?>
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-blue"><i class="fa fa-plug"></i></span>
<div class="info-box-content" id="power">
<b>POWER</b> <br>
Today : <?= $this->electric_m->get_power(date("Y-m-d")); ?> W<br>
Monthly : <?= $this->electric_m->get_power(date("Y-m")); ?> W<br>
Years : <?= $this->electric_m->get_power(date("Y")); ?> W
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-red"><i class="fa fa-bolt"></i></span>
<div class="info-box-content" id="current">
<b>CURRENT</b> <br>
Today : <?= $this->electric_m->sum_electric('i', date("Y-m-d"))->i; ?> A<br>
Monthly : <?= $this->electric_m->sum_electric('i', date("Y-m"))->i; ?> A<br>
Years : <?= $this->electric_m->sum_electric('i', date("Y"))->i; ?> A
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
<div class="col-md-3 col-sm-6 col-xs-12">
<div class="info-box">
<span class="info-box-icon bg-yellow"><i class="fa fa-code-fork"></i></span>
<div class="info-box-content" id="volt">
<b>VOLT</b> <br>
Today : <?= $this->electric_m->sum_electric('v', date("Y-m-d"))->v; ?> V<br>
Monthly : <?= $this->electric_m->sum_electric('v', date("Y-m"))->v; ?> V<br>
Years : <?= $this->electric_m->sum_electric('v', date("Y"))->v; ?> V
</div>
<!-- /.info-box-content -->
</div>
<!-- /.info-box -->
</div>
</div>
<div class="row">
<div class="col-xs-12">
<!-- interactive chart -->
<div class="box box-primary">
<div class="box-header with-border">
<i class="fa fa-bar-chart-o"></i>
<h3 class="box-title">Realtime Energy Monitor</h3>
<div class="box-tools pull-right">
Real time
<div class="btn-group" id="realtime" data-toggle="btn-toggle">
<button type="button" class="btn btn-default btn-xs active" data-toggle="on">On</button>
<button type="button" class="btn btn-default btn-xs" data-toggle="off">Off</button>
</div>
</div>
</div>
<div class="box-body">
<div id="interactive" style="height: 300px;"></div>
</div>
<!-- /.box-body-->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">List Energy Monitor</h3>
</div>
<!-- /.box-header -->
<div class="box-body" id="list">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Time</th>
<th>Current</th>
<th>Volt</th>
<th>Power</th>
<th>Source</th>
</tr>
</thead>
<tbody >
<?php
foreach ($electrics as $row) {
?>
<tr>
<td><?= $row->el_time; ?></td>
<td><?= $row->i; ?> A</td>
<td><?= $row->v; ?> V</td>
<td><?= $this->electric_m->get_power($row->el_time); ?> W</td>
<td><?= $row->sc_code; ?> - <?= $row->sc_name; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
</div>
<!-- /.row -->
<!-- FLOT CHARTS -->
<script src="<?= $PATH . '/assets/plugins/flot/jquery.flot.min.js'; ?>"></script>
<!-- FLOT RESIZE PLUGIN - allows the chart to redraw when the window is resized -->
<script src="<?= $PATH . '/assets/plugins/flot/jquery.flot.resize.min.js'; ?>"></script>
<!-- DataTables -->
<script src="<?= $PATH . '/assets/plugins/datatables/jquery.dataTables.min.js'; ?>"></script>
<script src="<?= $PATH . '/assets/plugins/datatables/dataTables.bootstrap.min.js'; ?>"></script>
<script type="text/javascript">
$(function () {
/*
* Flot Interactive Chart
* -----------------------
*/
// We use an inline data source in the example, usually data would
// be fetched from a server
var data = [], totalPoints = 100;
function getRandomData() {
if (data.length > 0)
data = data.slice(1);
// Do a random walk
while (data.length < totalPoints) {
var prev = data.length > 0 ? data[data.length - 1] : 50,
y = prev + Math.random() * 10 - 5;
if (y < 0) {
y = 0;
} else if (y > 100) {
y = 100;
}
data.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < data.length; ++i) {
res.push([i, data[i]]);
}
return res;
}
var interactive_plot = $.plot("#interactive", [getRandomData()], {
grid: {
borderColor: "#f3f3f3",
borderWidth: 1,
tickColor: "#f3f3f3"
},
series: {
shadowSize: 0, // Drawing is faster without shadows
color: "#3c8dbc"
},
lines: {
fill: true, //Converts the line chart to area chart
color: "#3c8dbc"
},
yaxis: {
min: 0,
max: 100,
show: true
},
xaxis: {
min: 0,
max: 10,
show: true
}
});
var updateInterval = 1000; //Fetch data ever x milliseconds
var realtime = "on"; //If == to on then fetch data every x seconds. else stop fetching
function update() {
interactive_plot.setData([getRandomData()]);
// Since the axes don't change, we don't need to call plot.setupGrid()
interactive_plot.draw();
if (realtime === "on")
setTimeout(update, updateInterval);
}
//INITIALIZE REALTIME DATA FETCHING
if (realtime === "on") {
update();
}
//REALTIME TOGGLE
$("#realtime .btn").click(function () {
if ($(this).data("toggle") === "on") {
realtime = "on";
}
else {
realtime = "off";
}
update();
});
/*
* END INTERACTIVE CHART
*/
});
/*
* Custom Label formatter
* ----------------------
*/
function labelFormatter(label, series) {
return '<div style="font-size:13px; text-align:center; padding:2px; color: #fff; font-weight: 600;">'
+ label
+ "<br>"
+ Math.round(series.percent) + "%</div>";
}
$("#example1").DataTable({
'order' : [[0, 'desc']]
});
setInterval(function(){
$.ajax({
url: "<?= base_url() ?>" + "electric/cost",
success: function(result){
$("#cost").html(result);
}});
$.ajax({
url: "<?= base_url() ?>" + "electric/power",
success: function(result){
$("#power").html(result);
}});
$.ajax({
url: "<?= base_url() ?>" + "electric/current",
success: function(result){
$("#current").html(result);
}});
$.ajax({
url: "<?= base_url() ?>" + "electric/volt",
success: function(result){
$("#volt").html(result);
}});
$.ajax({
url: "<?= base_url() ?>" + "electric/list",
success: function(result){
$("#list").html(result);
}});
}, 1000);
</script><file_sep><body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<a href="<?= base_url(); ?>"><b>Frame</b>KAY</a>
</div>
<?php
echo (isset($notif)) ? '<div style="padding:10px;">' . $notif . '</div>' : '' ;
echo ($this->session->flashdata('notif') != '') ? '<div style="padding:10px;">' . $this->session->flashdata('notif') . '</div>' : '' ;
?>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Reset your password</p>
<form action="<?= base_url('user/reset_password'); ?>" method="POST">
<div class="form-group has-feedback">
<input type="email" name="email" value="<?= (isset($_POST['email'])) ? $_POST['email'] : '' ; ?>" autocomplete="off" class="form-control" placeholder="Enter your Email address" REQUIRED>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-12">
<button type="submit" class="btn btn-primary btn-block btn-flat">Reset Password</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
<center><a href="<?= base_url(); ?>">Back to home</a></center>
</div>
<!-- /.login-box -->
<file_sep><?php
class Electric_m extends CI_Model {
public function __construct()
{
// Call the CI_Model constructor
parent::__construct();
}
public function get_electric()
{
$this->db->select('*');
$this->db->from('kay_electric');
$this->db->join('kay_source', 'kay_source.sc_code = kay_electric.el_source');
$query = $this->db->get();
return $query->result_object();
}
public function count_electric($date='')
{
$this->db->join('kay_source', 'kay_source.sc_code = kay_electric.el_source');
if ($date != "") {
$this->db->like('el_time', $date);
}
$query = $this->db->get('kay_electric');
return $query->num_rows();
}
public function sum_electric($code='', $date='')
{
if ($code != "") {
$this->db->select_sum($code);
}
$this->db->join('kay_source', 'kay_source.sc_code = kay_electric.el_source');
if ($date != "") {
$this->db->like('el_time', $date);
}
$query = $this->db->get('kay_electric');
return $query->row();
}
public function get_power($date='')
{
$i = $this->sum_electric('i', $date)->i;
$v = $this->sum_electric('v', $date)->v;
return $i * $v;
}
public function get_cost($date='')
{
$w = $this->get_power($date);
$s = $this->count_electric($date);
$kwh = 13000;
$kws = $kwh / 60;
$ws = $kws / 1000;
$cw = $w * $ws;
$cws = $cw * $s;
return $cws;
}
}<file_sep># energymonitor
Sistem Monitoring Energy
<file_sep>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Time</th>
<th>Current</th>
<th>Volt</th>
<th>Power</th>
<th>Source</th>
</tr>
</thead>
<tbody >
<?php
foreach ($electrics as $row) {
?>
<tr>
<td><?= $row->el_time; ?></td>
<td><?= $row->i; ?> A</td>
<td><?= $row->v; ?> V</td>
<td><?= $this->electric_m->get_power($row->el_time); ?> W</td>
<td><?= $row->sc_code; ?> - <?= $row->sc_name; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<script src="<?= $PATH . '/assets/plugins/datatables/dataTables.bootstrap.min.js'; ?>"></script>
<script type="text/javascript">
$("#example1").DataTable({
'order' : [[0, 'desc']]
});
</script> | dd2e1757800d0079c43b178f49777e31e853ed6a | [
"Markdown",
"SQL",
"PHP"
] | 26 | PHP | kikikiswanto/energymonitor | 91f87d9fb7eb5b4324fd25758ad38645be243384 | 8ea6bcfe471ad33c907517d6075c112ac3277d33 |
refs/heads/main | <file_sep># corr
A spelling corrector as described in _<NAME>'s_ [article](https://norvig.com/spell-correct.html).
I will write an article on how I implemented it soon.
<file_sep>use std::{
collections::{HashMap, HashSet},
fs::read_to_string,
io::ErrorKind,
iter::once,
path::PathBuf,
};
use regex::Regex;
fn main() {
let words = words("big.txt".into());
let word_map = counter(words);
//println!("{:?}", map);
assert_eq!(correction("speling", &word_map), "spelling".to_string());
println!("{:?}", correction("korrectud", &word_map));
}
fn words(path: PathBuf) -> Vec<String> {
// add code here
let content = match read_to_string(path) {
Ok(c) => c,
Err(e) if e.kind() == ErrorKind::InvalidData => {
panic!("{:?}", "Text includes non-utf-8");
}
Err(e) => {
panic!("{:?}", e);
}
};
let re = Regex::new(r"\w+").unwrap();
let matches = re
.find_iter(&content)
.map(|m| m.as_str().to_lowercase())
.collect::<Vec<_>>();
matches
}
fn counter(words: Vec<String>) -> HashMap<String, i32> {
let mut word_map = HashMap::new();
for word in words {
word_map.entry(word).and_modify(|n| *n += 1).or_insert(1);
}
word_map
}
fn P(word: &str, word_map: &HashMap<String, i32>) -> i32 {
let num = word_map.values().fold(0, |acc, v| acc + v);
let freq = word_map.get(word).expect("word not existent");
*freq / num
}
fn edits1(word: &str) -> HashSet<String> {
let letters = "abcdefghijklmnopqrstuvwxyz".to_string();
let splits = splits(word.to_owned());
let deletes = deletes(&splits);
let transposes = transposes(&splits);
let replaces = replaces(&splits, &letters);
let inserts = inserts(&splits, &letters);
deletes
.into_iter()
.chain(
transposes
.into_iter()
.chain(replaces.into_iter().chain(inserts.into_iter())),
)
.collect::<HashSet<_>>()
}
fn edits2(word: &str) -> Vec<String> {
let mut list = vec![];
for e1 in edits1(word) {
for e2 in edits1(&e1) {
list.push(e2);
}
}
list
}
fn known(words: &[String], map: &HashMap<String, i32>) -> HashSet<String> {
let words_set = words.iter().cloned().collect::<HashSet<_>>();
let all_words_set = map.keys().cloned().collect::<HashSet<_>>();
let set = all_words_set
.intersection(&words_set)
.cloned()
.collect::<HashSet<_>>();
set
}
fn candidates(word: &str, map: &HashMap<String, i32>) -> HashSet<String> {
if !known(&once(word.to_string()).collect::<Vec<_>>(), map).is_empty() {
known(&once(word.to_string()).collect::<Vec<_>>(), map)
} else if !known(&edits1(word).into_iter().collect::<Vec<_>>(), map).is_empty() {
known(&edits1(word).into_iter().collect::<Vec<_>>(), map)
} else if !known(&edits2(word), map).is_empty() {
known(&edits2(word), map)
} else {
let mut set = HashSet::new();
set.insert(word.to_string());
set
}
}
fn correction(word: &str, word_map: &HashMap<String, i32>) -> String {
let set = candidates(word, &word_map);
set.into_iter()
.max_by(|x, y| P(x, &word_map).cmp(&P(y, &word_map)))
.expect("one mut be the greatest")
}
//Helpers
fn splits(word: String) -> Vec<(String, String)> {
let mut splits = vec![];
let len = word.len();
let range = 0..len + 1;
for i in range {
splits.push((word[..i].to_string(), word[i..].to_string()))
}
splits
}
fn deletes(splits: &Vec<(String, String)>) -> Vec<String> {
splits
.iter()
.cloned()
.filter(|(_, r)| !r.is_empty())
.map(|(mut l, r)| {
l.push_str(&r[1..]);
l
})
.collect::<Vec<_>>()
}
fn transposes(splits: &Vec<(String, String)>) -> Vec<String> {
splits
.iter()
.cloned()
.filter(|(_, r)| r.len() > 1)
.map(|(mut l, r)| {
let r_regs = r.chars().collect::<Vec<_>>();
l.push(r_regs[1]);
l.push(r_regs[0]);
l.push_str(
&r_regs[2..]
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
.concat(),
);
l
})
.collect::<Vec<_>>()
}
fn replaces(splits: &Vec<(String, String)>, letters: &String) -> Vec<String> {
let mut repl = vec![];
for c in letters.chars() {
for (l, r) in splits.iter() {
if !r.is_empty() {
let mut l = l.clone();
l.push(c);
l.push_str(&r[1..].to_string());
repl.push(l.to_owned());
}
}
}
repl
}
fn inserts(splits: &Vec<(String, String)>, letters: &String) -> Vec<String> {
let mut ins = vec![];
for c in letters.chars() {
for (l, r) in splits {
let mut l = l.clone();
l.push(c);
l.push_str(r);
ins.push(l.to_owned());
}
}
ins
}
| 3ebe5516f0b5fcd2c86ebfc3226e354c41a80e06 | [
"Markdown",
"Rust"
] | 2 | Markdown | OLUWAMUYIWA/corr | b7c9e6928f143ac613bcacc6b16f255ff7103fce | 54358c4033afdb6b920d2e29d27d33e5df8ca2a3 |
refs/heads/master | <repo_name>AdStage/omniauth-adstage<file_sep>/lib/omniauth/strategies/adstage.rb
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Adstage < OmniAuth::Strategies::OAuth2
# change the class name and the :name option to match your application name
option :name, :adstage
option :client_options, {
:site => (ENV['ADSTAGE_ENDPOINT'] || "https://www.adstage.io"),
:authorize_url => "/oauth/authorize"
}
uid { user_info['id'] }
info do
info_hash = user_info
info_hash[:organizations] = organizations_info
info_hash
end
private
def user_info
@user_info ||= access_token.get('/api/me').parsed
end
def organizations_info
user_info['_embedded']['adstage:organizations']
end
end
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
# Specify your gem's dependencies in omniauth-adstage.gemspec
gemspec
<file_sep>/lib/omniauth-adstage.rb
require 'omniauth-adstage/version'
require 'omniauth/strategies/adstage'
# Ensure OAuth2::Response supports parsing HAL.
require 'oauth2/response'
::OAuth2::Response.register_parser(:hal_json, ['application/hal+json']) do |body|
MultiJson.load(body) rescue body
end
| 787963c2b46b496c8bfde3237064b65c27967624 | [
"Ruby"
] | 3 | Ruby | AdStage/omniauth-adstage | 7dd05ef1a8c2a4fad74d488b9915b5aaca63cbe4 | e6170875b8db8159c84692effa98be416183cc37 |
refs/heads/master | <file_sep>#ifndef PARAMETER_H
#define PARAMETER_H
#include <QString>
#include <vector>
class MySlider;
class Mesh;
class Vertex;
class Transformation;
using namespace std;
/**
* @brief The Parameter class. The parameter to control the shape.
* Every parameter will be controled by a slider bar.
*/
class Parameter
{
public:
Parameter();
QString name;
float start;
float end;
float stepsize;
float value;
float getValue();
/* The slider of this parameter. */
MySlider *slider;
/* A list of objects to update when changing value of this parameter. */
vector<Vertex*> influenceVertices;
vector<Mesh*> influenceMeshes;
vector<Transformation*> influenceTransformations;
void update();
void addInfluenceMesh(Mesh * mesh);
void addInfluenceTransformation(Transformation *t);
void addInfluenceVertex(Vertex * vertex);
void changeParameterValue(float value);
};
#endif // PARAMETER_H
<file_sep>#include "testpolyline.h"
TestPolyline::TestPolyline()
{
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "transformation.h"
#include "utils.h"
Transformation::Transformation()
{
int type = 0;
matrix = mat4(1);
x = 0.0f;
y = 0.0f;
z = 0.0f;
w = 0.0f;
isParametric = false;
x_expr = "";
y_expr = "";
z_expr = "";
w_expr = "";
}
Transformation::Transformation(int type, float x, float y, float z)
{
this -> type = type;
this -> x = x;
this -> y = y;
this -> z = z;
isParametric = false;
x_expr = "";
y_expr = "";
z_expr = "";
w_expr = "";
updateMatrix();
}
Transformation::Transformation(int type, float x, float y, float z, float w)
{
this -> type = type;
this -> x = x;
this -> y = y;
this -> z = z;
this -> w = w;
isParametric = false;
x_expr = "";
y_expr = "";
z_expr = "";
w_expr = "";
updateMatrix();
}
Transformation::Transformation(int type,
unordered_map<string, Parameter> *params,
string input1,
string input2)
{
this -> type = type;
this -> params = params;
string nextExpression = "";
bool expressionMode = false;
string number = "";
int i = 0;
for(char& c : (input1 + " " + input2))
{
if(c == '{')
{
expressionMode = true;
}
else if(c == '}')
{
expressionMode = false;
switch(i)
{
case 0:
x_expr = nextExpression.substr(5);
x = evaluate_transformation_expression(x_expr, params, this);
break;
case 1:
y_expr = nextExpression.substr(5);
y = evaluate_transformation_expression(y_expr, params, this);
break;
case 2:
z_expr = nextExpression.substr(5);
z = evaluate_transformation_expression(z_expr, params, this);
break;
case 3:
w_expr = nextExpression.substr(5);
w = evaluate_transformation_expression(w_expr, params, this);
break;
}
nextExpression = "";
i++;
}
else if(expressionMode)
{
nextExpression.push_back(c);
}
else if(!expressionMode && ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+'))
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
x = stof(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
case 3:
w = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
x = stof(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
case 3:
w = stof(number);
break;
}
}
isParametric = (x_expr != "" ||
y_expr != "" ||
z_expr != "" ||
w_expr != "");
updateMatrix();
}
void Transformation::rotate()
{
matrix = glm::rotate( w / 180 * glm::pi<float>(), vec3(x, y, z));
}
void Transformation::scale()
{
matrix = glm::scale(vec3(x, y, z));
}
void Transformation::translate()
{
matrix = glm::translate(vec3(x, y, z));
}
void Transformation::mirror()
{
float d = w;
vec3 plane_normal = vec3(x, y, z);
float k = - d / length(plane_normal);
plane_normal = normalize(plane_normal);
float a = plane_normal[0];
float b = plane_normal[1];
float c = plane_normal[2];
matrix[0][0] = 1 - 2 * a * a;
matrix[0][1] = - 2 * a * b;
matrix[0][2] = - 2 * a * c;
matrix[0][3] = 0;
matrix[1][0] = - 2 * a * b;
matrix[1][1] = 1 - 2 * b * b;
matrix[1][2] = - 2 * b * c;
matrix[1][3] = 0;
matrix[2][0] = - 2 * a * c;
matrix[2][1] = - 2 * b * c;
matrix[2][2] = 1 - 2 * c * c;
matrix[2][3] = 0;
matrix[3][0] = 2 * a * k;
matrix[3][1] = 2 * b * k;
matrix[3][2] = 2 * c * k;
matrix[3][3] = 1;
}
mat4 Transformation::getMatrix()
{
return matrix;
}
void Transformation::updateMatrix()
{
switch (type) {
case 1:
rotate();
break;
case 2:
scale();
break;
case 3:
translate();
break;
case 4:
mirror();
break;
}
}
void Transformation::updateParameter()
{
if(isParametric)
{
if(x_expr != "")
{
x = evaluate_expression(x_expr, params);
}
if(y_expr != "")
{
y = evaluate_expression(y_expr, params);
}
if(z_expr != "")
{
z = evaluate_expression(z_expr, params);
}
if(w_expr != "")
{
w = evaluate_expression(w_expr, params);
}
}
}
void Transformation::update()
{
updateParameter();
updateMatrix();
}
void Transformation::setGlobalParameter(unordered_map<string, Parameter> *params)
{
this -> params = params;
}
void Transformation::addParam(Parameter* param)
{
influencingParams.push_back(param);
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "vertex.h"
#include "parameter.h"
Vertex::Vertex()
{
position = vec3(0, 0, 0);
normal = vec3(0, 0, 0);
oneEdge = NULL;
ID = 0;
selected = false;
isParametric = false;
before_transform_vertex = NULL;
source_vertex = NULL;
}
Vertex::Vertex(float x, float y, float z, unsigned long ID)
{
position = vec3(x, y, z);
normal = vec3(0, 0, 0);
oneEdge = NULL;
ID = ID;
selected = false;
isParametric = false;
before_transform_vertex = NULL;
}
void Vertex::addParam(Parameter* param)
{
influencingParams.push_back(param);
}
void Vertex::setVertexParameterValues(string input)
{
float x, y, z;
string nextExpression = "";
bool expressionMode = false;
string number = "";
int i = 0;
for(char& c : input)
{
if(c == '{')
{
expressionMode = true;
}
else if(c == '}')
{
expressionMode = false;
switch(i)
{
case 0:
x_expr = nextExpression.substr(5);
x = evaluate_vertex_expression(x_expr, params, this);
break;
case 1:
y_expr = nextExpression.substr(5);
y = evaluate_vertex_expression(y_expr, params, this);
break;
case 2:
z_expr = nextExpression.substr(5);
z = evaluate_vertex_expression(z_expr, params, this);
break;
}
nextExpression = "";
i++;
}
else if(expressionMode)
{
nextExpression.push_back(c);
}
else if(!expressionMode && ((c >= '0' && c <= '9')
|| c == '.' || c == '-' || c == '+'))
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
x = stof(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
x = stof(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
}
}
isParametric = x_expr != "" || y_expr != "" || z_expr != "";
position = vec3(x, y, z);
}
void Vertex::setGlobalParameter(unordered_map<string, Parameter> *params)
{
this -> params = params;
}
void Vertex::update()
{
if(isParametric)
{
float new_x, new_y, new_z;
if(x_expr != "")
{
new_x = evaluate_expression(x_expr, params);
}
else
{
new_x = position[0];
}
if(y_expr != "")
{
new_y = evaluate_expression(y_expr, params);
}
else
{
new_y = position[1];
}
if(z_expr != "")
{
new_z = evaluate_expression(z_expr, params);
}
else
{
new_z = position[2];
}
position = vec3(new_x, new_y, new_z);
}
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "mesh.h"
#include "parameter.h"
#include "group.h"
Mesh::Mesh(int type)
{
user_set_color = false;
transformations_up.clear();
parent = NULL;
this -> type = type;
in_editing_mode = false;
if(type == 1 || type == 2)
{
n = 0;
ro = 0.0f;
ratio = 0.0f;
h = 0.0f;
n_expr = "";
ro_expr = "";
ratio_expr = "";
h_expr = "";
}
isConsolidateMesh = false;
}
void Mesh::addVertex(Vertex * v)
{
vertList.push_back(v);
}
Edge * Mesh::findEdge(Vertex * v1, Vertex * v2)
{
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
vector<Edge*>::iterator eIt;
vIt = edgeTable.find(v2);
if(vIt != edgeTable.end())
{
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt ++)
{
if((*eIt) -> vb == v1)
{
//cout<<"Find Edge from vertex "<<v2 -> ID<<" to vertex "<<v1 -> ID<<"."<<endl;
return (*eIt);
}
}
}
vIt = edgeTable.find(v1);
if(vIt != edgeTable.end()) {
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt ++) {
if((*eIt) -> vb == v2) {
//cout<<"Find M Edge from vertex "<<v1 -> ID<<" to vertex "<<v2 -> ID<<"."<<endl;
(*eIt) -> mobius = true;
(*eIt) -> va -> onMobius = true;
(*eIt) -> vb -> onMobius = true;
return (*eIt);
}
}
}
return NULL;
}
Edge * Mesh::createEdge(Vertex * v1, Vertex * v2) {
Edge * edge = findEdge(v1, v2);
if(edge == NULL) {
//cout<<"Creating new Edge from vertex "<<v1 -> ID<<" to vertex "<<v2 -> ID<<"."<<endl;
edge = new Edge(v1, v2);
if(v1 -> oneEdge == NULL) {
v1 -> oneEdge = edge;
}
if(v2 -> oneEdge == NULL) {
v2 -> oneEdge = edge;
}
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
vIt = edgeTable.find(v1);
if(vIt != edgeTable.end()) {
(vIt -> second).push_back(edge);
} else {
vector<Edge*> currEdges;
currEdges.push_back(edge);
edgeTable[v1] = currEdges;
}
}
//cout<<"The va of edge is "<<edge -> va -> ID<<" . The vb is "<< edge -> vb -> ID<<" ."<<endl;
return edge;
}
void Mesh::addTriFace(Vertex * v1, Vertex * v2, Vertex * v3) {
Face * newFace = new Face;
Edge * e12 = createEdge(v1, v2);
Edge * e23 = createEdge(v2, v3);
Edge * e31 = createEdge(v3, v1);
if(e12 -> fa == NULL) {
e12 -> fa = newFace;
} else if(e12 -> fb == NULL) {
e12 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v1 -> ID<<" and vertex2 :"<<v2 -> ID<<endl;
exit(0);
}
if(e23 -> fa == NULL) {
e23 -> fa = newFace;
} else if(e23 -> fb == NULL) {
e23 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v2 -> ID<<" and vertex2 :"<<v3 -> ID<<endl;
exit(0);
}
if(e31 -> fa == NULL) {
e31 -> fa = newFace;
} else if(e31 -> fb == NULL) {
e31 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v3 -> ID<<" and vertex2 :"<<v1 -> ID<<endl;
exit(0);
}
newFace -> oneEdge = e12;
//cout<<"Testing: "<<newFace -> oneEdge -> va -> ID<<endl;
e12 -> setNextEdge(v1, newFace, e31);
e12 -> setNextEdge(v2, newFace, e23);
e23 -> setNextEdge(v2, newFace, e12);
e23 -> setNextEdge(v3, newFace, e31);
e31 -> setNextEdge(v1, newFace, e12);
e31 -> setNextEdge(v3, newFace, e23);
newFace -> id = faceList.size();
faceList.push_back(newFace);
}
void Mesh::addQuadFace(Vertex * v1, Vertex * v2, Vertex * v3, Vertex * v4) {
Face * newFace = new Face;
Edge * e12 = createEdge(v1, v2);
Edge * e23 = createEdge(v2, v3);
Edge * e34 = createEdge(v3, v4);
Edge * e41 = createEdge(v4, v1);
if(e12 -> fa == NULL) {
e12 -> fa = newFace;
} else if(e12 -> fb == NULL) {
e12 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v1 -> ID<<" and vertex2 :"<<v2 -> ID<<endl;
exit(0);
}
if(e23 -> fa == NULL) {
e23 -> fa = newFace;
} else if(e23 -> fb == NULL) {
e23 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v2 -> ID<<" and vertex2 :"<<v3 -> ID<<endl;
exit(0);
}
if(e34 -> fa == NULL) {
e34 -> fa = newFace;
} else if(e34 -> fb == NULL) {
e34 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v3 -> ID<<" and vertex2 :"<<v4 -> ID<<endl;
exit(0);
}
if(e41 -> fa == NULL) {
e41 -> fa = newFace;
} else if(e41 -> fb == NULL) {
e41 -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<v4 -> ID<<" and vertex2 :"<<v1 -> ID<<endl;
exit(0);
}
newFace -> oneEdge = e12;
e12 -> setNextEdge(v1, newFace, e41);
e12 -> setNextEdge(v2, newFace, e23);
e23 -> setNextEdge(v2, newFace, e12);
e23 -> setNextEdge(v3, newFace, e34);
e34 -> setNextEdge(v3, newFace, e23);
e34 -> setNextEdge(v4, newFace, e41);
e41 -> setNextEdge(v4, newFace, e34);
e41 -> setNextEdge(v1, newFace, e12);
newFace -> id = faceList.size();
faceList.push_back(newFace);
}
void Mesh::addPolygonFace(vector<Vertex*> vertices, bool reverseOrder) {
if(vertices.size() < 3) {
cout<<"A face have at least 3 vertices"<<endl;
return;
}
Face * newFace = new Face;
vector<Vertex*>::iterator vIt;
vector<Edge*> edgesInFace;
vector<Edge*>::iterator eIt;
Edge * currEdge;
if(!reverseOrder) {
for(vIt = vertices.begin(); vIt < vertices.end(); vIt ++) {
if(vIt != vertices.end() - 1) {
currEdge = createEdge(*vIt, *(vIt + 1));
edgesInFace.push_back(currEdge);
} else {
currEdge = createEdge(*vIt, *(vertices.begin()));
edgesInFace.push_back(currEdge);
}
if(currEdge -> fa == NULL) {
currEdge -> fa = newFace;
} else if(currEdge -> fb == NULL) {
currEdge -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<currEdge -> va -> ID<<" and vertex2 :"<<currEdge -> vb -> ID<<endl;
exit(0);
}
}
} else {
for(vIt = vertices.end() - 1; vIt >= vertices.begin(); vIt --) {
if(vIt != vertices.begin()) {
currEdge = createEdge(*vIt, *(vIt - 1));
edgesInFace.push_back(currEdge);
} else {
currEdge = createEdge(*vIt, *(vertices.end() - 1));
edgesInFace.push_back(currEdge);
}
if(currEdge -> fa == NULL) {
currEdge -> fa = newFace;
} else if(currEdge -> fb == NULL) {
currEdge -> fb = newFace;
} else {
cout<<"ERROR: Try to create a Non-Manifold at edge with vertex1 : "
<<currEdge -> va -> ID<<" and vertex2 :"<<currEdge -> vb -> ID<<endl;
exit(0);
}
}
}
newFace -> oneEdge = currEdge;
for(eIt = edgesInFace.begin(); eIt < edgesInFace.end(); eIt ++) {
Edge * currEdge = (*eIt);
if(eIt == edgesInFace.begin()) {
if(newFace == currEdge -> fa) {
currEdge -> nextVbFa = *(eIt + 1);
currEdge -> nextVaFa = *(edgesInFace.end() - 1);
} else {
if(currEdge -> mobius) {
currEdge -> nextVbFb = *(eIt + 1);
currEdge -> nextVaFb = *(edgesInFace.end() - 1);
} else {
currEdge -> nextVaFb = *(eIt + 1);
currEdge -> nextVbFb = *(edgesInFace.end() - 1);
}
}
} else if(eIt == (edgesInFace.end() - 1)) {
if(newFace == currEdge -> fa) {
currEdge -> nextVbFa = *(edgesInFace.begin());
currEdge -> nextVaFa = *(eIt - 1);
} else {
if(currEdge -> mobius) {
currEdge -> nextVbFb = *(edgesInFace.begin());
currEdge -> nextVaFb = *(eIt - 1);
} else {
currEdge -> nextVaFb = *(edgesInFace.begin());
currEdge -> nextVbFb = *(eIt - 1);
}
}
} else {
if(newFace == currEdge -> fa) {
currEdge -> nextVbFa = *(eIt + 1);
currEdge -> nextVaFa = *(eIt - 1);
} else {
if(currEdge -> mobius) {
currEdge -> nextVbFb = *(eIt + 1);
currEdge -> nextVaFb = *(eIt - 1);
} else {
currEdge -> nextVaFb = *(eIt + 1);
currEdge -> nextVbFb = *(eIt - 1);
}
}
}
}
newFace -> id = faceList.size();
faceList.push_back(newFace);
}
// Build the next pointers for boundary edges in the mesh.
// @param mesh: refer to the mesh to build connection in.
// This one takes O(E) time.
void Mesh::buildBoundary() {
unordered_map<Vertex*, vector<Edge*> >::iterator evIt;
vector<Edge*> edgesAtThisPoint;
vector<Edge*>::iterator eIt;
for(evIt = edgeTable.begin(); evIt != edgeTable.end(); evIt++) {
edgesAtThisPoint = evIt -> second;
if(!edgesAtThisPoint.empty()) {
for(eIt = edgesAtThisPoint.begin(); eIt < edgesAtThisPoint.end(); eIt++) {
Edge * currEdge = (*eIt);
if((currEdge -> nextEdge(currEdge -> va, currEdge -> fb)) == NULL) {
Edge * firstBoundaryEdge = currEdge;
Vertex * currVert = currEdge -> va;
Edge * nextBoundaryEdge;
//cout<<"first: "<<currEdge -> va -> ID<<" "<<currEdge -> vb -> ID<<endl;
do {
currEdge -> isSharp = true;
//cout<<"Now building boundary at vertex: "<<endl;
//cout<<currVert -> ID<<endl;
Face * currFace = currEdge -> fa;
nextBoundaryEdge = currEdge -> nextEdge(currVert, currFace);
while(nextBoundaryEdge -> fb != NULL) {
currFace = nextBoundaryEdge -> theOtherFace(currFace);
nextBoundaryEdge = nextBoundaryEdge -> nextEdge(currVert, currFace);
}
currEdge -> setNextEdge(currVert, NULL, nextBoundaryEdge);
nextBoundaryEdge -> setNextEdge(currVert, NULL, currEdge);
currEdge = nextBoundaryEdge;
currVert = currEdge -> theOtherVertex(currVert);
} while (currEdge != firstBoundaryEdge);
}
}
}
}
}
// @param p1, p2, p3 are positions of three vertices,
// with edge p1 -> p2 and edge p2 -> p3.
vec3 getNormal3Vertex(vec3 p1, vec3 p2, vec3 p3){
return cross(p2 - p1, p3 - p2);
}
// Get the surface normal.
// @param currFace: pointer of the face.
void getFaceNormal(Face * currFace){
//cout<<"New Face!"<<endl;
Edge * firstEdge = currFace -> oneEdge;
Edge * currEdge;
Edge * nextEdge;
currEdge = firstEdge;
vec3 avgNorm = vec3(0, 0, 0);
vec3 p1;
vec3 p2;
vec3 p3;
do {
//cout<<"New Edge!"<<endl;
//cout<<"ID: "<<currEdge -> va -> ID<<endl;
//cout<<"ID: "<<currEdge -> vb -> ID<<endl;
if(currFace == currEdge -> fa) {
nextEdge = currEdge -> nextVbFa;
p1 = currEdge -> va -> position;
p2 = currEdge -> vb -> position;
p3 = nextEdge -> theOtherVertex(currEdge -> vb) -> position;
} else if(currFace == currEdge -> fb) {
if(currEdge -> mobius) {
nextEdge = currEdge -> nextVbFb;
p1 = currEdge -> va -> position;
p2 = currEdge -> vb -> position;
p3 = nextEdge -> theOtherVertex(currEdge -> vb) -> position;
} else {
nextEdge = currEdge -> nextVaFb;
p1 = currEdge -> vb -> position;
p2 = currEdge -> va -> position;
p3 = nextEdge -> theOtherVertex(currEdge -> va) -> position;
}
}
avgNorm += getNormal3Vertex(p1, p2, p3);
currEdge = nextEdge;
} while (currEdge != firstEdge);
//cout<<"The new Face normal is: "<<result[0]<<" "<<result[1]<<" "<<result[2]<<endl;
currFace -> normal = normalize(avgNorm);
}
// Get the vertex normal
// @param currVert: the target vertex.
void getVertexNormal(Vertex * currVert){
Edge * firstEdge = currVert -> oneEdge;
if(firstEdge == NULL) {
cout<<"Lonely vertex without any adjacent edges"<<endl;
return;
}
Edge * currEdge = firstEdge;
Face * currFace = currEdge -> fa;
vec3 avgNorm(0, 0, 0);
int mobiusCounter = 0;
do {
if(mobiusCounter % 2 == 0) {
avgNorm += currFace -> normal;
} else {
avgNorm -= currFace -> normal;
}
if(currEdge -> mobius) {
mobiusCounter += 1;
}
currFace = currEdge -> theOtherFace(currFace);
if(currFace == NULL) { //If the face is NULL, need to skip this face
Edge * nextEdge = currEdge -> nextEdge(currVert, currFace);
if(nextEdge -> va == currEdge -> va || nextEdge -> vb == currEdge -> vb) {
mobiusCounter += 1;
}
currEdge = nextEdge;
currFace = currEdge -> theOtherFace(currFace);
}
currEdge = currEdge -> nextEdge(currVert, currFace);
} while ( currEdge != firstEdge);
//if(currVert -> onMobius) {
//cout<<"The value of avgNorm is :"<<avgNorm[0]<<" "<<avgNorm[1]<<" "<<avgNorm[2]<<endl;
//cout<<"The position of this vertex is :"<<currVert -> position[0]<<" "<<currVert -> position[1]<<" "<<currVert -> position[2]<<endl;
//}//cout<<"ID: "<<currVert -> ID <<" has "<<mobiusCounter<<" mConter"<<endl;
currVert -> normal = normalize(avgNorm);
}
// Iterate over every vertex in the mesh and compute its normal
void Mesh::computeNormals(){
vector<Vertex*>::iterator vIt;
vector<Face*>::iterator fIt;
//cout<<"faceTable size: "<<faceList.size()<<endl;
for(fIt = faceList.begin(); fIt < faceList.end(); fIt++) {
getFaceNormal(*fIt);
}
//cout<<"vertTable size: "<<vertList.size()<<endl;
for(vIt = vertList.begin(); vIt != vertList.end(); vIt++) {
//cout<<"Now calculating vertex with ID: "<< vIt -> first <<endl;
getVertexNormal(*vIt);
}
}
void Mesh::drawMesh(int startIndex, bool smoothShading)
{
/* The overall mesh color.*/
GLfloat fcolor[] = {1.0f * color.red() / 255,
1.0f * color.green() / 255,
1.0f * color.blue() / 255,
1.0f * color.alpha() /255};
/* The color for the selected face */
GLfloat fscolor[] = {1.0f - 1.0f * color.red() / 255,
1.0f - 1.0f * color.green() / 255,
1.0f - 1.0f * color.blue() / 255,
1.0f - 1.0f * color.alpha() /255};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, fcolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, fcolor);
Face * tempFace;
vector<Face*>::iterator fIt;
for(fIt = faceList.begin(); fIt < faceList.end(); fIt++)
{
tempFace = (*fIt);
if(tempFace -> user_defined_color)
{
QColor user_color = tempFace -> color;
if(tempFace -> selected)
{
/* The reverse of user defined face color, ussed for selection. */
GLfloat uscolor[] = {1.0f - 1.0f * user_color.red() / 255,
1.0f - 1.0f * user_color.green() / 255,
1.0f - 1.0f * user_color.blue() / 255,
1.0f - 1.0f * user_color.alpha() /255};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, uscolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, uscolor);
}
else
{
/* The user defined face color.*/
GLfloat ucolor[] = {1.0f * user_color.red() / 255,
1.0f * user_color.green() / 255,
1.0f * user_color.blue() / 255,
1.0f * user_color.alpha() /255};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, ucolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ucolor);
}
} else {
if(tempFace -> selected)
{
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, fscolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, fscolor);
}
}
vec3 fNormal = tempFace -> normal;
Vertex * tempv;
Edge * firstEdge = (*fIt) -> oneEdge;
//cout<<"New Face: "<<endl;
glLoadName(tempFace -> id + startIndex);
glBegin(GL_POLYGON);
Edge * currEdge = firstEdge;
Edge * nextEdge;
//tempv = currEdge -> va;
//cout<<"Hmm?"<<endl;
//cout<<"Hello! I am on the "<<fIt - faceList.begin()<<" face."<<endl;
if(!smoothShading)
{
glNormal3f(fNormal[0], fNormal[1], fNormal[2]);
}
do
{
if(tempFace == currEdge -> fa)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
}
else
{
if(currEdge -> mobius)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
}
else
{
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
if(smoothShading) {
float normx;
float normy;
float normz;
if(tempv -> onMobius)
{
vec3 vNormal = tempv -> normal;
if(dot(vNormal, fNormal) >= 0)
{
normx = tempv -> normal[0];
normy = tempv -> normal[1];
normz = tempv -> normal[2];
}
else
{
normx = - tempv -> normal[0];
normy = - tempv -> normal[1];
normz = - tempv -> normal[2];
}
}
else
{
normx = tempv -> normal[0];
normy = tempv -> normal[1];
normz = tempv -> normal[2];
}
glNormal3f(normx, normy, normz);
}
//cout<<"normx: "<<normx<<" normy: "<<normy<<" normz: "<<normz<<endl;
float x = tempv -> position[0];
float y = tempv -> position[1];
float z = tempv -> position[2];
//cout<<"x: "<<x<<" y: "<<y<<" z: "<<z<<endl;
glVertex3f(x, y, z);
currEdge = nextEdge;
//cout<<"Current Vertex ID: "<<tempv -> ID<<endl;
} while(currEdge != firstEdge);
glEnd();
if(tempFace -> selected || tempFace -> user_defined_color)
{
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, fcolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, fcolor);
}
}
}
vector<Edge*> Mesh::boundaryEdgeList() {
vector<Edge*> boundaryEdgeList;
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
//cout<<"Edge table size: "<<edgeTable.size()<<endl;
for(vIt = edgeTable.begin(); vIt != edgeTable.end(); vIt++) {
//cout<<vIt -> first -> ID<<endl;
vector<Edge*> edges = vIt -> second;
vector<Edge*>::iterator eIt;
vector<Edge*> newEdges;
for(eIt = edges.begin(); eIt < edges.end(); eIt ++) {
if((*eIt) -> fb == NULL) {
boundaryEdgeList.push_back(*eIt);
}
}
}
//cout<<"size: " << boundaryEdgeList.size()<<endl;
return boundaryEdgeList;
}
void Mesh::drawVertices()
{
vector<Vertex*>::iterator vIt;
glPointSize(10);
for(vIt = vertList.begin(); vIt < vertList.end(); vIt++) {
if((*vIt) -> selected) {
glBegin(GL_POINTS);
vec3 position = (*vIt) -> position;
glNormal3f(position[0] * 100, position[1] * 100, position[2] * 100);
glVertex3f(position[0], position[1], position[2]);
glEnd();
}
}
}
bool Mesh::isEmpty() {
return vertList.size() == 0 && faceList.size() == 0;
}
void Mesh::clear()
{
//for(Vertex*& v : vertList)
//{
// delete v;
//}
//for(Face*& f : faceList)
//{
// delete f;
//}
vertList.clear();
faceList.clear();
edgeTable.clear();
}
void Mesh::clearAndDelete()
{
for(Vertex*& v : vertList)
{
delete v;
}
for(Face*& f : faceList)
{
delete f;
}
vertList.clear();
faceList.clear();
edgeTable.clear();
}
void Mesh::setColor(QColor color)
{
this -> color = color;
}
void Mesh::setGlobalParameter(unordered_map<string, Parameter> *params)
{
this -> params = params;
}
void Mesh::addTransformation(Transformation new_transform)
{
transformations_up.push_back(new_transform);
}
void Mesh::setTransformation(vector<Transformation> new_transforms)
{
transformations_up = new_transforms;
}
Mesh Mesh::makeCopy(string copy_mesh_name) {
//cout<<"Creating a copy of the current map.\n";
Mesh newMesh;
if(copy_mesh_name == "")
{
newMesh.name = this->name;
}
else
{
newMesh.name = copy_mesh_name;
}
newMesh.clear();
vector<Vertex*>::iterator vIt;
for(vIt = vertList.begin();
vIt < vertList.end(); vIt ++) {
Vertex * vertCopy = new Vertex;
vertCopy -> ID = (*vIt) -> ID;
vertCopy -> name = (*vIt) -> name;
vertCopy -> position = (*vIt) -> position;
vertCopy -> isParametric = (*vIt) -> isParametric;
if((*vIt) -> isParametric)
{
vertCopy -> x_expr = (*vIt) -> x_expr;
vertCopy -> y_expr = (*vIt) -> y_expr;
vertCopy -> z_expr = (*vIt) -> z_expr;
vertCopy -> params = (*vIt) -> params;
vertCopy -> influencingParams = (*vIt) -> influencingParams;
}
newMesh.addVertex(vertCopy);
}
vector<Face*>::iterator fIt;
vector<Vertex*> vertices;
for(fIt = faceList.begin();
fIt < faceList.end(); fIt ++) {
Face * tempFace = *fIt;
Edge * firstEdge = tempFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
vertices.clear();
do {
if(tempFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
vertices.push_back(newMesh.vertList[tempv -> ID]);
currEdge = nextEdge;
} while (currEdge != firstEdge);
newMesh.addPolygonFace(vertices);
newMesh.faceList[newMesh.faceList.size() - 1] -> user_defined_color
= (*fIt) -> user_defined_color;
newMesh.faceList[newMesh.faceList.size() - 1] -> color
= (*fIt) -> color;
newMesh.faceList[newMesh.faceList.size() - 1] -> name
= (*fIt) -> name;
}
newMesh.buildBoundary();
newMesh.computeNormals();
newMesh.color = color;
newMesh.params = params;
newMesh.type = type;
if(type == 1)
{
newMesh.n = n;
newMesh.ro = ro;
newMesh.ratio = ratio;
newMesh.h = h;
newMesh.n_expr = n_expr;
newMesh.ro_expr = ro_expr;
newMesh.ratio_expr = ratio_expr;
newMesh.h_expr = h_expr;
newMesh.influencingParams = influencingParams;
}
else if(type == 2)
{
newMesh.n = n;
newMesh.ro = ro;
newMesh.ratio = ratio;
newMesh.h = h;
newMesh.n_expr = n_expr;
newMesh.ro_expr = ro_expr;
newMesh.ratio_expr = ratio_expr;
newMesh.h_expr = h_expr;
newMesh.influencingParams = influencingParams;
}
return newMesh;
}
Mesh Mesh::makeCopyForTempMesh(string copy_mesh_name) {
Mesh newMesh;
if(copy_mesh_name == "")
{
newMesh.name = this->name;
}
else
{
newMesh.name = copy_mesh_name;
}
newMesh.clear();
unordered_map<Vertex*, Vertex*> original_to_copy;
unordered_map<Vertex*, Vertex*>::iterator o2cIt;
vector<Face*>::iterator fIt;
vector<Vertex*> vertices;
for(fIt = faceList.begin();
fIt < faceList.end(); fIt ++)
{
Face * tempFace = *fIt;
Edge * firstEdge = tempFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
vertices.clear();
do
{
if(tempFace == currEdge -> fa)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
}
else
{
if(currEdge -> mobius)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
}
else
{
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
o2cIt = original_to_copy.find(tempv);
if(o2cIt == original_to_copy.end())
{
Vertex * vertCopy = new Vertex;
vertCopy -> ID = tempv -> ID;
vertCopy -> name = tempv -> name;
vertCopy -> position = tempv -> position;
vertCopy -> source_vertex = tempv -> source_vertex;
newMesh.addVertex(vertCopy);
original_to_copy[tempv] = vertCopy;
vertices.push_back(vertCopy);
}
else
{
vertices.push_back(o2cIt -> second);
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
newMesh.addPolygonFace(vertices);
newMesh.faceList[newMesh.faceList.size() - 1] -> user_defined_color
= (*fIt) -> user_defined_color;
if((*fIt) -> user_defined_color)
{
newMesh.faceList[newMesh.faceList.size() - 1] -> color
= (*fIt) -> color;
}
newMesh.faceList[newMesh.faceList.size() - 1] -> name
= (*fIt) -> name;
}
newMesh.buildBoundary();
newMesh.computeNormals();
newMesh.color = QColor(255, 69, 0);
newMesh.params = params;
newMesh.type = type;
return newMesh;
}
Mesh Mesh::makeCopyForTransform() {
//cout<<"Creating a copy of the current map.\n";
Mesh newMesh;
newMesh.before_transform_mesh = this;
newMesh.clear();
newMesh.name = this -> name;
vector<Vertex*>::iterator vIt;
for(vIt = vertList.begin();
vIt < vertList.end(); vIt ++) {
Vertex * vertCopy = new Vertex;
vertCopy -> ID = (*vIt) -> ID;
vertCopy -> name = (*vIt) -> name;
vertCopy -> position = (*vIt) -> position;
vertCopy -> before_transform_vertex = (*vIt);
newMesh.addVertex(vertCopy);
}
vector<Face*>::iterator fIt;
vector<Vertex*> vertices;
for(fIt = faceList.begin();
fIt < faceList.end(); fIt ++) {
Face * tempFace = *fIt;
Edge * firstEdge = tempFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
vertices.clear();
do {
if(tempFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
vertices.push_back(newMesh.vertList[tempv -> ID]);
currEdge = nextEdge;
} while (currEdge != firstEdge);
newMesh.addPolygonFace(vertices);
newMesh.faceList[newMesh.faceList.size() - 1] -> user_defined_color
= (*fIt) -> user_defined_color;
newMesh.faceList[newMesh.faceList.size() - 1] -> color
= (*fIt) -> color;
newMesh.faceList[newMesh.faceList.size() - 1] -> name
= (*fIt) -> name;
}
newMesh.buildBoundary();
newMesh.computeNormals();
newMesh.color = color;
newMesh.params = params;
newMesh.type = type;
if(type == 1)
{
newMesh.n = n;
newMesh.ro = ro;
newMesh.ratio = ratio;
newMesh.h = h;
newMesh.n_expr = n_expr;
newMesh.ro_expr = ro_expr;
newMesh.ratio_expr = ratio_expr;
newMesh.h_expr = h_expr;
newMesh.influencingParams = influencingParams;
}
else if(type == 2)
{
newMesh.n = n;
newMesh.ro = ro;
newMesh.ratio = ratio;
newMesh.h = h;
newMesh.n_expr = n_expr;
newMesh.ro_expr = ro_expr;
newMesh.ratio_expr = ratio_expr;
newMesh.h_expr = h_expr;
newMesh.influencingParams = influencingParams;
}
return newMesh;
}
void Mesh::updateCopyForTransform()
{
transformations_up = before_transform_mesh -> transformations_up;
for(Vertex*& v: vertList)
{
v -> position = v -> before_transform_vertex -> position;
}
}
void Mesh::transform(Transformation* t)
{
mat4 matrix = t -> getMatrix();
vector<Vertex*>::iterator vIt;
for(vIt = vertList.begin(); vIt < vertList.end(); vIt++)
{
(*vIt) -> position = vec3(matrix * vec4((*vIt) -> position, 1));
}
}
void Mesh::transform(mat4 matrix)
{
vector<Vertex*>::iterator vIt;
for(vIt = vertList.begin(); vIt < vertList.end(); vIt++)
{
(*vIt) -> position = vec3(matrix * vec4((*vIt) -> position, 1));
}
}
mat4 Mesh::transformToTop()
{
mat4 result = mat4(1);
for(Transformation& t: transformations_up)
{
result = t.getMatrix() * result;
}
Group *p = this -> parent;
while(p != NULL)
{
for(Transformation& t : p -> transformations_up)
{
result = t.getMatrix() * result;
}
p = p -> parent;
}
return result;
}
void Mesh::setFunnelParameterValues(string input)
{
string nextExpression = "";
bool expressionMode = false;
string number = "";
int i = 0;
for(char& c : input)
{
if(c == '{')
{
expressionMode = true;
}
else if(c == '}')
{
expressionMode = false;
switch(i)
{
case 0:
n_expr = nextExpression.substr(5);
n = int(evaluate_mesh_expression(n_expr, params, this) + 0.5);
break;
case 1:
ro_expr = nextExpression.substr(5);
ro = evaluate_mesh_expression(ro_expr, params, this);
break;
case 2:
ratio_expr = nextExpression.substr(5);
ratio = evaluate_mesh_expression(ratio_expr, params, this);
break;
case 3:
h_expr = nextExpression.substr(5);
h = evaluate_mesh_expression(h_expr, params, this);
break;
}
nextExpression = "";
i++;
}
else if(expressionMode)
{
nextExpression.push_back(c);
}
else if(!expressionMode && ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+'))
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
n = stoi(number);
break;
case 1:
ro = stof(number);
break;
case 2:
ratio = stof(number);
break;
case 3:
h = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
n = stoi(number);
break;
case 1:
ro = stof(number);
break;
case 2:
ratio = stof(number);
break;
case 3:
h = stof(number);
break;
}
}
}
void Mesh::setTunnelParameterValues(string input)
{
string nextExpression = "";
bool expressionMode = false;
string number = "";
int i = 0;
for(char& c : input)
{
if(c == '{')
{
expressionMode = true;
}
else if(c == '}')
{
expressionMode = false;
switch(i)
{
case 0:
n_expr = nextExpression.substr(5);
n = int(evaluate_mesh_expression(n_expr, params, this) + 0.5);
break;
case 1:
ro_expr = nextExpression.substr(5);
ro = evaluate_mesh_expression(ro_expr, params, this);
break;
case 2:
ratio_expr = nextExpression.substr(5);
ratio = evaluate_mesh_expression(ratio_expr, params, this);
break;
case 3:
h_expr = nextExpression.substr(5);
h = evaluate_mesh_expression(h_expr, params, this);
break;
}
nextExpression = "";
i++;
}
else if(expressionMode)
{
nextExpression.push_back(c);
}
else if(!expressionMode && ((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+'))
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
n = stoi(number);
break;
case 1:
ro = stof(number);
break;
case 2:
ratio = stof(number);
break;
case 3:
h = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
n = stoi(number);
break;
case 1:
ro = stof(number);
break;
case 2:
ratio = stof(number);
break;
case 3:
h = stof(number);
break;
}
}
}
void Mesh::updateFunnel()
{
if(n_expr != "")
{
int new_n = evaluate_expression(n_expr, params);
if(new_n != n)
{
if(in_editing_mode)
{
return;
}
n = new_n;
updateFunnel_n();
}
}
if(ro_expr != "")
{
float new_ro = evaluate_expression(ro_expr, params);
if(new_ro != ro)
{
ro = new_ro;
updateFunnel_ro_ratio_or_h();
}
}
if(ratio_expr != "")
{
float new_ratio = evaluate_expression(ratio_expr, params);
if(new_ratio != ratio)
{
ratio = new_ratio;
updateFunnel_ro_ratio_or_h();
}
}
if(h_expr != "")
{
float new_h = evaluate_expression(h_expr, params);
if(new_h != h)
{
h = new_h;
updateFunnel_ro_ratio_or_h();
}
}
}
void Mesh::updateTunnel()
{
if(n_expr != "")
{
int new_n = evaluate_expression(n_expr, params);
if(new_n != n)
{
if(in_editing_mode)
{
return;
}
n = new_n;
updateTunnel_n();
}
}
if(ro_expr != "")
{
float new_ro = evaluate_expression(ro_expr, params);
if(new_ro != ro)
{
ro = new_ro;
updateTunnel_ro_ratio_or_h();
}
}
if(ratio_expr != "")
{
float new_ratio = evaluate_expression(ratio_expr, params);
if(new_ratio != ratio)
{
ratio = new_ratio;
updateTunnel_ro_ratio_or_h();
}
}
if(h_expr != "")
{
float new_h = evaluate_expression(h_expr, params);
if(new_h != h)
{
h = new_h;
updateTunnel_ro_ratio_or_h();
}
}
}
void Mesh::updateFunnel_n()
{
makeFunnel();
computeNormals();
//transform(transformToTop());
}
void Mesh::updateFunnel_ro_ratio_or_h()
{
for(int i = 0; i < n; i++)
{
Vertex * newVertex = vertList[i];
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ro * glm::cos(currAngle), ro * glm::sin(currAngle), 0);
}
float ri = ro * (1 + ratio);
for(int i = 0; i < n; i++)
{
Vertex * newVertex = vertList[i + n];
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle), ri * glm::sin(currAngle), h);
}
computeNormals();
//transform(transformToTop());
}
void Mesh::makeFunnel()
{
if(n < 3) {
return;
}
vertList.clear();
edgeTable.clear();
faceList.clear();
vector<Vertex*> baseCircle;
vector<Vertex*> highCircle;
for(int i = 0; i < n; i++)
{
Vertex * newVertex = new Vertex;
newVertex->ID = i;
newVertex->name = "bc" + to_string(i);
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ro * glm::cos(currAngle),
ro * glm::sin(currAngle), 0);
baseCircle.push_back(newVertex);
addVertex(newVertex);
}
float ri = ro * (1 + ratio);
for(int i = 0; i < n; i++)
{
Vertex * newVertex = new Vertex;
newVertex->ID = i + n;
newVertex->name = "hc"+ to_string(i);
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle),
ri * glm::sin(currAngle), h);
highCircle.push_back(newVertex);
addVertex(newVertex);
}
for(int i = 0; i < n - 1 ; i++)
{
addQuadFace(baseCircle[i], baseCircle[i + 1], highCircle[i + 1], highCircle[i]);
}
addQuadFace(baseCircle[n - 1], baseCircle[0], highCircle[0], highCircle[n - 1]);
buildBoundary();
}
void Mesh::makeTunnel()
{
if(n < 3) {
return;
}
vertList.clear();
edgeTable.clear();
faceList.clear();
vector<Vertex*> baseCircle;
vector<Vertex*> highCircle;
vector<Vertex*> lowCircle;
for(int i = 0; i < n; i++)
{
Vertex * newVertex = new Vertex;
newVertex->ID = i;
newVertex->name = "bc" + to_string(i);
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ro * glm::cos(currAngle),
ro * glm::sin(currAngle), 0);
baseCircle.push_back(newVertex);
addVertex(newVertex);
}
float ri = ro * (1 + ratio);
for(int i = 0; i < n; i++)
{
Vertex * newVertex = new Vertex;
newVertex->ID = i + n;
newVertex->name = "hc" + to_string(i);
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle),
ri * glm::sin(currAngle), h);
highCircle.push_back(newVertex);
addVertex(newVertex);
}
for(int i = 0; i < n; i++)
{
Vertex * newVertex = new Vertex;
newVertex->ID = i + 2 * n;
newVertex->name = "lc" + to_string(i);
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle),
ri * glm::sin(currAngle), -h);
lowCircle.push_back(newVertex);
addVertex(newVertex);
}
for(int i = 0; i < n - 1 ; i++)
{
addQuadFace(baseCircle[i], baseCircle[i + 1], highCircle[i + 1], highCircle[i]);
addQuadFace(lowCircle[i], lowCircle[i + 1], baseCircle[i + 1], baseCircle[i]);
}
addQuadFace(baseCircle[n - 1], baseCircle[0], highCircle[0], highCircle[n - 1]);
addQuadFace(lowCircle[n - 1], lowCircle[0], baseCircle[0], baseCircle[n - 1]);
buildBoundary();
}
void Mesh::updateTunnel_n()
{
makeTunnel();
computeNormals();
}
void Mesh::updateTunnel_ro_ratio_or_h()
{
for(int i = 0; i < n; i++)
{
Vertex * newVertex = vertList[i];
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ro * glm::cos(currAngle),
ro * glm::sin(currAngle), 0);
}
float ri = ro * (1 + ratio);
for(int i = 0; i < n; i++)
{
Vertex * newVertex = vertList[i + n];
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle),
ri * glm::sin(currAngle), h);
}
for(int i = 0; i < n; i++)
{
Vertex * newVertex = vertList[i + 2 * n];
float currAngle = 2.0 * i / n * PI;
newVertex -> position = vec3(ri * glm::cos(currAngle),
ri * glm::sin(currAngle), -h);
}
computeNormals();
}
void Mesh::addParam(Parameter* param)
{
influencingParams.push_back(param);
}
Vertex * Mesh::findVertexInThisMesh(string name)
{
for(Vertex*& v: vertList)
{
if(v->name == name)
{
return v;
}
}
return NULL;
}
bool Mesh::deleteFaceInThisMesh(string name)
{
for(Face*& f: faceList)
{
cout<<f->name<<" ";
if(f->name == name)
{
deleteFace(f);
return true;
}
}
return false;
}
void Mesh::deleteVertex(Vertex *v)
{
bool foundThisVertex = false;
int counter = 0;
for(Vertex * nextVert : vertList)
{
if(foundThisVertex)
{
nextVert->ID -= 1;
}
else if(nextVert == v)
{
foundThisVertex = true;
}
else
{
counter++;
}
}
if(foundThisVertex)
{
vertList.erase(vertList.begin()+counter);
}
delete v;
}
void Mesh::deleteFace(Face *face)
{
bool foundThisFace = false;
int counter = 0;
for(Face * nextFace : faceList)
{
if(foundThisFace)
{
nextFace->id -= 1;
} else if(nextFace == face)
{
foundThisFace = true;
} else {
counter++;
}
}
if(foundThisFace)
{
faceList.erase(faceList.begin()+counter);
}
vector<Edge*> removeEdgeList;
removeEdgeList.clear();
Edge * firstEdge = face -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
do
{
if(face == currEdge -> fa)
{
nextEdge = currEdge -> nextVbFa;
if(currEdge -> fb != NULL)
{
if(currEdge -> mobius)
{
currEdge -> nextVaFa = currEdge -> nextVaFb;
currEdge -> nextVbFa = currEdge -> nextVbFb;
currEdge -> mobius = false;
//Maybe we need to remark the end vertex non-Mobius here.
}
else
{
/*Switch the va and vb, also need to change in the edgetable. */
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
vector<Edge*>::iterator eIt;
vIt = edgeTable.find(currEdge -> va);
if(vIt != edgeTable.end())
{
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt++)
{
if((*eIt) == currEdge)
{
(vIt -> second).erase(eIt);
break;
}
}
}
else
{
cout<<"Error, there is a bug in the program!"<<endl;
}
vIt = edgeTable.find(currEdge -> vb);
if(vIt != edgeTable.end())
{
(vIt -> second).push_back(currEdge);
}
else
{
vector<Edge*> edges;
edges.push_back(currEdge);
edgeTable[currEdge -> vb] = edges;
}
Vertex * temp = currEdge -> va;
currEdge -> va = currEdge -> vb;
currEdge -> vb = temp;
currEdge -> nextVaFa = currEdge -> nextVbFb;
currEdge -> nextVbFa = currEdge -> nextVaFb;
}
currEdge -> fa = currEdge -> fb;
currEdge -> nextVaFb = NULL;
currEdge -> nextVbFb = NULL;
currEdge -> fb = NULL;
}
else
{
currEdge -> nextVaFa = NULL;
currEdge -> nextVbFa = NULL;
currEdge -> fa = NULL;
removeEdgeList.push_back(currEdge);
}
}
else
{
if(currEdge -> mobius)
{
nextEdge = currEdge -> nextVbFb;
currEdge -> mobius = false;
} else
{
nextEdge = currEdge -> nextVaFb;
}
currEdge -> nextVaFb = NULL;
currEdge -> nextVbFb = NULL;
currEdge -> fb = NULL;
}
currEdge = nextEdge;
} while(currEdge != firstEdge);
for(Edge * edge : removeEdgeList)
{
deleteEdge(edge);
}
delete face;
return;
}
void Mesh::deleteEdge(Edge * edge)
{
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
vector<Edge*>::iterator eIt;
vIt = edgeTable.find(edge -> va);
bool foundEdge = false;
if(vIt != edgeTable.end())
{
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt++)
{
if((*eIt) == edge)
{
foundEdge = true;
(vIt -> second).erase(eIt);
break;
}
}
}
if(!foundEdge)
{
cout<<"Error: You can't delete this edge. Check the program!"<<endl;
}
else
{
/* Also need to settle edgeTable here. We also need to set the oneEdge pointer
* for the affected vertex when edge is deleted. */
if(edge -> va -> oneEdge == edge)
{
foundEdge = false;
if((vIt -> second).size() > 0)
{
edge -> va -> oneEdge = *((vIt -> second).begin());
foundEdge = true;
}
else
{
for(vIt = edgeTable.begin(); vIt != edgeTable.end(); vIt++)
{
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt++)
{
if((*eIt) -> vb == edge -> va)
{
edge -> va -> oneEdge = (*eIt);
foundEdge = true;
break;
}
}
}
}
if(!foundEdge)
{
cout<<"Warning: Your deletion has deleted a vertex."<<endl;
edge -> va -> oneEdge = NULL;
deleteVertex(edge -> va);
}
}
if(edge -> vb -> oneEdge == edge)
{
foundEdge = false;
vIt = edgeTable.find(edge -> vb);
if(vIt != edgeTable.end() && (vIt -> second).size() > 0)
{
edge -> vb -> oneEdge = *((vIt -> second).begin());
foundEdge = true;
}
else
{
for(vIt = edgeTable.begin(); vIt != edgeTable.end(); vIt++)
{
for(eIt = (vIt -> second).begin(); eIt < (vIt -> second).end(); eIt++)
{
if((*eIt) -> vb == edge -> vb)
{
edge -> vb -> oneEdge = (*eIt);
foundEdge = true;
break;
}
}
}
}
if(!foundEdge)
{
cout<<"Warning: Your deletion has deleted a vertex."<<endl;
edge -> vb -> oneEdge = NULL;
deleteVertex(edge -> vb);
}
}
}
/* Also need to remove the key in edgeTable if it does not exist anymore. */
delete(edge);
return;
}
void Mesh::updateVertListAfterDeletion()
{
vertList.clear();
bool foundVa;
bool foundVb;
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
for(vIt = edgeTable.begin(); vIt != edgeTable.end(); vIt++)
{
for(Edge * edge : (vIt -> second))
{
foundVa = false;
foundVb = false;
for(Vertex* v : vertList)
{
if(v == edge -> va)
{
foundVa = true;
}
if(v == edge -> vb)
{
foundVb = true;
}
if(foundVa && foundVb)
{
break;
}
}
if(!foundVa)
{
vertList.push_back(edge -> va);
}
if(!foundVb)
{
vertList.push_back(edge -> vb);
}
}
}
return;
}
void Mesh::setBoundaryEdgeToNull(Vertex* v) {
/* Traverse around v and find boundary edges.
* Set the nextFb pointers to NULL for those edges. */
vector<Edge*> edgeAtThisPoint;
unordered_map<Vertex*, vector<Edge*> >::iterator vIt;
vIt = edgeTable.find(v);
if(vIt != edgeTable.end()) {
edgeAtThisPoint = vIt -> second;
for(Edge* e : edgeAtThisPoint) {
e -> isSharp = false;
if((e -> fb) == NULL) {
e->nextVaFb = NULL;
e->nextVbFb = NULL;
}
}
} else {
cout<<"Error: The Vertex doesn't belongs to this Mesh. Debug here."<<endl;
}
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __MAKEPOLYLINE_H__
#define __MAKEPOLYLINE_H__
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include "mesh.h"
#include "polyline.h"
#include "zipper.h"
#include "subdivison.h"
using namespace glm;
using namespace std;
//////////////////////////////////////////////////////////////////////
// MakePolyline Class -- Create Initial Meshes.
Mesh initPolyline();
Mesh initPolyline1();
Mesh initPolyline2();
Mesh initPolyline4();
Mesh initPolyline8();
Mesh initPolyline9();
Mesh initPolyline3();
Mesh initPolyline5();
Mesh initPolyline6();
#endif // __MAKEPOLYLINE_H__
<file_sep>#include "nomeparser.h"
NomeParser::NomeParser()
{
}
bool testComments(string token)
{
if(token[0] == '#') {
return true;
}
return false;
}
/**
* @brief warning: Helper function to output warnings.
* @param type:
* 0: Parameter reading error.
* 1: Stoi exception. Line skipped.
* @param lineNumber: The current line number.
* @return
*/
string warning(int type, int lineNumber)
{
switch(type)
{
case 0:
return "Warning: parameter at line "
+ to_string(lineNumber) + " is not set because of insufficient parameters.";
case 1:
return "Warning: line " + to_string(lineNumber)
+ " contains string that can't be parsed, skipping this line.";
case 2:
return "Warning: parameter at line "
+ to_string(lineNumber) + " has duplicated names of existing parameters.";
case 3:
return "Warning: mesh at line "
+ to_string(lineNumber) + " has duplicated names of existing meshes.";
case 4:
return "Warning: group at line "
+ to_string(lineNumber) + " has duplicated names of existing groups.";
case 5:
return "Warninng: instance at line "
+ to_string(lineNumber) + " has not been created yet.";
case 6:
return "Warning: new instance at line"
+ to_string(lineNumber) + " does not have a name.";
case 7:
return "Warning: parameter name at line"
+ to_string(lineNumber) + " does not match any defined parameter.";
case 8:
return "Warning: parameter at line"
+ to_string(lineNumber) + " does not have a retored value.";
case 9:
return "Warning: vertex at line"
+ to_string(lineNumber) + " can't be restored.";
case 10:
return "Warning: point at line"
+ to_string(lineNumber) + " doesn't have a name. It can't be initiated.";
case 11:
return "Warning: point at line"
+ to_string(lineNumber) + " has already been created (duplicate names)." +
" It can't be initiated.";
case 12:
return "Warning: polyline at line"
+ to_string(lineNumber) + " doesn't have a name. It can't be initiated.";
case 13:
return "Warning: polyline at line"
+ to_string(lineNumber) + " has already been created (duplicate names)." +
" It can't be initiated.";
case 14:
return "Warning: vertex at line"
+ to_string(lineNumber) + " can't be added to polyline. It has not been created.";
case 15:
return "Warning: Color at line"
+ to_string(lineNumber) + " can't be assigned. It has not been created.";
case 16:
return "Warning: Color at line"
+ to_string(lineNumber) + " has already been created (duplicate names).";
case 17:
return "Warning: Color at line"
+ to_string(lineNumber) + " does not have enough input.";
case 18:
return "Warning: Instance at line"
+ to_string(lineNumber) + " does not complete color definition. " +
"It can't be instantiated.";
case 19:
return "Warning: face at line"
+ to_string(lineNumber) + " doesn't have a name. It can't be initiated.";
case 20:
return "Warning: face at line"
+ to_string(lineNumber) + " has already been created (duplicate names)." +
" It can't be initiated.";
case 21:
return "Warning: vertex at line"
+ to_string(lineNumber) + " can't be added to face. It has not been created.";
case 22:
return "Warning: Face at line"
+ to_string(lineNumber) + " does not complete color definition. " +
"It can't be instantiated.";
case 23:
return "Warning: face at line"
+ to_string(lineNumber) + " can't be added to mesh. It has not been created.";
case 24:
return "Warning: face at line"
+ to_string(lineNumber) + " can't be deleted. It does not have a name.";
case 25:
return "Warning: face at line"
+ to_string(lineNumber) + " can't be deleted. It is not in the current scene.";
case 26:
return "Warning: mesh at line"
+ to_string(lineNumber) + " doesn't have a name.";
case 27:
return "Warning: face at line"
+ to_string(lineNumber) + " can't be added to mesh. The mesh does not have a name.";
}
return "";
}
void NomeParser::makeWithNome(vector<ParameterBank> &banks,
unordered_map<string, Parameter> ¶ms,
Group &group,
string input,
vector<string> &colorlines,
vector<string> &banklines,
vector<string> &geometrylines,
vector<int> &postProcessingLines)
{
banks.clear();
group.clear();
ifstream file(input);
if (!file.good())
{
cout<<"THE PATH OF MINI SIF FILE IS NOT VAILD.";
exit(1);
}
string nextLine;
int lineNumber = 1;
bool createBank = false;
bool constructingMesh = false;
bool deletePhase = false;
string currentGroup = "";
unordered_map<string, Parameter>::iterator pIt;
unordered_map<string, Mesh> meshes;
unordered_map<string, Mesh>::iterator meshIt;
unordered_map<string, Group> groups;
unordered_map<string, Group>::iterator groupIt;
unordered_map<string, Vertex*> global_vertices;
unordered_map<string, Vertex*>::iterator vertIt;
unordered_map<string, PolyLine> polylines;
unordered_map<string, PolyLine>::iterator lineIt;
unordered_map<string, Face*> global_faces;
unordered_map<Face*, vector<Vertex*> > map_face_vertices;
unordered_map<string, Face*>::iterator faceIt;
string name = "";
unordered_map<string, QColor> user_defined_colors;
unordered_map<string, QColor>::iterator colorIt;
string current_mesh_name = "";
while(std::getline(file, nextLine))
{
istringstream iss(nextLine);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
if(testComments(*tIt))
{
break;
}
else if((*tIt) == "bank")
{
banklines.push_back(nextLine);
ParameterBank newBank;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
newBank.setName(QString::fromStdString(*tIt));
}
}
banks.push_back(newBank);
createBank = true;
goto newLineEnd;
}
else if((*tIt) == "endbank")
{
banklines.push_back(nextLine);
createBank = false;
goto newLineEnd;
}
else if(createBank && (*tIt) == "set")
{
banklines.push_back(nextLine);
Parameter newParameter;
int i = 0;
while(i < 5) {
if(tIt >= tokens.end() - 1) {
cout<<warning(0, lineNumber)<<endl;
goto newLineEnd;
}
string nextToken = *(++tIt);
if(testComments(nextToken)) {
cout<<warning(0, lineNumber)<<endl;
goto newLineEnd;
}
switch(i)
{
case 0:
newParameter.name = banks[banks.size() - 1].name
+ QString::fromStdString("_" + nextToken);
name = nextToken;
break;
case 1:
try
{
newParameter.value = std::stof(nextToken);
break;
}
catch (std::exception e)
{
cout<<warning(1, lineNumber)<<endl;
goto newLineEnd;
}
case 2:
try
{
newParameter.start = std::stof(nextToken);
break;
}
catch (std::exception e)
{
cout<<warning(1, lineNumber)<<endl;
goto newLineEnd;
}
case 3:
try
{
newParameter.end = std::stof(nextToken);
break;
}
catch (std::exception e)
{
cout<<warning(1, lineNumber)<<endl;
goto newLineEnd;
}
case 4:
try
{
newParameter.stepsize = std::stof(nextToken);
break;
}
catch (std::exception e)
{
cout<<warning(1, lineNumber)<<endl;
goto newLineEnd;
}
}
i++;
}
pIt = params.find(newParameter.name.toStdString());
if(pIt == params.end())
{
params[banks[banks.size() - 1].name.toStdString() + "_" + name]
= newParameter;
}
else
{
cout<<warning(2, lineNumber)<<endl;
goto newLineEnd;
}
banks[banks.size() - 1].addParameter(
¶ms[banks[banks.size() - 1].name.toStdString() + "_" + name]);
}
else if((*tIt) == "surface")
{
colorlines.push_back(nextLine);
string color_name;
QColor new_color;
if(++tIt < tokens.end())
{
color_name = (*tIt);
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
cout<<warning(16, lineNumber)<<endl;
goto newLineEnd;
}
}
else
{
cout<<warning(17, lineNumber)<<endl;
}
if(++tIt < tokens.end())
{
if((*tIt) != "color")
{
cout<<warning(17, lineNumber)<<endl;
}
}
else
{
cout<<warning(17, lineNumber)<<endl;
}
string color_expression;
bool expression_input = false;
bool inExpression = false;
while(++tIt < tokens.end())
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
expression_input = true;
}
else if(c == ')' && !inExpression)
{
expression_input = false;
goto colordone;
}
else if(c == '#')
{
goto newLineEnd;
}
else if(expression_input)
{
color_expression.push_back(c);
}
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
color_expression.push_back(' ');
}
colordone:
new_color = evaluate_color_expression(color_expression);
user_defined_colors[color_name] = new_color;
goto newLineEnd;
}
else if((*tIt) == "funnel")
{
geometrylines.push_back(nextLine);
Mesh newFunnel(1);
newFunnel.setGlobalParameter(¶ms);
if(++tIt < tokens.end())
{
newFunnel.name = (*tIt);
}
string funnel_expression;
bool expression_input = false;
bool inExpression = false;
while(++tIt < tokens.end())
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
expression_input = true;
}
else if(c == ')' && !inExpression)
{
expression_input = false;
}
else if(c == '#')
{
goto newLineEnd;
}
else if(expression_input)
{
funnel_expression.push_back(c);
}
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
funnel_expression.push_back(' ');
}
newFunnel.setFunnelParameterValues(funnel_expression);
newFunnel.makeFunnel();
if(meshes.find(newFunnel.name) == meshes.end())
{
meshes[newFunnel.name] = newFunnel;
}
else
{
cout<<warning(3, lineNumber)<<endl;
}
//newFunnel.computeNormals();
}
else if((*tIt) == "tunnel")
{
geometrylines.push_back(nextLine);
Mesh newTunnel(2);
newTunnel.setGlobalParameter(¶ms);
if(++tIt < tokens.end())
{
newTunnel.name = (*tIt);
}
string tunnel_expression;
bool expression_input = false;
bool inExpression = false;
while(++tIt < tokens.end())
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
expression_input = true;
}
else if(c == ')' && !inExpression)
{
expression_input = false;
}
else if(c == '#')
{
goto newLineEnd;
}
else if(expression_input)
{
tunnel_expression.push_back(c);
}
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
tunnel_expression.push_back(' ');
}
newTunnel.setTunnelParameterValues(tunnel_expression);
newTunnel.makeTunnel();
if(meshes.find(newTunnel.name) == meshes.end())
{
meshes[newTunnel.name] = newTunnel;
}
else
{
cout<<warning(3, lineNumber)<<endl;
}
//newTunnel.computeNormals();
}
else if((*tIt) == "object")
{
geometrylines.push_back(nextLine);
Mesh newMesh(0);
newMesh.setGlobalParameter(¶ms);
if(++tIt < tokens.end())
{
if(!testComments(*tIt))
{
newMesh.name = *tIt;
}
else
{
cout<<warning(3, lineNumber)<<endl;
goto newLineEnd;
}
}
string faceInside = "";
bool addingFace = false;
while(++tIt < tokens.end())
{
for(char& c : (*tIt))
{
if(c == '(')
{
addingFace = true;
}
else if(c == ')')
{
addingFace = false;
if(faceInside != "")
{
faceIt = global_faces.find(faceInside);
if(faceIt == global_faces.end())
{
cout<<warning(23, lineNumber);
}
else
{
Vertex * foundVertex;
vector<Vertex*> vertices;
for(Vertex * vc : map_face_vertices[(faceIt -> second)])
{
foundVertex = NULL;
for(Vertex * v : newMesh.vertList)
{
if(v -> source_vertex == vc)
{
foundVertex = v;
vertices.push_back(v);
}
}
if(foundVertex == NULL)
{
Vertex * newVertex = new Vertex;
newVertex -> isParametric = vc -> isParametric;
newVertex -> position = vc -> position;
newVertex -> ID = newMesh.vertList.size();
newVertex -> source_vertex = vc;
newVertex -> name = vc -> name;
newVertex -> x_expr = vc -> x_expr;
newVertex -> y_expr = vc -> y_expr;
newVertex -> z_expr = vc -> z_expr;
newVertex -> influencingParams = vc -> influencingParams;
newVertex -> params = vc -> params;
newMesh.addVertex(newVertex);
vertices.push_back(newVertex);
}
}
newMesh.addPolygonFace(vertices);
newMesh.faceList[newMesh.faceList.size()-1]->user_defined_color = faceIt -> second -> user_defined_color;
if(faceIt -> second -> user_defined_color)
{
newMesh.faceList[newMesh.faceList.size()-1]->color = faceIt -> second -> color;
}
newMesh.faceList[newMesh.faceList.size()-1] -> name = faceIt -> second -> name;
}
faceInside = "";
}
goto endAddingFaceInMesh;
}
else if(addingFace)
{
faceInside.push_back(c);
}
}
if(faceInside != "")
{
faceIt = global_faces.find(faceInside);
if(faceIt == global_faces.end())
{
cout<<warning(23, lineNumber);
}
else
{
Vertex * foundVertex;
vector<Vertex*> vertices;
for(Vertex * vc : map_face_vertices[(faceIt -> second)])
{
foundVertex = NULL;
for(Vertex * v : newMesh.vertList)
{
if(v -> source_vertex == vc)
{
foundVertex = v;
vertices.push_back(v);
}
}
if(foundVertex == NULL)
{
Vertex * newVertex = new Vertex;
newVertex -> isParametric = vc -> isParametric;
newVertex -> position = vc -> position;
newVertex -> ID = newMesh.vertList.size();
newVertex -> source_vertex = vc;
newVertex -> name = vc -> name;
newVertex -> x_expr = vc -> x_expr;
newVertex -> y_expr = vc -> y_expr;
newVertex -> z_expr = vc -> z_expr;
newVertex -> influencingParams = vc -> influencingParams;
newVertex -> params = vc -> params;
newMesh.addVertex(newVertex);
vertices.push_back(newVertex);
}
}
newMesh.addPolygonFace(vertices);
newMesh.faceList[newMesh.faceList.size()-1]->user_defined_color = faceIt -> second -> user_defined_color;
if(faceIt -> second -> user_defined_color)
{
newMesh.faceList[newMesh.faceList.size()-1]->color = faceIt -> second -> color;
}
}
faceInside = "";
}
}
endAddingFaceInMesh:
if(meshes.find(newMesh.name) == meshes.end())
{
meshes[newMesh.name] = newMesh;
}
else
{
cout<<warning(3, lineNumber)<<endl;
}
}
else if((*tIt) == "face" && (!deletePhase) && (!constructingMesh))
{
geometrylines.push_back(nextLine);
Face * newFace = new Face;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
faceIt = global_faces.find(*tIt);
if(faceIt == global_faces.end())
{
newFace -> name = *tIt;
global_faces[*tIt] = newFace;
}
else
{
cout<<warning(20, lineNumber)<<endl;
}
}
else
{
cout<<warning(19, lineNumber)<<endl;
}
}
string vertInside = "";
bool addingVert = false;
vector<Vertex*> vertices;
vertices.clear();
while(++tIt < tokens.end() && (*tIt) != "endface")
{
for(char & c: (*tIt))
{
if(c == '(')
{
addingVert = true;
}
else if(c == ')')
{
addingVert = false;
if(vertInside != "")
{
vertIt = global_vertices.find(vertInside);
if(vertIt == global_vertices.end())
{
cout<<warning(21, lineNumber);
}
else
{
vertices.push_back(vertIt -> second);
}
vertInside = "";
}
goto endAddingVertInFace;
}
else if(addingVert)
{
vertInside.push_back(c);
}
}
if(vertInside != "")
{
vertIt = global_vertices.find(vertInside);
if(vertIt == global_vertices.end())
{
cout<<warning(21, lineNumber);
}
else
{
vertices.push_back(vertIt -> second);
}
vertInside = "";
}
}
endAddingVertInFace:
map_face_vertices[newFace] = vertices;
if(++tIt < tokens.end() && (*tIt) == "surface")
{
string color_name = "";
QColor color;
bool foundColor = false;
if(++tIt < tokens.end())
{
color_name = *tIt;
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
foundColor = true;
color = colorIt -> second;
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
if(foundColor)
{
newFace -> color = color;
newFace -> user_defined_color = true;
}
}
}
else if((*tIt) == "face" && deletePhase)
{
postProcessingLines.push_back(lineNumber);
/* Hmm, this is weird, I did not do anything here!
Except putting the delte into postProcessingLines.
*/
goto newLineEnd;
}
else if((*tIt) == "face" && constructingMesh)
{
if(current_mesh_name == "")
{
cout<<warning(27, lineNumber)<<endl;
goto newLineEnd;
}
else if(current_mesh_name == "consolidatedmesh")
{
postProcessingLines.push_back(lineNumber);
goto newLineEnd;
}
geometrylines.push_back(nextLine);
Face * newFace = new Face;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
faceIt = global_faces.find(*tIt);
if(faceIt == global_faces.end())
{
newFace -> name = *tIt;
global_faces[*tIt] = newFace;
}
else
{
cout<<warning(20, lineNumber)<<endl;
}
}
else
{
cout<<warning(19, lineNumber)<<endl;
}
}
string vertInside = "";
bool addingVert = false;
vector<Vertex*> vertices;
vertices.clear();
while(++tIt < tokens.end() && (*tIt) != "endface")
{
for(char & c: (*tIt))
{
if(c == '(')
{
addingVert = true;
}
else if(c == ')')
{
addingVert = false;
if(vertInside != "")
{
vertIt = global_vertices.find(vertInside);
if(vertIt == global_vertices.end())
{
cout<<warning(21, lineNumber);
}
else
{
vertices.push_back(vertIt -> second);
}
vertInside = "";
}
goto endAddingVertInFace1;
}
else if(addingVert)
{
vertInside.push_back(c);
}
}
if(vertInside != "")
{
vertIt = global_vertices.find(vertInside);
if(vertIt == global_vertices.end())
{
cout<<warning(21, lineNumber);
}
else
{
vertices.push_back(vertIt -> second);
}
vertInside = "";
}
}
endAddingVertInFace1:
/* Add this face to the current mesh now.*/
vector<Vertex*> mappedVertices;
mappedVertices.clear();
bool foundVertex;
for(Vertex * vs : vertices)
{
foundVertex = false;
for(Vertex * v : meshes[current_mesh_name].vertList)
{
if(v -> source_vertex == vs)
{
foundVertex = true;
mappedVertices.push_back(v);
break;
}
}
if(!foundVertex)
{
Vertex * newVertex = new Vertex;
newVertex -> isParametric = vs -> isParametric;
newVertex -> position = vs -> position;
newVertex -> ID = meshes[current_mesh_name].vertList.size();
newVertex -> source_vertex = vs;
newVertex -> name = vs -> name;
newVertex -> x_expr = vs -> x_expr;
newVertex -> y_expr = vs -> y_expr;
newVertex -> z_expr = vs -> z_expr;
newVertex -> influencingParams = vs -> influencingParams;
newVertex -> params = vs -> params;
meshes[current_mesh_name].addVertex(newVertex);
mappedVertices.push_back(newVertex);
}
}
meshes[current_mesh_name].addPolygonFace(mappedVertices);
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> name = newFace -> name;
if(++tIt < tokens.end() && (*tIt) == "surface")
{
string color_name = "";
QColor color;
bool foundColor = false;
if(++tIt < tokens.end())
{
color_name = *tIt;
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
foundColor = true;
color = colorIt -> second;
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
if(foundColor)
{
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> color = color;
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> user_defined_color = true;
}
}
delete newFace;
}
else if((*tIt) == "polyline")
{
geometrylines.push_back(nextLine);
PolyLine newPolyline;
if((++tIt) < tokens.end() && !testComments(*tIt))
{
lineIt = polylines.find(*tIt);
if(lineIt == polylines.end())
{
newPolyline.name = *tIt;
}
else
{
cout<<warning(13, lineNumber)<<endl;
}
}
else
{
cout<<warning(12, lineNumber)<<endl;
}
string vertInside = "";
bool addingVert = false;
while(++tIt < tokens.end() && (*tIt) != "endpolyline")
{
for(char& c : (*tIt))
{
if(c == '(')
{
addingVert = true;
}
else if(c == ')')
{
addingVert = false;
if(++tIt < tokens.end() && (*tIt) != "endpolyline")
{
if(*tIt == "isloop")
{
newPolyline.isLoop = true;
}
}
goto endPolyLineWhile;
}
else if(addingVert)
{
vertInside.push_back(c);
}
}
if(vertInside != "")
{
vertIt = global_vertices.find(vertInside);
if(vertIt == global_vertices.end())
{
cout<<warning(14, lineNumber);
}
else
{
newPolyline.addVertex(vertIt -> second);
}
vertInside = "";
}
}
endPolyLineWhile:
polylines[newPolyline.name] = newPolyline;
}
else if((*tIt) == "point")
{
geometrylines.push_back(nextLine);
Vertex * newVertex = new Vertex;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
vertIt = global_vertices.find(*tIt);
if(vertIt == global_vertices.end())
{
newVertex -> name = *tIt;
global_vertices[*tIt] = newVertex;
}
else
{
cout<<warning(11, lineNumber)<<endl;
}
}
else
{
cout<<warning(10, lineNumber)<<endl;
}
}
string xyz;
bool makingXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endpoint")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZ = true;
}
else if(c == ')' && !inExpression)
{
makingXYZ = false;
goto endPointWhile;
}
else if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyz != "")
{
xyz.push_back(' ');
}
}
endPointWhile:
newVertex->setGlobalParameter(¶ms);
newVertex->setVertexParameterValues(xyz);
}
else if((*tIt) == "group")
{
geometrylines.push_back(nextLine);
Group newGroup;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
newGroup.setName(*tIt);
}
}
groups[newGroup.name] = newGroup;
currentGroup = newGroup.name;
goto newLineEnd;
}
else if((*tIt) == "endgroup")
{
geometrylines.push_back(nextLine);
currentGroup = "";
goto newLineEnd;
}
else if((*tIt) == "instance")
{
string instanceName;
Mesh newMesh;
Group newGroup;
PolyLine newPolyline;
string className;
bool findMesh = false;
bool findGroup = false;
bool findPolyline = false;
bool foundColor = false;
QColor color;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
instanceName = *tIt;
}
} else {
cout<<warning(5, lineNumber)<<endl;
}
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
className = *tIt;
}
} else {
cout<<warning(6, lineNumber)<<endl;
}
if(className == "consolidatedmesh")
{
postProcessingLines.push_back(lineNumber);
goto newLineEnd;
}
else
{
geometrylines.push_back(nextLine);
}
meshIt = meshes.find(className);
if(meshIt != meshes.end())
{
newMesh = (meshIt -> second).makeCopy(instanceName);
findMesh = true;
}
else
{
groupIt = groups.find(className);
if(groupIt != groups.end())
{
newGroup = (groupIt -> second).makeCopy(instanceName);
findGroup = true;
}
else
{
lineIt = polylines.find(className);
if(lineIt != polylines.end())
{
newPolyline = (lineIt -> second).makeCopy(instanceName);
findPolyline = true;
}
else
{
cout<<warning(5, lineNumber)<<endl;
}
}
}
vector<Transformation> transformations_up;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
if(testComments(*tIt))
{
goto newLineEnd;
}
if(*tIt == "rotate")
{
string xyz;
string angle;
bool makingXYZ = false;
bool makingAngle = false;
bool doneXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
if(!doneXYZ)
{
makingXYZ = true;
}
else
{
makingAngle = true;
}
}
else if(c == ')' && !inExpression)
{
if(makingXYZ)
{
doneXYZ = true;
makingXYZ = false;
} else if(makingAngle)
{
makingAngle = false;
goto endWhile1;
}
}
else
{
if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
else if(makingAngle)
{
angle.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
}
if(makingXYZ && xyz != "")
{
xyz.push_back(' ');
}
else if(makingAngle && angle != "")
{
angle.push_back(' ');
}
}
endWhile1:
Transformation t(1, ¶ms, xyz, angle);
transformations_up.push_back(t);
}
else if(*tIt == "translate" || *tIt == "scale")
{
bool isTranslate = false;
if(*tIt == "translate")
{
isTranslate = true;
}
string xyz = "";
bool makingXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZ = true;
}
else if(c == ')' && !inExpression)
{
makingXYZ = false;
goto endWhile2;
}
else if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyz != "")
{
xyz.push_back(' ');
}
}
endWhile2:
if(isTranslate)
{
Transformation t(3,¶ms, xyz);
transformations_up.push_back(t);
}
else
{
Transformation t(2, ¶ms, xyz);
transformations_up.push_back(t);
}
}
else if(*tIt == "mirror")
{
string xyzw = "";
bool makingXYZW = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZW = true;
}
else if(c == ')' && !inExpression)
{
makingXYZW = false;
goto endWhile3;
}
else if(makingXYZW)
{
xyzw.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyzw != "")
{
xyzw.push_back(' ');
}
}
endWhile3:
Transformation t(4, ¶ms, xyzw);
transformations_up.push_back(t);
}
if(*tIt == "surface")
{
string color_name;
if(++tIt < tokens.end())
{
color_name = *tIt;
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
color = colorIt -> second;
foundColor = true;
}
else
{
cout<<warning(18, lineNumber)<<endl;
}
}
else
{
cout<<warning(18, lineNumber)<<endl;
}
}
}
if(currentGroup != "")
{
if(findMesh)
{
newMesh.setTransformation(transformations_up);
if(foundColor)
{
newMesh.setColor(color);
newMesh.user_set_color = true;
}
groups[currentGroup].addMesh(newMesh);
}
else if(findGroup)
{
newGroup.setTransformation(transformations_up);
if(foundColor)
{
newGroup.setColor(color);
newGroup.user_set_color = true;
}
groups[currentGroup].addGroup(newGroup);
}
else if(findPolyline)
{
newPolyline.setTransformation(transformations_up);
if(foundColor)
{
newPolyline.setColor(color);
newPolyline.user_set_color = true;
}
groups[currentGroup].addPolyline(newPolyline);
}
}
else
{
if(findMesh)
{
newMesh.setTransformation(transformations_up);
if(foundColor)
{
newMesh.setColor(color);
newMesh.user_set_color = true;
}
group.addMesh(newMesh);
}
else if(findGroup)
{
newGroup.setTransformation(transformations_up);
if(foundColor)
{
newGroup.setColor(color);
newGroup.user_set_color = true;
}
group.addGroup(newGroup);
}
else if(findPolyline)
{
newPolyline.setTransformation(transformations_up);
if(foundColor)
{
newPolyline.setColor(color);
newPolyline.user_set_color = true;
}
group.addPolyline(newPolyline);
}
}
}
else if(*tIt == "delete")
{
postProcessingLines.push_back(lineNumber);
deletePhase = true;
goto newLineEnd;
}
else if(*tIt == "enddelete")
{
postProcessingLines.push_back(lineNumber);
deletePhase = false;
goto newLineEnd;
}
else if(*tIt == "mesh")
{
constructingMesh = true;
Mesh newMesh(0);
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
if(*tIt == "consolidatedmesh")
{
postProcessingLines.push_back(lineNumber);
current_mesh_name = "consolidatedmesh";
goto newLineEnd;
}
else
{
geometrylines.push_back(nextLine);
}
newMesh.name = *tIt;
newMesh.setGlobalParameter(¶ms);
}
else
{
cout<<warning(26, lineNumber);
goto newLineEnd;
}
}
else
{
cout<<warning(26, lineNumber);
goto newLineEnd;
}
if(meshes.find(newMesh.name) == meshes.end())
{
meshes[newMesh.name] = newMesh;
current_mesh_name = newMesh.name;
}
else
{
cout<<warning(3, lineNumber)<<endl;
}
goto newLineEnd;
}
else if(*tIt == "endmesh")
{
constructingMesh = false;
if(current_mesh_name == "consolidatedmesh")
{
postProcessingLines.push_back(lineNumber);
}
else
{
geometrylines.push_back(nextLine);
}
current_mesh_name = "";
}
}
newLineEnd:
lineNumber++;
}
group.mapFromParameters();
}
void NomeParser::postProcessingWithNome(unordered_map<string, Parameter> ¶ms,
vector<int> &postProcessingLines,
SlideGLWidget *canvas,
Group &group,
string input)
{
if(postProcessingLines.size() == 0)
{
return;
}
ifstream file(input);
if (!file.good())
{
cout<<"THE PATH OF MINI SIF FILE IS NOT VAILD.";
exit(1);
}
string nextLine;
int lineNumber = 1;
bool deletePhase = false;
bool restoreConsolidatedMesh = false;
string current_mesh_name = "";
unordered_map<string, QColor> user_defined_colors;
unordered_map<string, QColor>::iterator colorIt;
vector<int>::iterator fileLineIter = postProcessingLines.begin();
unordered_map<string, Mesh> meshes;
unordered_map<string, Mesh>::iterator meshIt;
unordered_map<string, Face*> global_faces;
unordered_map<string, Face*>::iterator faceIt;
while(std::getline(file, nextLine))
{
istringstream iss(nextLine);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
if((*tIt) != "surface" && lineNumber != (*fileLineIter))
{
goto newLineEnd;
}
else if((*tIt) == "surface")
{
//cout<<nextLine<<endl;
string color_name;
QColor new_color;
if(++tIt < tokens.end())
{
color_name = (*tIt);
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
cout<<warning(16, lineNumber)<<endl;
goto newLineEnd;
}
}
else
{
cout<<warning(17, lineNumber)<<endl;
}
if(++tIt < tokens.end())
{
if((*tIt) != "color")
{
cout<<warning(17, lineNumber)<<endl;
}
}
else
{
cout<<warning(17, lineNumber)<<endl;
}
string color_expression;
bool expression_input = false;
bool inExpression = false;
while(++tIt < tokens.end())
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
expression_input = true;
}
else if(c == ')' && !inExpression)
{
expression_input = false;
goto colordone;
}
else if(c == '#')
{
goto newLineEnd;
}
else if(expression_input)
{
color_expression.push_back(c);
}
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
color_expression.push_back(' ');
}
colordone:
new_color = evaluate_color_expression(color_expression);
user_defined_colors[color_name] = new_color;
goto newLineEnd;
}
else
{
fileLineIter++;
}
if((*tIt) == "mesh")
{
restoreConsolidatedMesh = true;
Mesh newMesh(0);
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
if(*tIt != "consolidatedmesh")
{
cout<<"Error: there is a bug in the program. Check!"<<endl;
goto newLineEnd;
}
newMesh.name = *tIt;
newMesh.setGlobalParameter(¶ms);
}
else
{
cout<<warning(26, lineNumber)<<endl;
goto newLineEnd;
}
}
else
{
cout<<warning(26, lineNumber)<<endl;
goto newLineEnd;
}
if(meshes.find(newMesh.name) == meshes.end())
{
meshes[newMesh.name] = newMesh;
current_mesh_name = newMesh.name;
}
else
{
cout<<warning(3, lineNumber)<<endl;
}
goto newLineEnd;
}
else if((*tIt) == "endmesh")
{
restoreConsolidatedMesh = false;
goto newLineEnd;
}
else if((*tIt) == "delete")
{
deletePhase = true;
goto newLineEnd;
}
else if((*tIt) == "enddelete")
{
deletePhase = false;
goto newLineEnd;
}
else if((*tIt) == "face" && deletePhase)
{
string deleteFaceName = "";
if(++tIt < tokens.end())
{
deleteFaceName = *tIt;
}
else
{
cout<<warning(24, lineNumber)<<endl;
goto newLineEnd;
}
//cout<<deleteFaceName<<endl;
bool found = (canvas
-> hierarchical_scene_transformed).deleteFaceInThisGroup(deleteFaceName);
if(!found)
{
cout<<warning(25, lineNumber)<<endl;
}
goto newLineEnd;
}
else if((*tIt) == "face" && restoreConsolidatedMesh)
{
if(current_mesh_name != "consolidatedmesh")
{
cout<<"Error: there is a bug in the program. Check!"<<endl;
goto newLineEnd;
}
Face * newFace = new Face;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
faceIt = global_faces.find(*tIt);
if(faceIt == global_faces.end())
{
newFace -> name = *tIt;
global_faces[*tIt] = newFace;
}
else
{
cout<<warning(20, lineNumber)<<endl;
}
}
else
{
cout<<warning(19, lineNumber)<<endl;
}
}
string vertInside = "";
bool addingVert = false;
vector<Vertex*> vertices;
vertices.clear();
while(++tIt < tokens.end() && (*tIt) != "endface")
{
for(char & c: (*tIt))
{
if(c == '(')
{
addingVert = true;
}
else if(c == ')')
{
addingVert = false;
if(vertInside != "")
{
Vertex *v = (canvas -> hierarchical_scene_transformed).findVertexInThisGroup(vertInside);
if(!(canvas -> master_mesh.isEmpty())) /* Dealing with recovery of SIF.*/
{
v = (canvas -> master_mesh.findVertexInThisMesh(vertInside));
}
if(v == NULL)
{
cout<<warning(9, lineNumber)<<endl;
}
else
{
vertices.push_back(v);
}
vertInside = "";
}
goto endAddingVertInFace;
}
else if(addingVert)
{
vertInside.push_back(c);
}
}
if(vertInside != "")
{
//cout<<vertInside<<endl;
Vertex *v = (canvas -> hierarchical_scene_transformed).findVertexInThisGroup(vertInside);
if(!(canvas -> master_mesh.isEmpty())) /* Dealing with recovery of SIF.*/
{
v = (canvas -> master_mesh.findVertexInThisMesh(vertInside));
}
if(v == NULL)
{
cout<<warning(9, lineNumber)<<endl;
}
else
{
vertices.push_back(v);
}
vertInside = "";
}
}
endAddingVertInFace:
/* Add this face to the current mesh.*/
vector<Vertex*> mappedVertices;
mappedVertices.clear();
bool foundVertex;
for(Vertex * vs : vertices)
{
foundVertex = false;
for(Vertex * v : meshes[current_mesh_name].vertList)
{
if(v -> source_vertex == vs)
{
foundVertex = true;
mappedVertices.push_back(v);
break;
}
}
if(!foundVertex)
{
Vertex * newVertex = new Vertex;
newVertex -> isParametric = vs -> isParametric;
newVertex -> position = vs -> position;
newVertex -> ID = meshes[current_mesh_name].vertList.size();
newVertex -> source_vertex = vs;
newVertex -> name = vs -> name;
newVertex -> x_expr = vs -> x_expr;
newVertex -> y_expr = vs -> y_expr;
newVertex -> z_expr = vs -> z_expr;
newVertex -> influencingParams = vs -> influencingParams;
newVertex -> params = vs -> params;
meshes[current_mesh_name].addVertex(newVertex);
mappedVertices.push_back(newVertex);
}
}
meshes[current_mesh_name].addPolygonFace(mappedVertices);
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> name = newFace -> name;
if(++tIt < tokens.end() && (*tIt) == "surface")
{
string color_name = "";
QColor color;
bool foundColor = false;
if(++tIt < tokens.end())
{
color_name = *tIt;
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
foundColor = true;
color = colorIt -> second;
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
}
else
{
cout<<warning(22, lineNumber)<<endl;
}
if(foundColor)
{
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> color = color;
meshes[current_mesh_name].faceList[meshes[current_mesh_name].faceList.size() - 1]
-> user_defined_color = true;
}
}
delete newFace;
}
else if((*tIt) == "instance")
{
string instanceName;
Mesh newMesh;
string className;
bool findMesh = false;
bool foundColor = false;
QColor color;
if((++tIt) < tokens.end())
{
if(!testComments(*tIt))
{
instanceName = *tIt;
}
}
else
{
cout<<warning(5, lineNumber)<<endl;
}
if((++tIt) < tokens.end())
{
if(!testComments(*tIt))
{
className = *tIt;
}
}
else
{
cout<<warning(6, lineNumber)<<endl;
}
if(className != "consolidatedmesh")
{
cout<<"Error: there is a bug in the program. Check!"<<endl;
goto newLineEnd;
}
else
{
meshIt = meshes.find(className);
if(meshIt != meshes.end())
{
newMesh = (meshIt -> second).makeCopyForTempMesh(instanceName);
findMesh = true;
}
}
vector<Transformation> transformations_up;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
if(testComments(*tIt))
{
goto newLineEnd;
}
if(*tIt == "rotate")
{
string xyz;
string angle;
bool makingXYZ = false;
bool makingAngle = false;
bool doneXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
if(!doneXYZ)
{
makingXYZ = true;
}
else
{
makingAngle = true;
}
}
else if(c == ')' && !inExpression)
{
if(makingXYZ)
{
doneXYZ = true;
makingXYZ = false;
} else if(makingAngle)
{
makingAngle = false;
goto endWhile1;
}
}
else
{
if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
else if(makingAngle)
{
angle.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
}
if(makingXYZ && xyz != "")
{
xyz.push_back(' ');
}
else if(makingAngle && angle != "")
{
angle.push_back(' ');
}
}
endWhile1:
Transformation t(1, ¶ms, xyz, angle);
transformations_up.push_back(t);
}
else if(*tIt == "translate" || *tIt == "scale")
{
bool isTranslate = false;
if(*tIt == "translate")
{
isTranslate = true;
}
string xyz = "";
bool makingXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZ = true;
}
else if(c == ')' && !inExpression)
{
makingXYZ = false;
goto endWhile2;
}
else if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyz != "")
{
xyz.push_back(' ');
}
}
endWhile2:
if(isTranslate)
{
Transformation t(3,¶ms, xyz);
transformations_up.push_back(t);
}
else
{
Transformation t(2, ¶ms, xyz);
transformations_up.push_back(t);
}
}
else if(*tIt == "mirror")
{
string xyzw = "";
bool makingXYZW = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZW = true;
}
else if(c == ')' && !inExpression)
{
makingXYZW = false;
goto endWhile3;
}
else if(makingXYZW)
{
xyzw.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyzw != "")
{
xyzw.push_back(' ');
}
}
endWhile3:
Transformation t(4, ¶ms, xyzw);
transformations_up.push_back(t);
}
if(*tIt == "surface")
{
string color_name;
if(++tIt < tokens.end())
{
color_name = *tIt;
colorIt = user_defined_colors.find(color_name);
if(colorIt != user_defined_colors.end())
{
color = colorIt -> second;
foundColor = true;
}
else
{
cout<<warning(18, lineNumber)<<endl;
}
}
else
{
cout<<warning(18, lineNumber)<<endl;
}
}
}
if(findMesh)
{
newMesh.setTransformation(transformations_up);
if(foundColor)
{
newMesh.setColor(color);
newMesh.user_set_color = true;
}
group.addMesh(newMesh);
}
else
{
cout<<"Error: there is a bug in the program. Check!"<<endl;
}
}
else
{
cout<<nextLine<<endl;
goto newLineEnd;
}
}
newLineEnd:
lineNumber++;
}
canvas -> set_to_editing_mode(true);
canvas -> updateFromSavedMesh();
}
void NomeParser::appendWithANOM(unordered_map<string, Parameter> ¶ms,
Group &group,
SlideGLWidget* canvas,
string input)
{
ifstream file(input);
if (!file.good())
{
cout<<"THE PATH OF MINI SIF FILE IS NOT VAILD.";
exit(1);
}
string nextLine;
int lineNumber = 1;
bool restoreBank = false;
bool restoreConsolidateMesh = false;
unordered_map<string, Parameter>::iterator pIt;
vector<Vertex*> restore_vertices;
unordered_map<string, Group> groups;
string currentGroup = "";
while(std::getline(file, nextLine))
{
istringstream iss(nextLine);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
if(testComments(*tIt))
{
break;
}
else if((*tIt) == "savedparameter")
{
restoreBank = true;
goto newLineEnd;
}
else if((*tIt) == "endsavedparameter")
{
restoreBank = false;
goto newLineEnd;
}
else if((*tIt) == "consolidate")
{
restoreConsolidateMesh = true;
goto newLineEnd;
}
else if((*tIt) == "endconsolidate")
{
restoreConsolidateMesh = false;
goto newLineEnd;
}
else if(restoreBank)
{
pIt = params.find(*tIt);
if(pIt == params.end())
{
cout<<warning(7, lineNumber)<<endl;
}
else
{
tIt++;
if(tIt >= tokens.end() || testComments(*tIt))
{
cout<<warning(8, lineNumber)<<endl;
}
else
{
float value = stof(*tIt);
(pIt -> second).changeParameterValue(value);
}
}
goto newLineEnd;
}
else if(restoreConsolidateMesh)
{
if(*tIt == "consolidateface")
{
restore_vertices.clear();
goto newLineEnd;
}
else if(*tIt == "endconsolidateface")
{
canvas->consolidate_mesh.addPolygonFace(restore_vertices);
goto newLineEnd;
}
else if(*tIt == "vertex")
{
tIt++;
if(tIt >= tokens.end() || testComments(*tIt))
{
cout<<warning(9, lineNumber)<<endl;
}
Vertex *v = (canvas -> hierarchical_scene_transformed).findVertexInThisGroup(*tIt);
if(!(canvas -> master_mesh.isEmpty())) /* Dealing with recovery of SIF.*/
{
v = (canvas -> master_mesh.findVertexInThisMesh(*tIt));
}
if(v == NULL)
{
cout<<warning(9, lineNumber);
}
else
{
(canvas -> consolidate_mesh).addVertex(v);
restore_vertices.push_back(v);
}
goto newLineEnd;
}
}
else if((*tIt) == "instance")
{
string instanceName;
Mesh newMesh;
string className;
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
instanceName = *tIt;
}
}
else
{
cout<<warning(5, lineNumber);
}
if((++tIt) < tokens.end()) {
if(!testComments(*tIt))
{
className = *tIt;
}
}
else
{
cout<<warning(6, lineNumber);
}
if(className == "consolidatemesh")
{
newMesh = (canvas -> consolidate_mesh).makeCopyForTempMesh(instanceName);
}
else
{
goto newLineEnd;
}
vector<Transformation> transformations_up;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
if(testComments(*tIt))
{
goto newLineEnd;
}
if(*tIt == "rotate")
{
string xyz;
string angle;
bool makingXYZ = false;
bool makingAngle = false;
bool doneXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
if(!doneXYZ)
{
makingXYZ = true;
}
else
{
makingAngle = true;
}
}
else if(c == ')' && !inExpression)
{
if(makingXYZ)
{
doneXYZ = true;
makingXYZ = false;
} else if(makingAngle)
{
makingAngle = false;
goto endWhile1;
}
}
else
{
if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
else if(makingAngle)
{
angle.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
}
if(makingXYZ && xyz != "")
{
xyz.push_back(' ');
}
else if(makingAngle && angle != "")
{
angle.push_back(' ');
}
}
endWhile1:
Transformation t(1, ¶ms, xyz, angle);
transformations_up.push_back(t);
}
else if(*tIt == "translate" || *tIt == "scale")
{
bool isTranslate = false;
if(*tIt == "translate")
{
isTranslate = true;
}
string xyz = "";
bool makingXYZ = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZ = true;
}
else if(c == ')' && !inExpression)
{
makingXYZ = false;
goto endWhile2;
}
else if(makingXYZ)
{
xyz.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyz != "")
{
xyz.push_back(' ');
}
}
endWhile2:
if(isTranslate)
{
Transformation t(3,¶ms, xyz);
transformations_up.push_back(t);
}
else
{
Transformation t(2, ¶ms, xyz);
transformations_up.push_back(t);
}
}
else if(*tIt == "mirror")
{
string xyzw = "";
bool makingXYZW = false;
bool inExpression = false;
while(++tIt < tokens.end() && (*tIt) != "endinstance")
{
for(char& c : (*tIt))
{
if(c == '(' && !inExpression)
{
makingXYZW = true;
}
else if(c == ')' && !inExpression)
{
makingXYZW = false;
goto endWhile3;
}
else if(makingXYZW)
{
xyzw.push_back(c);
if(c == '{')
{
inExpression = true;
}
else if(c == '}')
{
inExpression = false;
}
}
}
if(xyzw != "")
{
xyzw.push_back(' ');
}
}
endWhile3:
Transformation t(4, ¶ms, xyzw);
transformations_up.push_back(t);
}
}
if(currentGroup != "")
{
newMesh.setTransformation(transformations_up);
groups[currentGroup].addMesh(newMesh);
}
else
{
newMesh.setTransformation(transformations_up);
group.addMesh(newMesh);
}
}
}
newLineEnd:
lineNumber++;
}
canvas -> updateFromSavedMesh();
}
<file_sep>#ifndef MYSLIDER_H
#define MYSLIDER_H
#include <QWidget>
#include "parameter.h"
#include <QSlider>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
class MySlider : public QWidget
{
Q_OBJECT
public:
MySlider();
MySlider(Parameter *param);
void generalSetup();
void setParameter(Parameter *param);
QSlider *slider;
QLabel *currValue;
private:
Parameter *param;
public slots:
void changeValue(int);
signals:
void paramValueChanged(float);
};
#endif // MYSLIDER_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "nomeglwidget.h"
#include "controlpanel.h"
#include "nomeparser.h"
#include "sliderpanel.h"
QT_BEGIN_NAMESPACE
class QAction;
class QActionGroup;
class QLabel;
class QMenu;
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
private:
void createActions();
void createMenus();
void createCanvas(QString name);
void createControlPanel(SlideGLWidget *canvas);
void createSliderPanel(SlideGLWidget * canvas);
void save_current_status_nome(string out_put_file);
void save_current_status_anom(string out_put_file);
QMenu *fileMenu;
QAction *openAct;
QAction *saveAct;
QAction *closeAct;
QAction *quitAct;
SlideGLWidget *canvas;
ControlPanel *controls;
NomeParser *nomeParser;
Group scene;
Group append_scene;
unordered_map<string, Parameter> params;
vector<ParameterBank> banks;
vector<SliderPanel*> slider_panels;
vector<string> colorlines;
vector<string> banklines;
vector<string> geometrylines;
vector<int> postProcessingLines;
private slots:
void open();
void save();
void close();
void quit();
protected:
void contextMenuEvent(QContextMenuEvent *event) Q_DECL_OVERRIDE;
};
#endif // MAINWINDOW_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __MESH_H__
#define __MESH_H__
#include <vector>
#include <unordered_map>
#include <glm/glm.hpp>
#include <glm/gtc/constants.hpp>
#include <string>
#include <QMainWindow>
#include <QtOpenGL>
#if __linux__
#include <GL/glut.h>
#include <GL/gl.h>
#elif __APPLE__
#include <GLUT/GLUT.h>
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#endif
#include "face.h"
#include "transformation.h"
#include "utils.h"
class Parameter;
class Group;
using namespace std;
using namespace glm;
//////////////////////////////////////////////////////////////////////
// Mesh Class -- A MESH is a collection of polygon facets
class Mesh
{
public:
/* A list of all vertices in this mesh. */
vector<Vertex*> vertList;
/* A list of all facets in this mesh.*/
vector<Face*> faceList;
/* This is an auxillary table to build a mesh, matching edge to vertex.*/
unordered_map<Vertex*, vector<Edge*> > edgeTable;
Mesh(int type = 0);
/**
* @brief addVertex: Add one vertex to this Mesh.
* @param v, the vertex to be added in.
*/
void addVertex(Vertex * v);
/**
* @brief addVertex: Add one vertex to this Mesh,
* the position of the vertex is made of an expression.
* @param v, the vertex to be added in.
* @param expr, the expresssions for the vertex.
*/
void addVertex(Vertex * v, vector<string> &expr);
/**
* @brief deleteVertex: Delete one vertex from this Mesh.
* If vertex is not in this mesh, do nothing.
* @param v: a pointer to the vertex that we want to delete.
*/
void deleteVertex(Vertex *v);
/**
* @brief Add one edge v1-v2 to this Mesh.
* @param v1, v2: the two vertices of this edge.
* If it already exists, then return the existing edge.
*/
Edge * createEdge(Vertex * v1, Vertex * v2);
/**
* @brief Find one edge v1-v2 in this Mesh.
* @param v1, v2: the two vertices of this edge.
* If it does not exists, then return NULL.
*/
Edge * findEdge(Vertex * v1, Vertex * v2);
/**
* @brief deleteEdge Delete edge v1-v2 in this Mesh.
* @param v1, v2: the two vertices of this edge.
*/
void deleteEdge(Edge * edge);
/**
* @brief Add a triangle face to a mesh, with three vertices.
* @param v1, v2, v3 are the three vertices of the face.
*/
void addTriFace(Vertex * v1, Vertex * v2, Vertex * v3);
// Add a quad face to a mesh, with three vertices.
// @param v1, v2, v3, v4 are the four vertices of the face.
void addQuadFace(Vertex * v1, Vertex * v2, Vertex * v3, Vertex * v4);
// Add a arbitrary polygon face to a mesh, with three vertices.
// @param vertices is a list of consequtive vertices of the face.
void addPolygonFace(vector<Vertex*> vertices, bool reverseOrder = false);
/**
* @brief delelteFace: Delete a face from this mesh.
* @param face: the face to be deleted.
*/
void deleteFace(Face * face);
/**
* @brief drawMesh: Draw a mesh in OpenGL
* @param startIndex: The starting index of drawing polygon name.
* @param smoothShading: Indicate if we are in smooth shading or flat shading.
*/
/**
* @brief makeCopy: Make a copy of current mesh.
* @return The copied mesh.
*/
Mesh makeCopy(string copy_mesh_name = "");
/**
* @brief makeCopyForTransform: Make a copy of current mesh.
* It is used for future transformation.
* @return The copied mesh in order to transform.
*/
Mesh makeCopyForTransform();
/**
* @brief makeCopyForTempMesh: Make a copy of the temp mesh from canvas.
* @param copy_mesh_name: the name of the new copy mesh.
* @return The copied mesh.
*/
Mesh makeCopyForTempMesh(string copy_mesh_name);
void updateCopyForTransform();
/**
* @brief transform: Transform this mesh.
* @param t: The transformation for this mesh.
*/
void transform(Transformation* t);
void transform(mat4 matrix);
mat4 transformToTop();
void drawMesh(int startIndex, bool smoothShading);
// Draw the selected vertices in OpenGL
void drawVertices();
// Build Boundary Pointers for Mesh.
void buildBoundary();
// Reverse the effect of buildBoundary function on some vertices. */
void setBoundaryEdgeToNull(Vertex* v);
// Compute the vertex normals for every face and vertex of the mesh.
void computeNormals();
// Return the list of edges on the boarders
vector<Edge*> boundaryEdgeList();
/* The color of this mesh.*/
QColor color;
/* Check if this mesh if empty. */
bool isEmpty();
/* Set color of this mesh*/
void setColor(QColor color);
/**
* @brief clear: clear the current mesh.
*/
void clear();
/**
* @brief clear: clear the current mesh and delete the vertices and faces.
*/
void clearAndDelete();
/* Indicator of whether user sets the color of this mesh.*/
bool user_set_color;
/* transformation matrix to go up one level.*/
vector<Transformation> transformations_up;
/* Add one transformation to this mesh of going up one level. */
void addTransformation(Transformation new_transform);
/* Reset the transformations to this mesh of going up one level. */
void setTransformation(vector<Transformation>);
/* The name of this mesh. */
string name;
/* Update the value of all elements made by expression. */
void updateMesh();
/* A map of vertex ID to its position expression. */
unordered_map<int, vector<string> > idToExprs;
/* A pointer to the global parameter. */
unordered_map<string, Parameter> *params;
/* Set the global parameter pointer for this mesh. */
void setGlobalParameter(unordered_map<string, Parameter> *params);
/* The paraent group of this mesh. */
Group *parent;
/**
* Type of this mesh.
* 0: A general mesh.
* 1: A Funnel.
* 2: A Tunnel.
* 3: A rim line.
* 99: Consolidated mesh or Temporary mesh.
*/
int type;
/* Parameters used by funnel. */
int n;
float ro;
float ratio;
float h;
string n_expr;
string ro_expr;
string ratio_expr;
string h_expr;
void makeFunnel();
void makeTunnel();
void updateFunnel();
void updateTunnel();
void updateFunnel_n();
void updateTunnel_n();
void updateFunnel_ro_ratio_or_h();
void updateTunnel_ro_ratio_or_h();
void setFunnelParameterValues(string);
void setTunnelParameterValues(string);
vector<Parameter*> influencingParams;
/* Add a parameter that influence this funnel. */
void addParam(Parameter*);
/* The pointer to the copied mesh before transformation. */
Mesh * before_transform_mesh;
/* Find a vertex in this mesh given its name. */
Vertex * findVertexInThisMesh(string name);
/* Find a face in this mesh given its name. And delete this face.
* return true if it is in this mesh. */
bool deleteFaceInThisMesh(string name);
/* Indicator that this group is in editing mode.
* So we can't change the hyper parameters of this mesh,
* e.g. the parameter n of the mesh.
*/
bool in_editing_mode;
/* For the face deletion for consolidate mesh.*/
bool isConsolidateMesh;
/* Update the vertList after we delete from consolidate mesh.*/
void updateVertListAfterDeletion();
};
// @param p1, p2, p3 are positions of three vertices,
// with edge p1 -> p2 and edge p2 -> p3.
vec3 getNormal3Vertex(vec3 p1, vec3 p2, vec3 p3);
#define PI (glm::pi<float>())
#define VERYSMALLVALUE 0.001
#endif // __MESH_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef MAKEGROUP_H
#define MAKEGROUP_H
#include "group.h"
#include "mesh.h"
#include "makeMesh.h"
#include "polyline.h"
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
using namespace glm;
using namespace std;
//////////////////////////////////////////////////////////////////////
// MakeGroup Class -- Unit test class for group
void makeGroupTest1(Group &group);
void makeGroupTest2(Group &group);
void makeGroupTest3(Group &group);
void makeGroupTest4(Group &group);
void makeGroupTest5(Group &group);
void makeGroupTest6(Group &group);
#endif // MAKEGROUP_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __MYSELECTION_H__
#define __MYSELECTION_H__
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <vector>
#include <unordered_map>
#include "polyline.h"
#include "mesh.h"
using namespace glm;
using namespace std;
//////////////////////////////////////////////////////////////////////
// Selection Class -- Handles Mouse Selection.
class MySelection
{
private:
/* Faces selected. Can be used to delete Face or change colors.*/
unordered_map<Mesh*, vector<Face*> > selectedFaces;
/* For partial border selection/*/
Vertex * firstBorderSelectionPoint = NULL;
Vertex * secondBorderSelectionPoint = NULL;
vector<Vertex*> allBorderPoints;
vector<Vertex*> firstHalfBorder;
vector<Vertex*> vertToSelect;
public:
/* Vertices selected. Can be used to create Face or Polyline.*/
vector<Vertex*> selectedVertices;
/**
* @brief list_hits: A debug function. Shows the current hit
* objects names.
* @param hits: The returned hits from GL_SELECT mode name buffer.
* Indicating objects hit by the clicking ray.
* @param names: The user defined name buffer.
*/
void list_hits(GLint hits, GLuint *names);
/**
* @brief: Select the hitted face from mesh.
* @param mesh: the mesh that contains this face.
* @param hits: The returned hits from GL_SELECT mode name buffer.
* Indicating objects hit by the clicking ray.
* @param names: The user defined name buffer.
*/
void selectFace(vector<Mesh*> &globalMeshList, vector<int> &globalNameIndexList,
GLint hits, GLuint *names);
void selectFace(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolylineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
/**
* @brief selectVertex: Select the nearest vertex.
* @param mesh: the mesh that contains this face.
* @param hits: The returned hits from GL_SELECT mode name buffer.
* Indicating objects hit by the clicking ray.
* @param names: The user defined name buffer.
* @param posX: X position from the actual hit point on polygon.
* @param posY: Y position from the actual hit point on polygon.
* @param posZ: Z position from the actual hit point on polygon.
*/
void selectVertex(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
void selectVertex(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolyllineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
// Select all border vertices
/**
* @brief selectWholeBorder: Select all vertices from a border.
* The border is the cloest one to the clicking ray hit.
* @param mesh: the mesh that contains this face.
* @param hits: The returned hits from GL_SELECT mode name buffer.
* Indicating objects hit by the clicking ray.
* @param names: The user defined name buffer.
* @param posX: X position from the actual hit point on polygon.
* @param posY: Y position from the actual hit point on polygon.
* @param posZ: Z position from the actual hit point on polygon.
*/
void selectWholeBorder(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
void selectWholeBorder(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolyllineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
/**
* @brief selectPartialBorder: Select all vertices from a border.
* The border is the cloest one to the clicking ray hit.
* @param mesh: the mesh that contains this face.
* @param hits: The returned hits from GL_SELECT mode name buffer.
* Indicating objects hit by the clicking ray.
* @param names: The user defined name buffer.
* @param posX: X position from the actual hit point on polygon.
* @param posY: Y position from the actual hit point on polygon.
* @param posZ: Z position from the actual hit point on polygon.
*/
void selectPartialBorder(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
void selectPartialBorder(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolyllineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ);
/**
* @brief: clear the current selection
*/
void clearSelection();
/**
* @brief addSelectedToMesh: Add the selected vertices as a polygon to
* a mesh.
* @param mesh. The destiny mesh.
*/
void addSelectedToMesh(Mesh &mesh);
/**
* @brief addSelectedToPolyline: Add the selected vertices to a new polyline.
* @param isLoop: indicate if this polyline is a loop.
* @return pointer to the new polyline
*/
PolyLine addSelectedToPolyline(bool isLoop = false);
/* Delete the faces that we have selected. */
void deleteSelectedFaces(vector<string> & deletedFaces);
};
#endif // SELECTION_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "group.h"
Group::Group()
{
subgroups.clear();
myMeshes.clear();
myPolylines.clear();
user_set_color = false;
transformations_up.clear();
parent = NULL;
in_editing_mode = false;
}
void Group::addMesh(Mesh &mesh)
{
myMeshes.push_back(mesh);
mesh.parent = this;
}
void Group::addGroup(Group &group)
{
subgroups.push_back(group);
group.parent = this;
}
void Group::addPolyline(PolyLine &polyline)
{
myPolylines.push_back(polyline);
polyline.parent = this;
}
vector<Mesh*> Group::flattenedMeshes()
{
vector<Mesh*> result;
vector<Mesh>::iterator mIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
for(Transformation& transformUp : (*mIt).transformations_up)
{
(*mIt).transform(&transformUp);
}
(*mIt).computeNormals();
result.push_back(&(*mIt));
}
vector<Group>::iterator gIt;
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
vector<Mesh*> flattenedFromThisSubGroup = (*gIt).flattenedMeshes();
vector<Mesh*>::iterator mpIt;
for(mpIt = flattenedFromThisSubGroup.begin();
mpIt < flattenedFromThisSubGroup.end(); mpIt++)
{
for(Transformation& transformUp : (*gIt).transformations_up)
{
(**mpIt).transform(&transformUp);
}
result.push_back(*mpIt);
}
}
return result;
}
vector<PolyLine*> Group::flattenedPolylines()
{
vector<PolyLine*> result;
vector<PolyLine>::iterator pIt;
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
for(Transformation& transformUp : (*pIt).transformations_up)
{
(*pIt).transform(&transformUp);
}
result.push_back(&(*pIt));
}
vector<Group>::iterator gIt;
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
vector<PolyLine*> flattenedFromThisSubGroup = (*gIt).flattenedPolylines();
vector<PolyLine*>::iterator ppIt;
for(ppIt = flattenedFromThisSubGroup.begin();
ppIt < flattenedFromThisSubGroup.end(); ppIt++)
{
for(Transformation& transformUp : (*gIt).transformations_up)
{
(*(*ppIt)).transform(&transformUp);
}
result.push_back(*ppIt);
}
}
return result;
}
void Group::assignColor()
{
vector<Mesh>::iterator mIt;
vector<PolyLine>::iterator pIt;
vector<Group>::iterator gIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
if(!((*mIt).user_set_color))
{
(*mIt).setColor(color);
}
}
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
if(!((*pIt).user_set_color)) {
(*pIt).setColor(color);
}
}
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
if(!((*gIt).user_set_color))
{
(*gIt).setColor(color);
(*gIt).assignColor();
}
else
{
(*gIt).assignColor();
}
}
}
void Group::updateGroupElementName()
{
vector<Mesh>::iterator mIt;
vector<PolyLine>::iterator pIt;
vector<Group>::iterator gIt;
if(this -> name != "" || this -> parent == NULL)
{
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
if(this -> parent != NULL)
{
(*mIt).name = this->name + "_" + (*mIt).name;
}
for(Vertex*& v : (*mIt).vertList)
{
v -> name = (*mIt).name + "_" + v -> name;
}
for(Face*& f : (*mIt).faceList)
{
if(f -> name == "")
{
f -> name = (*mIt).name + "_" + to_string(f -> id);
}
else
{
f -> name = (*mIt).name + "_" + f -> name;
}
}
}
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
(*pIt).name = this -> name + "_" + (*pIt).name;
for(Vertex*& v: (*pIt).vertices)
{
v -> name = (*pIt).name + "_" + v -> name;
}
}
}
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
(*gIt).updateGroupElementName();
}
}
void Group:: setColor(QColor color)
{
this -> color = color;
}
Mesh Group::merge()
{
vector<Mesh*> flatten = this -> flattenedMeshes();
return ::merge(flatten);
}
void Group::addTransformation(Transformation new_transform)
{
transformations_up.push_back(new_transform);
}
void Group::setTransformation(vector<Transformation> new_transforms)
{
transformations_up = new_transforms;
}
void Group::clear()
{
subgroups.clear();
myMeshes.clear();
myPolylines.clear();
transformations_up.clear();
}
void Group::clearAndDelete()
{
for(Group g: subgroups) {
g.clearAndDelete();
}
for(Mesh m: myMeshes) {
m.clearAndDelete();
}
subgroups.clear();
myMeshes.clear();
myPolylines.clear();
transformations_up.clear();
}
Group Group::makeCopy(string copy_group_name)
{
Group newGroup;
newGroup.clear();
if(copy_group_name == "")
{
newGroup.name = this->name;
}
else
{
newGroup.name = copy_group_name;
}
vector<Mesh>::iterator mIt;
vector<Group>::iterator gIt;
vector<PolyLine>::iterator pIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
Mesh newMesh = (*mIt).makeCopy();
newMesh.transformations_up = (*mIt).transformations_up;
newMesh.user_set_color = (*mIt).user_set_color;
newMesh.color = (*mIt).color;
newGroup.addMesh(newMesh);
}
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
PolyLine newPolyline = (*pIt).makeCopy();
newPolyline.transformations_up = (*pIt).transformations_up;
newPolyline.user_set_color = (*pIt).user_set_color;
newPolyline.color = (*pIt).color;
newGroup.addPolyline(newPolyline);
}
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
Group copyGroup = (*gIt).makeCopy();
copyGroup.transformations_up = (*gIt).transformations_up;
copyGroup.user_set_color = (*gIt).user_set_color;
copyGroup.color = (*gIt).color;
newGroup.addGroup(copyGroup);
}
return newGroup;
}
Group Group::makeCopyForTransform()
{
Group newGroup;
newGroup.before_transform_group = this;
newGroup.name = this->name;
newGroup.clear();
vector<Mesh>::iterator mIt;
vector<Group>::iterator gIt;
vector<PolyLine>::iterator pIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
Mesh newMesh = (*mIt).makeCopyForTransform();
newMesh.transformations_up = (*mIt).transformations_up;
newMesh.user_set_color = (*mIt).user_set_color;
newMesh.color = (*mIt).color;
newGroup.addMesh(newMesh);
}
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
PolyLine newPolyline = (*pIt).makeCopyForTransform();
newPolyline.transformations_up = (*pIt).transformations_up;
newPolyline.user_set_color = (*pIt).user_set_color;
newPolyline.color = (*pIt).color;
newGroup.addPolyline(newPolyline);
}
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
Group copyGroup = (*gIt).makeCopyForTransform();
copyGroup.transformations_up = (*gIt).transformations_up;
copyGroup.user_set_color = (*gIt).user_set_color;
copyGroup.color = (*gIt).color;
newGroup.addGroup(copyGroup);
}
return newGroup;
}
void Group::updateCopyForTransform()
{
transformations_up = before_transform_group -> transformations_up;
vector<Mesh>::iterator mIt;
vector<Group>::iterator gIt;
vector<PolyLine>::iterator pIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
(*mIt).updateCopyForTransform();
}
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
(*pIt).updateCopyForTransform();
}
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
(*gIt).updateCopyForTransform();
}
}
void Group::setName(string name)
{
this -> name = name;
}
void Group::mapFromParameters()
{
bool found;
for(Transformation& t : transformations_up)
{
vector<Parameter*> params = t.influencingParams;
for(Parameter*& p : params)
{
p->addInfluenceTransformation(&t);
}
}
vector<Mesh>::iterator mIt;
for(mIt = myMeshes.begin(); mIt < myMeshes.end(); mIt++)
{
vector<Parameter*> params = (*mIt).influencingParams;
for(Parameter*& p : params)
{
p->addInfluenceMesh(&(*mIt));
}
for(Transformation& t : (*mIt).transformations_up)
{
vector<Parameter*> params = t.influencingParams;
for(Parameter*& p : params)
{
p->addInfluenceTransformation(&t);
}
}
for(Vertex*& v : (*mIt).vertList)
{
vector<Parameter*> params = v -> influencingParams;
for(Parameter*& p : params)
{
found = false;
for(Vertex * vin : p -> influenceVertices)
{
if(vin == v)
{
found = true;
}
}
if(!found)
{
p->addInfluenceVertex(v);
}
}
}
}
vector<PolyLine>::iterator pIt;
for(pIt = myPolylines.begin(); pIt < myPolylines.end(); pIt++)
{
for(Vertex*& v : (*pIt).vertices)
{
vector<Parameter*> params = v -> influencingParams;
for(Parameter*& p : params)
{
found = false;
for(Vertex * vin : p -> influenceVertices)
{
if(vin == v)
{
found = true;
}
}
if(!found)
{
p->addInfluenceVertex(v);
}
}
}
for(Transformation& t : (*pIt).transformations_up)
{
vector<Parameter*> params = t.influencingParams;
for(Parameter*& p : params)
{
p->addInfluenceTransformation(&t);
}
}
}
vector<Group>::iterator gIt;
for(gIt = subgroups.begin(); gIt < subgroups.end(); gIt++)
{
(*gIt).mapFromParameters();
}
}
Vertex* Group::findVertexInThisGroup(string name)
{
for(Mesh &mesh : myMeshes)
{
Vertex *v = mesh.findVertexInThisMesh(name);
if(v != NULL)
{
return v;
}
}
for(PolyLine &polyline : myPolylines)
{
Vertex *v = polyline.findVertexInThisPolyline(name);
if(v != NULL)
{
return v;
}
}
for(Group& group : subgroups)
{
Vertex *v = group.findVertexInThisGroup(name);
if(v != NULL)
{
return v;
}
}
return NULL;
}
bool Group::deleteFaceInThisGroup(string name)
{
for(Mesh &mesh : myMeshes)
{
bool found = mesh.deleteFaceInThisMesh(name);
if(found)
{
mesh.buildBoundary();
return true;
}
}
for(Group& group : subgroups)
{
bool found = group.deleteFaceInThisGroup(name);
if(found)
{
return true;
}
}
return false;
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __OFFSET_H__
#define __OFFSET_H__
#include <vector>
#include "mesh.h"
using namespace glm;
//////////////////////////////////////////////////////////////////////
// Offset Class -- Offset for a given mesh.
//
class Offset{
public:
// The amount of offset for this mesh.
float offsetVal;
// The original mesh.
Mesh startMesh;
// The positive offset mesh.
Mesh posOffsetMesh;
// The negtive offset mesh.
Mesh negOffsetMesh;
// The side offset mesh.
Mesh sideOffsetMesh;
// The combination of posOffsetMesh, negOffsetMesh and sideOffsetMesh
Mesh offsetMesh;
// Constructor of offset.
// @param mesh: the initial mesh to find offset
// @param val: the offsetVal
Offset(Mesh & mesh, float val);
// Find the positive and negative offset and their side cover.
// It runs fast and with sharp edge between the cover and offset surface.
void makeSeperateOffset();
// Find the positive, negative and side cover as a whole mesh.
// Runs slow then the seperate one, but have smooth connection between cover and offset surface.
void makeFullOffset();
// Change the value of offset
// @param val: the offset value, can be positive or negative.
void changeOffsetValTo(float val);
private:
// Calculate the offset for one vertex.
// @param v: the vertex to calculate offset.
// @param full: true if we are doing a full offset. false if we are doing seperate offset.
void calcVertexOffset(Vertex * v, bool full);
};
#endif // __OFFSET_H__
<file_sep>#ifndef NOMEPARSER_H
#define NOMEPARSER_H
#include <vector>
#include "parameterbank.h"
#include "nomeglwidget.h"
#include "mesh.h"
#include "polyline.h"
#include "group.h"
#include "utils.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
class NomeParser
{
public:
NomeParser();
void makeWithNome(vector<ParameterBank> &banks,
unordered_map<string, Parameter> ¶ms,
Group &group,
string input,
vector<string> &colorlines,
vector<string> &banklines,
vector<string> &geometrylines,
vector<int> &postProcessingLines);
void postProcessingWithNome(unordered_map<string, Parameter> ¶ms,
vector<int> &postProcessingLines,
SlideGLWidget * canvas,
Group &group,
string input);
void appendWithANOM(unordered_map<string, Parameter> ¶ms,
Group &group,
SlideGLWidget * canvas,
string input);
};
#endif // MINISLFPARSER_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef GROUP_H
#define GROUP_H
#include "mesh.h"
#include "polyline.h"
#include "transformation.h"
#include "merge.h"
#include <vector>
#include <unordered_map>
#include <QColor>
class Group
{
public:
Group();
/* A list of subgroup under this group. */
vector<Group> subgroups;
/* A list of mesh under this group. */
vector<Mesh> myMeshes;
/* A list of polyline under this group. */
vector<PolyLine> myPolylines;
/* The color of this group. */
QColor color;
/* Indicator of whether user sets the color of this group.*/
bool user_set_color;
/**
* @brief addMesh: Add a mesh to this group.
* @param mesh: The pointer to the added mesh.
*/
void addMesh(Mesh &mesh);
/**
* @brief addGroup: Add a group to this group.
* @param group: The pointer to the added group.
*/
void addGroup(Group &group);
/**
* @brief addPolyline: Add a polyline to this group.
* @param polyline: The pointer to the added polyline.
*/
void addPolyline(PolyLine &polyline);
/**
* @brief flattenedMeshes. A flattened view of meshes in this group.
* @return all meshes under this group as a list.
*/
vector<Mesh*> flattenedMeshes();
/**
* @brief flattenedPolylines: A flattened view of polylines in this group.
* @return all polylines under this group as a list.
*/
vector<PolyLine*> flattenedPolylines();
/**
* @brief assignMeshColor. Top to bottom assigning my color
* to all sub meshes and polylines. If any mesh or subgroup
* has user set color, then skip them.
*/
void assignColor();
/**
* @brief merge: Merge this group into a single mesh.
* @return The merged mesh.
*/
Mesh merge();
/**
* @brief setColor: Set the color of this group.
*/
void setColor(QColor color);
/* The transformations to go up one level. */
vector<Transformation> transformations_up;
/* Set the transformation of this group. */
void addTransformation(Transformation new_transform);
/* Set the transformation of this group. */
void setTransformation(vector<Transformation> new_transforms);
/* make a copy of this group.*/
Group makeCopy(string copy_group_name = "");
/* make a copy of this group for future transformation. */
Group makeCopyForTransform();
/* Update me based on what I copied from .*/
void updateCopyForTransform();
/* Clear this group.*/
void clear();
/* Clear and delete everything from this group.*/
void clearAndDelete();
/* name of this group. */
string name;
/* set name of this group. */
void setName(string);
/* The parent of this group. */
Group* parent;
/**
* Build maps from parameters to the leaves of this group.
*/
void mapFromParameters();
/* A pointer to the original group before transformation. */
Group * before_transform_group;
/* Update the names for all elements in the group. Used for the final scene.*/
void updateGroupElementName();
/* Find a vertex given its hierarchical name.*/
Vertex* findVertexInThisGroup(string name);
/* Find a face given its hierachical name and delete this face. */
bool deleteFaceInThisGroup(string name);
/* Indicator that this group is in editing mode.
* So we can't change the hyper parameters of this mesh,
* e.g. the parameter n of the mesh.
*/
bool in_editing_mode;
};
#endif // GROUP_H
<file_sep>#ifndef TESTPOLYLINE_H
#define TESTPOLYLINE_H
#include "polyline.h"
class TestPolyline
{
public:
TestPolyline();
PolyLine line;
};
#endif // TESTPOLYLINE_H
<file_sep>#include "parameterbank.h"
ParameterBank::ParameterBank()
{
parameters.clear();
}
void ParameterBank::addParameter(Parameter *param)
{
parameters.push_back(param);
}
void ParameterBank::setName(QString name)
{
this -> name = name;
}
<file_sep>#include "sliderpanel.h"
SliderPanel::SliderPanel()
{
}
SliderPanel::SliderPanel(ParameterBank *bank, SlideGLWidget * canvas)
{
this -> bank = bank;
move(50, 900);
QVBoxLayout *mainLayout = new QVBoxLayout;
setLayout(mainLayout);
mainLayout->addWidget(new QLabel(bank -> name));
vector<Parameter*>::iterator pIt;
for(pIt = (bank -> parameters).begin(); pIt < (bank -> parameters).end(); pIt++)
{
Parameter *param = (*pIt);
MySlider *newSlider = new MySlider(param);
param -> slider = newSlider;
mainLayout -> addWidget(newSlider);
connect(newSlider, SIGNAL(paramValueChanged(float)), canvas, SLOT(paramValueChanged(float)));
}
}
<file_sep>#ifndef UTILS_H
#define UTILS_H
#include <string>
#include <iostream>
#include <unordered_map>
#include <glm/glm.hpp>
#include "parameter.h"
#include <stack>
#include <vector>
#include <QColor>
class Transformation;
using namespace glm;
float evaluate_expression(string expr,
unordered_map<string, Parameter> *params);
float evaluate_mesh_expression(string expr,
unordered_map<string, Parameter> *params,
Mesh * mesh);
float evaluate_transformation_expression(string expr,
unordered_map<string, Parameter> *params,
Transformation * t);
float evaluate_vertex_expression(string expr,
unordered_map<string, Parameter> *params,
Vertex * t);
QColor evaluate_color_expression(string expr);
float getParameterValue(string name,
unordered_map<string, Parameter> *params);
float getMeshParameterValue(string name,
unordered_map<string, Parameter> *params,
Mesh * mesh);
float getTransformationParameterValue(string name,
unordered_map<string, Parameter> *params,
Transformation *t);
float getVertexParameterValue(string name,
unordered_map<string, Parameter> *params,
Vertex * mesh);
bool isOperator(char token);
float getVal(float x, float y, char oper);
int getPriority(char oper);
vec3 getXYZ(string input);
float getOneValue(string input);
vec4 getXYZW(string input);
#endif // UTILS_H
<file_sep># Non-Orientable Manifold Editor (NOME)
Welcome to the non-orientable manifold editor (NOME) project. NOME is a computer aided geometric design tool developed at UC Berkeley from 2015. Inheiriting the major functionaliies from its ancestor SLIDE (https://people.eecs.berkeley.edu/~ug/slide/), NOME also provides a design envrionment that support mesh operations on single-sided 2 manifolds (wikipedia definition for manifold https://en.wikipedia.org/wiki/Manifold). It also supprt various fun and interactive UI operations such as vertex/face selection, face adding/deletion.
# User's Guide
1. Platforms, Download and Installation
NOME is developend and released on various platforms, including Microsoft Windows 7 or higher system, Mac OS, and Linus system.
2. Getting started
3. A Hello-Cube example
4. Want to explore more?
Appendix A: Commands of input .nome file
Appendix B: User Interface Details
# Programmer's Guide
1. Working Platform
2. Libraies and Dependcies
3. Get started programming with NOME
4. Some suggestions on contributing to NOME project
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "myselection.h"
void MySelection::list_hits(GLint hits, GLuint *names)
{
int i;
/*
For each hit in the buffer are allocated 4 bytes:
1. Number of hits selected (always one,
beacuse when we draw each object
we use glLoadName, so we replace the
prevous name in the stack)
2. Min Z
3. Max Z
4. Name of the hit (glLoadName)
*/
printf("%d hits:\n", hits);
for (i = 0; i < hits; i++)
printf( "Number: %d\n"
"Min Z: %d\n"
"Max Z: %d\n"
"Name on stack: %d\n",
(GLubyte)names[i * 4],
(GLubyte)names[i * 4 + 1],
(GLubyte)names[i * 4 + 2],
(GLubyte)names[i * 4 + 3]
);
printf("\n");
}
void MySelection::selectFace(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits,
GLuint *names)
{
if(hits > 0) {
int minimumDepth = INT_MAX;
int minimumDepthIndex = INT_MAX;
for (int i = 0; i < hits; i++) {
int currentDepth = (GLubyte)names[i * 4 + 1];
if(currentDepth < minimumDepth) {
minimumDepth = currentDepth;
minimumDepthIndex = i;
}
}
int currentID = names[minimumDepthIndex * 4 + 3];
Face * workFace;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
if(!workFace->selected)
{
workFace->selected = true;
}
else
{
workFace->selected = false;
}
}
}
void MySelection::selectFace(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolylineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Face * selectedFace = NULL;
Mesh * selectedMesh = NULL;
int endOfMesh = INT_MAX;
if(globalPolylineNameIndexList.size() > 0)
{
endOfMesh = globalPolylineNameIndexList[0];
}
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace = NULL;
Mesh * workMesh = NULL;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
/* Select a point on the polyline has a priority. */
if(currentID < endOfMesh)
{
for(mIt = globalMeshList.begin(),
nIt = globalNameIndexList.begin();
mIt < globalMeshList.end(); mIt++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
workMesh = currMesh;
break;
}
}
if(workFace != NULL)
{
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedFace = workFace;
selectedMesh = workMesh;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
}
}
unordered_map<Mesh*, vector<Face*> >::iterator mfIt;
if(selectedFace != NULL)
{
if(selectedFace -> selected)
{
selectedFace -> selected = false;
mfIt = selectedFaces.find(selectedMesh);
if(mfIt != selectedFaces.end())
{
vector<Face*>::iterator fIt;
for(fIt = (mfIt -> second).begin();
fIt < (mfIt -> second).end(); fIt ++) {
if((*fIt) == selectedFace) {
break;
}
}
(mfIt -> second).erase(fIt);
cout<<"Unselected Face: "<<selectedFace -> name<<endl;
}
else
{
cout<<"Error, there is a bug in the selectoin program!"<<endl;
}
}
else
{
selectedFace -> selected = true;
mfIt = selectedFaces.find(selectedMesh);
if(mfIt == selectedFaces.end())
{
vector<Face*> faces;
faces.push_back(selectedFace);
cout<<"Selected Face: "<<selectedFace -> name<<endl;
selectedFaces[selectedMesh] = faces;
}
else
{
(mfIt -> second).push_back(selectedFace);
cout<<"Selected Face: "<<selectedFace -> name<<endl;
}
}
}
else
{
cout<<"You did not click on a face."<<endl;
}
}
}
void MySelection::selectVertex(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolylineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex = NULL;
int endOfMesh = INT_MAX;
if(globalPolylineNameIndexList.size() > 0)
{
endOfMesh = globalPolylineNameIndexList[0];
}
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace = NULL;
Vertex *workVertex = NULL;
vector<Mesh*>::iterator mIt;
vector<PolyLine*>::iterator pIt;
vector<int>::iterator nIt;
/* Select a point on the polyline has a priority. */
if(currentID >= endOfMesh)
{
for(pIt = globalPolylineList.begin(),
nIt = globalPolylineNameIndexList.begin();
pIt < globalPolylineList.end(); pIt++, nIt++)
{
PolyLine *currLine = (*pIt);
if(currentID < (currLine -> vertices).size() + (*nIt))
{
workVertex = currLine -> vertices[currentID - (*nIt)];
float new_distance = distance(workVertex -> position,
hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = workVertex;
}
break;
}
}
if(selectedVertex != NULL)
{
goto getSelectedVertex;
}
}
else
{
for(mIt = globalMeshList.begin(),
nIt = globalNameIndexList.begin();
mIt < globalMeshList.end(); mIt++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
if(workFace != NULL)
{
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
}
}
getSelectedVertex:
if(selectedVertex -> source_vertex != NULL)
{
selectedVertex = selectedVertex -> source_vertex;
}
if(selectedVertex -> selected) {
selectedVertex -> selected = false;
vector<Vertex*>::iterator vIt;
for(vIt = selectedVertices.begin();
vIt < selectedVertices.end(); vIt ++) {
if((*vIt) == selectedVertex) {
break;
}
}
selectedVertices.erase(vIt);
cout<<"Unselected Vertex: "<<selectedVertex -> name<<endl;
cout<<"You have "<<selectedVertices.size()
<<" vertices selected."<<endl;
} else {
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
cout<<"Selected Vertex: "<<selectedVertex -> name<<endl;
cout<<"You have "<<selectedVertices.size()
<<" vertices selected."<<endl;
}
}
}
void MySelection::selectVertex(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex;
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
if(selectedVertex -> selected) {
selectedVertex -> selected = false;
vector<Vertex*>::iterator vIt;
for(vIt = selectedVertices.begin();
vIt < selectedVertices.end(); vIt ++) {
if((*vIt) == selectedVertex) {
break;
}
}
selectedVertices.erase(vIt);
cout<<"Unselected Vertex: "<<selectedVertex -> name<<endl;
cout<<"You have "<<selectedVertices.size()
<<" vertices selected."<<endl;
} else {
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
cout<<"Selected Vertex: "<<selectedVertex -> name<<endl;
cout<<"You have "<<selectedVertices.size()
<<" vertices selected."<<endl;
}
}
}
void MySelection::selectWholeBorder(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex;
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
// Test is this point is on border. If yes, find the startingEdge.
if(selectedVertex != NULL) {
Edge * firstEdge = selectedVertex -> oneEdge;
Edge * currEdge = firstEdge;
Face * currFace = currEdge -> fb;
Edge * nextEdge;
do {
if(currFace == NULL) {
break;
} else {
nextEdge = currEdge -> nextEdge(selectedVertex, currFace);
currFace = nextEdge -> theOtherFace(currFace);
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
if(currFace != NULL) {
cout<<"Your selected vertex is not on the border."
<<" Current Selection Cancelled.\n";
return;
}
if(selectedVertex -> selected) {
cout<<"Unselecting all points on this border.\n";
selectedVertices.clear();
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
nextVert -> selected = false;
//cout<<nextVert -> ID;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
} else {
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
selectedVertices.push_back(nextVert);
nextVert -> selected = true;
//cout<<nextVert -> ID;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
cout<<"You have selected "<<selectedVertices.size()
<<" points on this border.\n";
}
}
}
}
void MySelection::selectPartialBorder(vector<Mesh*> &globalMeshList,
vector<int> &globalNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex;
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
// Test is this point is on border. If yes, find the startingEdge.
if(selectedVertex != NULL) {
Edge * firstEdge = selectedVertex -> oneEdge;
Edge * currEdge = firstEdge;
Face * currFace = currEdge -> fb;
Edge * nextEdge;
do {
if(currFace == NULL) {
break;
} else {
nextEdge = currEdge -> nextEdge(selectedVertex, currFace);
currFace = nextEdge -> theOtherFace(currFace);
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
if(currFace != NULL) {
cout<<"Your selected vertex is not on the border."
<<" Current Selection Cancelled.\n";
return;
}
if (!firstBorderSelectionPoint) {
firstBorderSelectionPoint = selectedVertex;
cout<<"Selecting the first Point on border."<<endl;
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
allBorderPoints.push_back(nextVert);
//cout<<nextVert -> ID<<endl;;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
} else if (!secondBorderSelectionPoint) {
// We need to test if this second point in the border
// of the first selecte point.
vector<Vertex*>::iterator vIt;
for(vIt = allBorderPoints.begin();
vIt < allBorderPoints.end(); vIt++) {
if((*vIt) == selectedVertex) {
if((*vIt) == firstBorderSelectionPoint) {
cout<<"Unselecting the first point on border."<<endl;
firstBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
//(*vIt) -> selected = false;
}
break;
}
}
if(!allBorderPoints.empty()) {
if(vIt == allBorderPoints.end()) {
cout<<"Your choice of the two points are not on the"
<<" same border. Selection ABORT."<<endl;
firstBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
} else {
cout<<"Selecting the second point on border."<<endl;
secondBorderSelectionPoint = selectedVertex;
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
}
}
} else if(!vertToSelect.empty()) {
cout<<"Unselecting all points on partial border."<<endl;
vector<Vertex*>::iterator vIt;
for(vIt = vertToSelect.begin(); vIt < vertToSelect.end(); vIt++) {
(*vIt) -> selected = false;
}
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
vertToSelect.clear();
selectedVertices.clear();
} else {
vector<Vertex*>::iterator vIt;
bool hasSeenSecondPoint = false;
for(vIt = allBorderPoints.begin(); vIt < allBorderPoints.end(); vIt++) {
if((*vIt) == selectedVertex) {
if((*vIt) == firstBorderSelectionPoint
|| (*vIt) == secondBorderSelectionPoint) {
cout<<"Unselecting points on border."<<endl;
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
}
break;
} else if((*vIt) == secondBorderSelectionPoint) {
hasSeenSecondPoint = true;
}
}
if(!allBorderPoints.empty()) {
if(vIt == allBorderPoints.end()) {
cout<<"Your choice of the third points is not on"
<<"the same border. Selection ABORT."<<endl;
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
} else {
cout<<"Selecting this half border on this side."<<endl;
vector<Vertex*>::iterator vSelIt;
if(!hasSeenSecondPoint) {
for(vSelIt = allBorderPoints.begin();
vSelIt < allBorderPoints.end(); vSelIt++) {
vertToSelect.push_back(*vSelIt);
if((*vSelIt) == secondBorderSelectionPoint) {
break;
}
}
} else {
vertToSelect.push_back(firstBorderSelectionPoint);
for(vSelIt = allBorderPoints.end() - 1;
vSelIt >= allBorderPoints.begin(); vSelIt--) {
vertToSelect.push_back(*vSelIt);
if((*vSelIt) == secondBorderSelectionPoint) {
break;
}
}
}
selectedVertices.clear();
for(vSelIt = vertToSelect.begin();
vSelIt < vertToSelect.end(); vSelIt++) {
(*vSelIt) -> selected = true;
selectedVertices.push_back(*vSelIt);
}
cout<<"You have selected "<<selectedVertices.size()
<<" points on this border.\n";
}
}
}
}
}
}
void MySelection::selectWholeBorder(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolylineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex = NULL;
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace = NULL;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
if(workFace != NULL)
{
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
else
{
cout<<"Please click on a face."<<endl;
}
}
// Test is this point is on border. If yes, find the startingEdge.
if(selectedVertex != NULL) {
Edge * firstEdge = selectedVertex -> oneEdge;
Edge * currEdge = firstEdge;
Face * currFace = currEdge -> fb;
Edge * nextEdge;
do {
if(currFace == NULL) {
break;
} else {
nextEdge = currEdge -> nextEdge(selectedVertex, currFace);
currFace = nextEdge -> theOtherFace(currFace);
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
if(currFace != NULL) {
cout<<"Your selected vertex is not on the border."
<<" Current Selection Cancelled.\n";
return;
}
if(selectedVertex -> selected) {
cout<<"Unselecting all points on this border.\n";
selectedVertices.clear();
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
nextVert -> selected = false;
//cout<<nextVert -> ID;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
} else {
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
selectedVertices.push_back(nextVert);
nextVert -> selected = true;
//cout<<nextVert -> ID;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
cout<<"You have selected "<<selectedVertices.size()
<<" points on this border.\n";
}
}
}
}
void MySelection::selectPartialBorder(vector<Mesh*> &globalMeshList,
vector<PolyLine*> &globalPolylineList,
vector<int> &globalNameIndexList,
vector<int> &globalPolylineNameIndexList,
GLint hits, GLuint *names,
GLdouble posX, GLdouble posY, GLdouble posZ)
{
if(hits > 0) {
vec3 hit_position = vec3(posX, posY, posZ);
float min_distance = 500000.0;
Vertex * selectedVertex;
for (int i = 0; i < hits; i++) {
int currentID = names[i * 4 + 3];
Face * workFace;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = globalMeshList.begin(), nIt = globalNameIndexList.begin();
mIt != globalMeshList.end(); mIt ++, nIt++)
{
Mesh *currMesh = (*mIt);
if(currentID < (currMesh -> faceList).size() + (*nIt))
{
workFace = currMesh -> faceList[currentID - (*nIt)];
break;
}
}
if(workFace != NULL)
{
Edge * firstEdge = workFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(workFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
float new_distance = distance(tempv -> position, hit_position);
if(new_distance < min_distance) {
min_distance = new_distance;
selectedVertex = tempv;
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
else
{
cout<<"Please click on a face."<<endl;
}
}
// Test is this point is on border. If yes, find the startingEdge.
if(selectedVertex != NULL) {
Edge * firstEdge = selectedVertex -> oneEdge;
Edge * currEdge = firstEdge;
Face * currFace = currEdge -> fb;
Edge * nextEdge;
do {
if(currFace == NULL) {
break;
} else {
nextEdge = currEdge -> nextEdge(selectedVertex, currFace);
currFace = nextEdge -> theOtherFace(currFace);
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
if(currFace != NULL) {
cout<<"Your selected vertex is not on the border."
<<" Current Selection Cancelled.\n";
return;
}
if (!firstBorderSelectionPoint) {
firstBorderSelectionPoint = selectedVertex;
cout<<"Selecting the first Point on border."<<endl;
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
Vertex * nextVert = selectedVertex;
Edge * nextBorderEdge = currEdge;
do {
allBorderPoints.push_back(nextVert);
//cout<<nextVert -> ID<<endl;;
if(nextVert == nextBorderEdge -> va) {
nextBorderEdge = nextBorderEdge -> nextVaFb;
} else {
nextBorderEdge = nextBorderEdge -> nextVbFb;
}
if(nextBorderEdge -> va == nextVert) {
nextVert = nextBorderEdge -> vb;
} else {
nextVert = nextBorderEdge -> va;
}
} while (nextVert != selectedVertex);
} else if (!secondBorderSelectionPoint) {
// We need to test if this second point in the border
// of the first selecte point.
vector<Vertex*>::iterator vIt;
for(vIt = allBorderPoints.begin();
vIt < allBorderPoints.end(); vIt++) {
if((*vIt) == selectedVertex) {
if((*vIt) == firstBorderSelectionPoint) {
cout<<"Unselecting the first point on border."<<endl;
firstBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
//(*vIt) -> selected = false;
}
break;
}
}
if(!allBorderPoints.empty()) {
if(vIt == allBorderPoints.end()) {
cout<<"Your choice of the two points are not on the"
<<" same border. Selection ABORT."<<endl;
firstBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
} else {
cout<<"Selecting the second point on border."<<endl;
secondBorderSelectionPoint = selectedVertex;
selectedVertex -> selected = true;
selectedVertices.push_back(selectedVertex);
}
}
} else if(!vertToSelect.empty()) {
cout<<"Unselecting all points on partial border."<<endl;
vector<Vertex*>::iterator vIt;
for(vIt = vertToSelect.begin(); vIt < vertToSelect.end(); vIt++) {
(*vIt) -> selected = false;
}
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
vertToSelect.clear();
selectedVertices.clear();
} else {
vector<Vertex*>::iterator vIt;
bool hasSeenSecondPoint = false;
for(vIt = allBorderPoints.begin(); vIt < allBorderPoints.end(); vIt++) {
if((*vIt) == selectedVertex) {
if((*vIt) == firstBorderSelectionPoint
|| (*vIt) == secondBorderSelectionPoint) {
cout<<"Unselecting points on border."<<endl;
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
}
break;
} else if((*vIt) == secondBorderSelectionPoint) {
hasSeenSecondPoint = true;
}
}
if(!allBorderPoints.empty()) {
if(vIt == allBorderPoints.end()) {
cout<<"Your choice of the third points is not on"
<<"the same border. Selection ABORT."<<endl;
firstBorderSelectionPoint -> selected = false;
secondBorderSelectionPoint -> selected = false;
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
selectedVertices.clear();
} else {
cout<<"Selecting this half border on this side."<<endl;
vector<Vertex*>::iterator vSelIt;
if(!hasSeenSecondPoint) {
for(vSelIt = allBorderPoints.begin();
vSelIt < allBorderPoints.end(); vSelIt++) {
vertToSelect.push_back(*vSelIt);
if((*vSelIt) == secondBorderSelectionPoint) {
break;
}
}
} else {
vertToSelect.push_back(firstBorderSelectionPoint);
for(vSelIt = allBorderPoints.end() - 1;
vSelIt >= allBorderPoints.begin(); vSelIt--) {
vertToSelect.push_back(*vSelIt);
if((*vSelIt) == secondBorderSelectionPoint) {
break;
}
}
}
selectedVertices.clear();
for(vSelIt = vertToSelect.begin();
vSelIt < vertToSelect.end(); vSelIt++) {
(*vSelIt) -> selected = true;
selectedVertices.push_back(*vSelIt);
}
cout<<"You have selected "<<selectedVertices.size()
<<" points on this border.\n";
}
}
}
}
}
}
void MySelection::clearSelection() {
vector<Vertex*>::iterator vIt;
for(vIt = selectedVertices.begin(); vIt < selectedVertices.end(); vIt++)
{
(*vIt) -> selected = false;
}
unordered_map<Mesh*, vector<Face*> >::iterator mfIt;
for(mfIt = selectedFaces.begin(); mfIt != selectedFaces.end(); mfIt++) {
vector<Face*> faces = mfIt -> second;
for(Face * face : faces) {
face -> selected = false;
}
}
selectedVertices.clear();
selectedFaces.clear();
firstBorderSelectionPoint = NULL;
secondBorderSelectionPoint = NULL;
allBorderPoints.clear();
vertToSelect.clear();
}
void MySelection::addSelectedToMesh(Mesh &mesh)
{
vector<Vertex*> vertices;
vertices.clear();
vector<Vertex*>::iterator vIt;
Vertex * foundVertex;
for(vIt = selectedVertices.begin();
vIt < selectedVertices.end(); vIt++)
{
foundVertex = NULL;
for(Vertex * v : mesh.vertList)
{
if((v -> source_vertex) == (*vIt))
{
foundVertex = v;
break;
}
}
if(foundVertex != NULL)
{
/* Reset the next pointer for the boundary
* edge of the found vertex here. */
mesh.setBoundaryEdgeToNull(foundVertex);
vertices.push_back(foundVertex);
}
else
{
Vertex * newVertex = new Vertex;
newVertex -> source_vertex = *vIt;
newVertex -> position = (*vIt) -> position;
newVertex -> ID = mesh.vertList.size();
newVertex -> name = (*vIt) -> name;
mesh.addVertex(newVertex);
vertices.push_back(newVertex);
}
}
mesh.addPolygonFace(vertices);
/* The build Boundary function may
* have destroyed our data structure.
* We need to reset the next pointers of
* the boundary edges of the newly added vertex*/
mesh.buildBoundary();
mesh.computeNormals();
clearSelection();
}
void MySelection::deleteSelectedFaces(vector<string> & deletedFaces)
{
unordered_map<Mesh*, vector<Face*> >::iterator mfIt;
for(mfIt = selectedFaces.begin(); mfIt != selectedFaces.end(); mfIt++)
{
Mesh * mesh = mfIt -> first;
vector<Face*> faces = mfIt -> second;
for(Face * face : faces)
{
if(mesh -> type != 99)
{
deletedFaces.push_back(face -> name);
}
face -> selected = false;
mesh -> deleteFace(face);
}
mesh -> buildBoundary();
mesh -> computeNormals();
if(mesh -> isConsolidateMesh)
{
mesh -> updateVertListAfterDeletion();
}
}
clearSelection();
}
PolyLine MySelection::addSelectedToPolyline(bool isLoop)
{
PolyLine newBorder;
if(selectedVertices.size() < 2) {
cout<<"A Line have size greater than 1."<<endl;
clearSelection();
return newBorder;
}
vector<Vertex*>::iterator vIt;
for(vIt = selectedVertices.begin();
vIt < selectedVertices.end(); vIt ++) {
newBorder.vertices.push_back(*vIt);
}
newBorder.isLoop = isLoop;
clearSelection();
return newBorder;
}
<file_sep>#ifndef SLIDERPANEL_H
#define SLIDERPANEL_H
#include <QWidget>
#include <iostream>
#include <QVBoxLayout>
#include "myslider.h"
#include "parameter.h"
#include "parameterbank.h"
#include "nomeglwidget.h"
class SliderPanel : public QWidget
{
Q_OBJECT
public:
SliderPanel();
SliderPanel(ParameterBank *bank, SlideGLWidget * canvas);
ParameterBank *bank;
};
#endif // SLIDERPANEL_H
<file_sep>#include "parameter.h"
#include "mesh.h"
#include "myslider.h"
Parameter::Parameter()
{
this -> name = QString("");
influenceMeshes.clear();
influenceVertices.clear();
influenceTransformations.clear();
}
float Parameter::getValue()
{
return value;
}
void Parameter::update()
{
for(Mesh*& m : influenceMeshes)
{
switch(m -> type)
{
case 1:
m -> updateFunnel();
break;
case 2:
m -> updateTunnel();
break;
}
}
for(Transformation*& t : influenceTransformations)
{
t -> update();
}
for(Vertex*& v : influenceVertices)
{
v -> update();
}
}
void Parameter::addInfluenceMesh(Mesh * mesh)
{
influenceMeshes.push_back(mesh);
}
void Parameter::addInfluenceTransformation(Transformation * t)
{
influenceTransformations.push_back(t);
}
void Parameter::addInfluenceVertex(Vertex * vertex)
{
influenceVertices.push_back(vertex);
}
void Parameter::changeParameterValue(float value)
{
this -> value = value;
slider -> slider -> setValue(int((this -> value - this -> start) / this -> stepsize + 0.5 ));
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "stl.h"
vec3 getTriFaceNormal(Vertex * va, Vertex * vb, Vertex * vc){
vec3 pa = va -> position;
vec3 pb = vb -> position;
vec3 pc = vc -> position;
vec3 vNormalb = getNormal3Vertex(pa, pb, pc);
vec3 vNormalc = getNormal3Vertex(pb, pc, pa);
vec3 vNormala = getNormal3Vertex(pc, pa, pb);
return normalize(vNormala + vNormalb + vNormalc);
}
void STL::STLOutput(vector<Mesh> &meshes, string outputSTL){
vector<Mesh>::iterator mIt;
ofstream file(outputSTL);
if (!file.is_open()) {
cout <<"COULD NOT OPEN THE FILE.\n";
} else {
file << "solid\n";
for(mIt = meshes.begin(); mIt < meshes.end(); mIt++) {
Mesh & currMesh = (*mIt);
vector<Face*>::iterator fIt;
for(fIt = currMesh.faceList.begin(); fIt < currMesh.faceList.end(); fIt++) {
Face * currFace = (*fIt);
Edge * firstEdge = currFace -> oneEdge;
Edge * currEdge;
if(firstEdge == NULL) {
cout<<"ERROR: This face does not have a sideEdge."<<endl;
exit(0);
}
Vertex * v0, * v1, * v2;
if(currFace == firstEdge -> fa) {
v0 = firstEdge -> va;
currEdge = firstEdge -> nextVbFa;
} else {
if(firstEdge -> mobius) {
v0 = firstEdge -> va;
currEdge = firstEdge -> nextVbFb;
} else {
v0 = firstEdge -> vb;
currEdge = firstEdge -> nextVaFb;
}
}
vec3 p0 = v0 -> position;
if(currEdge == NULL) {
cout<<"ERROR: This face contains only one edge and can not be drawn."<<endl;
}
do {
Edge * nextEdge;
if(currFace == currEdge -> fa) {
v1 = currEdge -> va;
v2 = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
v1 = currEdge -> va;
v2 = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
v1 = currEdge -> vb;
v2 = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
if(v2 != v0) {
vec3 faceNormal = getTriFaceNormal(v0, v1, v2);
file << " facet normal "<<faceNormal[0]<<" "<<faceNormal[1]<<" "<<faceNormal[2]<<"\n";
file << " outer loop\n";
vec3 p1 = v1 -> position;
vec3 p2 = v2 -> position;
file << " vertex " << p0[0] << " "<< p0[1] << " " << p0[2]<<"\n";
file << " vertex " << p1[0] << " "<< p1[1] << " " << p1[2]<<"\n";
file << " vertex " << p2[0] << " "<< p2[1] << " " << p2[2]<<"\n";
file << " endloop\n";
file << " endfacet\n";
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
}
file << "endsolid\n";
}
}
void STL::STLOutput(Mesh &currMesh, string outputSTL){
vector<Face*>::iterator faceIt;
ofstream file(outputSTL);
if (!file.is_open()) {
cout <<"Error: COULD NOT OPEN THE FILE.\n";
} else {
file << "solid\n";
vector<Face*>::iterator fIt;
for(fIt = currMesh.faceList.begin(); fIt < currMesh.faceList.end(); fIt++) {
Face * currFace = (*fIt);
Edge * firstEdge = currFace -> oneEdge;
Edge * currEdge;
if(firstEdge == NULL) {
cout<<"ERROR: This face does not have a sideEdge."<<endl;
exit(0);
}
Vertex * v0, * v1, * v2;
if(currFace == firstEdge -> fa) {
v0 = firstEdge -> va;
currEdge = firstEdge -> nextVbFa;
} else {
if(firstEdge -> mobius) {
v0 = firstEdge -> va;
currEdge = firstEdge -> nextVbFb;
} else {
v0 = firstEdge -> vb;
currEdge = firstEdge -> nextVaFb;
}
}
vec3 p0 = v0 -> position;
if(currEdge == NULL) {
cout<<"ERROR: This face contains only one edge and can not be drawn."<<endl;
}
do {
Edge * nextEdge;
if(currFace == currEdge -> fa) {
v1 = currEdge -> va;
v2 = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
v1 = currEdge -> va;
v2 = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
v1 = currEdge -> vb;
v2 = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
if(v2 != v0) {
vec3 faceNormal = getTriFaceNormal(v0, v1, v2);
file << " facet normal "<<faceNormal[0]<<" "<<faceNormal[1]<<" "<<faceNormal[2]<<"\n";
file << " outer loop\n";
vec3 p1 = v1 -> position;
vec3 p2 = v2 -> position;
file << " vertex " << p0[0] << " "<< p0[1] << " " << p0[2]<<"\n";
file << " vertex " << p1[0] << " "<< p1[1] << " " << p1[2]<<"\n";
file << " vertex " << p2[0] << " "<< p2[1] << " " << p2[2]<<"\n";
file << " endloop\n";
file << " endfacet\n";
}
currEdge = nextEdge;
} while (currEdge != firstEdge);
}
file << "endsolid\n";
}
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "edge.h"
Edge::Edge() {
va = vb = NULL;
nextVaFa = nextVaFb = nextVbFa = nextVbFb = NULL;
fa = fb = NULL;
edgePoint = NULL;
isSharp = false;
mobius = false;
firstHalf = secondHalf = NULL;
}
Edge::Edge(Vertex * v1, Vertex * v2) {
va = v1;
vb = v2;
nextVaFa = nextVaFb = nextVbFa = nextVbFb = NULL;
fa = fb = NULL;
edgePoint = NULL;
isSharp = false;
mobius = false;
firstHalf = secondHalf = NULL;
}
Edge * Edge::nextEdge(Vertex * v, Face * f) {
if(v == va) {
if(f == fa) {
return nextVaFa;
} else if (f == fb) {
return nextVaFb;
}
} else if(v == vb) {
if(f == fa) {
return nextVbFa;
} else if (f == fb) {
return nextVbFb;
}
}
cout<<"Error: Invalid search of edge at vertex "<<v -> ID<<"."<<endl;
exit(0);
}
void Edge::setNextEdge(Vertex * v, Face * f, Edge * nextEdge) {
if(v == va) {
if(f == fa) {
nextVaFa = nextEdge;
return;
} else if (f == fb) {
nextVaFb = nextEdge;
return;
}
} else if(v == vb) {
if(f == fa) {
nextVbFa = nextEdge;
return;
} else if (f == fb) {
nextVbFb = nextEdge;
return;
}
}
cout<<"Error: Invalid set next edge at vertex "<<v -> ID<<"."<<endl;
exit(0);
}
Vertex * Edge::theOtherVertex(Vertex * v) {
if(v == va) {
return vb;
} else if(v == vb) {
return va;
} else {
cout<<"ERROR: v is not in edge!"<<endl;
//exit(0);
}
}
Face * Edge::theOtherFace(Face * f) {
if(f == fa) {
return fb;
} else if(f == fb) {
return fa;
} else {
cout<<"ERROR: f is not adjacent to this edge"<<endl;
exit(0);
}
}
Edge * Edge::nextEdgeOfFace(Face * f) {
if(f == fa) {
return nextVbFa;
} else if(f == fb) {
if(mobius) {
return nextVbFb;
} else {
return nextVaFb;
}
} else {
cout<<"ERROR: f is not adjacent to this edge"<<endl;
exit(0);
}
}
<file_sep>#include "utils.h"
#include "transformation.h"
#include "mesh.h"
float evaluate_expression(string expr, unordered_map<string, Parameter> *params)
{
//cout<<expr<<endl;
vector<string> tokens;
stack<string> numberStack;
string number = "";
string lastNumber = "";
bool readingFromExpr = false;
string parameterName = "";
for(char& m : expr)
{
if(!readingFromExpr && ((m >= '0' && m <= '9') || m == '.'))
{
number.push_back(m);
}
else if(m == '$')
{
readingFromExpr = true;
}
else if(readingFromExpr && !(m == ' ' || m == '(' || m ==')'
|| isOperator(m)))
{
parameterName.push_back(m);
}
else
{
if(number != "")
{
tokens.push_back(number);
lastNumber = number;
number = "";
}
else if(parameterName != "")
{
string value = to_string(getParameterValue(parameterName, params));
tokens.push_back(value);
lastNumber = value;
parameterName = "";
readingFromExpr = false;
}
if(isOperator(m))
{
if(lastNumber == "")
{
tokens.push_back("0");
}
while(numberStack.size() > 0)
{
string last = numberStack.top();
if(getPriority(last[0]) >= getPriority(m))
{
tokens.push_back(last);
numberStack.pop();
}
else
{
break;
}
}
string newString = "";
newString.push_back(m);
numberStack.push(newString);
}
else if(m == '(')
{
string newString = "";
newString.push_back(m);
numberStack.push(newString);
lastNumber = "";
}
else if(m == ')')
{
while(numberStack.size() > 0) {
string last = numberStack.top();
numberStack.pop();
if(last != "(")
{
tokens.push_back(last);
}
else
{
break;
}
}
}
}
}
if(number != "")
{
tokens.push_back(number);
} else if(parameterName != "")
{
string value = to_string(getParameterValue(parameterName, params));
tokens.push_back(value);
lastNumber = value;
}
while(!numberStack.empty())
{
tokens.push_back(numberStack.top());
numberStack.pop();
}
stack<float> operands;
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
string token = (*tIt);
if(token.size() == 1 && isOperator(token[0]))
{
float y = operands.top();
operands.pop();
float x = operands.top();
operands.pop();
operands.push(getVal(x, y, token[0]));
}
else
{
operands.push(stof(token));
}
}
if(operands.empty())
{
return 0.0f;
}
return operands.top();
}
float evaluate_mesh_expression(string expr, unordered_map<string, Parameter> *params, Mesh * mesh)
{
//cout<<expr<<endl;
vector<string> tokens;
stack<string> numberStack;
string number = "";
string lastNumber = "";
bool readingFromExpr = false;
string parameterName = "";
for(char& m : expr)
{
if(!readingFromExpr && ((m >= '0' && m <= '9') || m == '.'))
{
number.push_back(m);
} else if(m == '$')
{
readingFromExpr = true;
}
else if(readingFromExpr && !(m == ' ' || m == '(' || m ==')' || isOperator(m)))
{
parameterName.push_back(m);
}
else
{
if(number != "")
{
tokens.push_back(number);
lastNumber = number;
number = "";
} else if(parameterName != "")
{
string value = to_string(getMeshParameterValue(parameterName, params, mesh));
tokens.push_back(value);
lastNumber = value;
parameterName = "";
readingFromExpr = false;
}
if(isOperator(m))
{
if(lastNumber == "") {
tokens.push_back("0");
}
while(numberStack.size() > 0)
{
string last = numberStack.top();
if(getPriority(last[0]) >= getPriority(m))
{
tokens.push_back(last);
numberStack.pop();
}
else
{
break;
}
}
string newString = "";
newString.push_back(m);
numberStack.push(newString);
}
else if(m == '(')
{
string newString = "";
newString.push_back(m);
numberStack.push(newString);
lastNumber = "";
}
else if(m == ')')
{
while(numberStack.size() > 0) {
string last = numberStack.top();
numberStack.pop();
if(last != "(")
{
tokens.push_back(last);
}
else
{
break;
}
}
}
}
}
if(number != "")
{
tokens.push_back(number);
} else if(parameterName != "")
{
string value = to_string(getMeshParameterValue(parameterName, params, mesh));
tokens.push_back(value);
lastNumber = value;
}
while(!numberStack.empty())
{
tokens.push_back(numberStack.top());
numberStack.pop();
}
stack<float> operands;
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
string token = (*tIt);
if(token.size() == 1 && isOperator(token[0]))
{
float y = operands.top();
operands.pop();
float x = operands.top();
operands.pop();
operands.push(getVal(x, y, token[0]));
}
else
{
operands.push(stof(token));
}
}
if(operands.empty())
{
return 0.0f;
}
return operands.top();
}
float evaluate_transformation_expression(string expr,
unordered_map<string, Parameter> *params,
Transformation * t)
{
//cout<<expr<<endl;
vector<string> tokens;
stack<string> numberStack;
string number = "";
string lastNumber = "";
bool readingFromExpr = false;
string parameterName = "";
for(char& m : expr)
{
if(!readingFromExpr && ((m >= '0' && m <= '9') || m == '.'))
{
number.push_back(m);
} else if(m == '$')
{
readingFromExpr = true;
}
else if(readingFromExpr && !(m == ' ' || m == '(' || m ==')' || isOperator(m)))
{
parameterName.push_back(m);
}
else
{
if(number != "")
{
tokens.push_back(number);
lastNumber = number;
number = "";
} else if(parameterName != "")
{
string value = to_string(getTransformationParameterValue(parameterName, params, t));
tokens.push_back(value);
lastNumber = value;
parameterName = "";
readingFromExpr = false;
}
if(isOperator(m))
{
if(lastNumber == "") {
tokens.push_back("0");
}
while(numberStack.size() > 0)
{
string last = numberStack.top();
if(getPriority(last[0]) >= getPriority(m))
{
tokens.push_back(last);
numberStack.pop();
}
else
{
break;
}
}
string newString = "";
newString.push_back(m);
numberStack.push(newString);
}
else if(m == '(')
{
string newString = "";
newString.push_back(m);
numberStack.push(newString);
lastNumber = "";
}
else if(m == ')')
{
while(numberStack.size() > 0) {
string last = numberStack.top();
numberStack.pop();
if(last != "(")
{
tokens.push_back(last);
}
else
{
break;
}
}
}
}
}
if(number != "")
{
tokens.push_back(number);
} else if(parameterName != "")
{
string value = to_string(getTransformationParameterValue(parameterName, params, t));
tokens.push_back(value);
lastNumber = value;
}
while(!numberStack.empty())
{
tokens.push_back(numberStack.top());
numberStack.pop();
}
stack<float> operands;
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
string token = (*tIt);
if(token.size() == 1 && isOperator(token[0]))
{
float y = operands.top();
operands.pop();
float x = operands.top();
operands.pop();
operands.push(getVal(x, y, token[0]));
}
else
{
operands.push(stof(token));
}
}
if(operands.empty())
{
return 0.0f;
}
return operands.top();
}
float evaluate_vertex_expression(string expr,
unordered_map<string, Parameter> *params,
Vertex * v)
{
//cout<<expr<<endl;
vector<string> tokens;
stack<string> numberStack;
string number = "";
string lastNumber = "";
bool readingFromExpr = false;
string parameterName = "";
for(char& m : expr)
{
if(!readingFromExpr && ((m >= '0' && m <= '9') || m == '.'))
{
number.push_back(m);
} else if(m == '$')
{
readingFromExpr = true;
}
else if(readingFromExpr && !(m == ' ' || m == '(' || m ==')' || isOperator(m)))
{
parameterName.push_back(m);
}
else
{
if(number != "")
{
tokens.push_back(number);
lastNumber = number;
number = "";
} else if(parameterName != "")
{
string value = to_string(getVertexParameterValue(parameterName, params, v));
tokens.push_back(value);
lastNumber = value;
parameterName = "";
readingFromExpr = false;
}
if(isOperator(m))
{
if(lastNumber == "") {
tokens.push_back("0");
}
while(numberStack.size() > 0)
{
string last = numberStack.top();
if(getPriority(last[0]) >= getPriority(m))
{
tokens.push_back(last);
numberStack.pop();
}
else
{
break;
}
}
string newString = "";
newString.push_back(m);
numberStack.push(newString);
}
else if(m == '(')
{
string newString = "";
newString.push_back(m);
numberStack.push(newString);
lastNumber = "";
}
else if(m == ')')
{
while(numberStack.size() > 0) {
string last = numberStack.top();
numberStack.pop();
if(last != "(")
{
tokens.push_back(last);
}
else
{
break;
}
}
}
}
}
if(number != "")
{
tokens.push_back(number);
} else if(parameterName != "")
{
string value = to_string(getVertexParameterValue(parameterName, params, v));
tokens.push_back(value);
lastNumber = value;
}
while(!numberStack.empty())
{
tokens.push_back(numberStack.top());
numberStack.pop();
}
stack<float> operands;
vector<string>::iterator tIt;
for(tIt = tokens.begin(); tIt < tokens.end(); tIt++)
{
string token = (*tIt);
if(token.size() == 1 && isOperator(token[0]))
{
float y = operands.top();
operands.pop();
float x = operands.top();
operands.pop();
operands.push(getVal(x, y, token[0]));
}
else
{
operands.push(stof(token));
}
}
if(operands.empty())
{
return 0.0f;
}
return operands.top();
}
bool isOperator(char token)
{
return token == '+' || token == '-' || token == '*' || token == '/';
}
float getParameterValue(string name, unordered_map<string, Parameter> *params)
{
unordered_map<string, Parameter>::iterator pIt;
pIt = params -> find(name);
if(pIt == params -> end())
{
std::cout<<"Warning: Parameter " + name + " has not be defined yet.";
return 0.0f;
}
return (pIt -> second).getValue();
}
float getMeshParameterValue(string name, unordered_map<string, Parameter> *params, Mesh *mesh)
{
unordered_map<string, Parameter>::iterator pIt;
pIt = params -> find(name);
if(pIt == params -> end())
{
std::cout<<"Warning: Parameter " + name + " has not be defined yet.";
return 0.0f;
}
mesh -> addParam(&(pIt -> second));
return (pIt -> second).getValue();
}
float getTransformationParameterValue(string name,
unordered_map<string, Parameter> *params,
Transformation *t)
{
unordered_map<string, Parameter>::iterator pIt;
pIt = params -> find(name);
if(pIt == params -> end())
{
std::cout<<"Warning: Parameter " + name + " has not be defined yet.";
return 0.0f;
}
t -> addParam(&(pIt -> second));
return (pIt -> second).getValue();
}
float getVertexParameterValue(string name,
unordered_map<string, Parameter> *params,
Vertex *v)
{
unordered_map<string, Parameter>::iterator pIt;
pIt = params -> find(name);
if(pIt == params -> end())
{
std::cout<<"Warning: Parameter " + name + " has not be defined yet.";
return 0.0f;
}
v -> addParam(&(pIt -> second));
return (pIt -> second).getValue();
}
float getVal(float x, float y, char oper)
{
switch(oper)
{
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
default:
cout<<"Warning: operator is not defined."<<endl;
return 0.0f;
}
}
int getPriority(char oper)
{
switch(oper)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
default:
return 0;
}
}
vec3 getXYZ(string input)
{
//cout<<input<<endl;
string number = "";
int i = 0;
float x;
float y;
float z;
for(char& c : input)
{
if((c >= '0' && c <= '9') || c == '.')
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
x = stof(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
x = stoi(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
}
}
return vec3(x, y, z);
}
float getOneValue(string input)
{
//cout<<input<<endl;
string number = "";
for(char& c : input)
{
if((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+')
{
number.push_back(c);
}
else
{
if(number != "")
{
return stoi(number);
}
}
}
if(number != "")
{
return stof(number);
}
return 0.0f;
}
vec4 getXYZW(string input)
{
cout<<input;
string number = "";
int i = 0;
float x;
float y;
float z;
float w;
for(char& c : input)
{
if((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+')
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
x = stoi(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
case 3:
w = stof(number);
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
x = stoi(number);
break;
case 1:
y = stof(number);
break;
case 2:
z = stof(number);
break;
case 3:
w = stof(number);
}
}
return vec4(x, y, z, w);
}
QColor evaluate_color_expression(string input)
{
float r, b, g;
string number = "";
int i = 0;
for(char& c : input)
{
if(((c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+'))
{
number.push_back(c);
}
else
{
if(number != "")
{
switch(i)
{
case 0:
r = stof(number);
break;
case 1:
g = stof(number);
break;
case 2:
b = stof(number);
break;
}
number = "";
i++;
}
}
}
if(number != "")
{
switch(i)
{
case 0:
r = stof(number);
break;
case 1:
g = stof(number);
break;
case 2:
b = stof(number);
break;
}
number = "";
i++;
}
//cout<<r<<" "<<g<<" "<<b<<endl;
return QColor(255*r, 255*g, 255*b);
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "face.h"
Face::Face(){
oneEdge = NULL;
facePoint = NULL;
selected = false;
id = -1;
name = "";
user_defined_color = false;
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __POLYLINE_H__
#define __POLYLINE_H__
#include <vector>
#include <glm/glm.hpp>
#include "mesh.h"
#include "transformation.h"
using namespace std;
using namespace glm;
class Group;
//////////////////////////////////////////////////////////////////////
// Polyline Class -- A Polyline is a list of vertices
class PolyLine {
public:
vector<Vertex*> vertices;
bool isLoop;
QColor color;
PolyLine();
/**
* @brief drawLine: Draw this polyline in OpenGL
*/
void drawLine(int start_index = 0);
/**
* @brief drawLineWithCubes: Draw this polygon with
* a cube around every vertex.
* @param start_index: the starting index of the name
* buffer.
*/
void drawLineWithCubes(int start_index = 0);
// Return the skewness of points in this polyline.
/**
* @brief skewness: Find the skeness of all points.
* @return the skewness of points in this polyline.
*/
vector<float> skewness();
/**
* @brief clear: clear this Polyline.
*/
void clear();
/**
* @brief isEmpty: Find if this line is empty.
* @return indicator of this polyline is empty.
*/
/**
* @brief makeCopy: Make a copy of this PolyLine
* @return the copied polyline
*/
PolyLine makeCopy(string copy_polyline_name = "");
/**
* @brief transform: Transform this polyline.
* @param t: The transformation for this polyline.
*/
void transform(Transformation* t);
/* Check if this polyline is empty.*/
bool isEmpty();
/* Set the color of this mesh. */
void setColor(QColor color);
/* Indicator of whether user sets the color of this mesh.*/
bool user_set_color;
/* The transformations to go up one level. */
vector<Transformation> transformations_up;
/* Set the transformation of this polyline. */
void addTransformation(Transformation new_transform);
/* Reset the transformations to this polyline of going up one level. */
void setTransformation(vector<Transformation>);
/* Add a vertex to the current polyline. */
void addVertex(Vertex *v);
/* parent group */
Group *parent;
/* The name of this polyline. */
string name;
/* Make a copy of this polyline in order for futrue transformation. */
PolyLine makeCopyForTransform();
/* The pointer to the polyline it copied from.*/
PolyLine *before_transform_polyline;
void updateCopyForTransform();
/* A helper functoin for drawLineWithCubes.*/
void drawCubeAroundVertex(Vertex *v, float size);
/* specify the sizes of the cubes to draw in the scene. */
vector<float> cubeSizes;
/* A helper function for drawLineWithCubes.*/
void updateCubeSizes();
/* Draw the selected vertices. */
void drawVertices();
/* Find a vertex in this polyline given its name. */
Vertex * findVertexInThisPolyline(string name);
};
#endif // __POLYLINE_H__
<file_sep>#ifndef PARAMETERBANK_H
#define PARAMETERBANK_H
#include <vector>
#include "parameter.h"
class ParameterBank
{
public:
ParameterBank();
vector<Parameter*> parameters;
void addParameter(Parameter* param);
void setName(QString name);
QString name;
};
#endif // PARAMETERBANK_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, NOME project.
* Advised by Prof. <NAME>.
*/
#ifndef CONTROLPANEL_H
#define CONTROLPANEL_H
#include <QWidget>
#include <iostream>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSlider>
#include <QGroupBox>
#include <QRadioButton>
#include <QPushButton>
#include <QComboBox>
#include <QColorDialog>
#include <QLineEdit>
#include <QStatusBar>
#include <QCheckBox>
#include "nomeglwidget.h"
class ControlPanel : public QWidget
{
Q_OBJECT
public:
ControlPanel();
/* @param canvas, the canvas that this panel control.*/
ControlPanel(SlideGLWidget * canvas);
/* Set up the layout and widgets.*/
void setupLayout();
/* Build the connections. */
void buildConnection();
/* The selection mode of current program.
* 1: vertex selection.
* 2: whole border secletion.
* 3: partial border selection.
*/
int selectionMode;
/* The subdivision level.*/
int subdivLevel;
/* Offset value. */
float offsetValue;
private:
SlideGLWidget *canvas;
/* Widgets and Layout in this Control Panel.*/
QVBoxLayout *mainLayout;
QVBoxLayout *viewLayout;
QGroupBox *modeGroupBox;
QVBoxLayout *modeLayout;
QHBoxLayout *modeSelectLayout;
QHBoxLayout *selectionLayout;
QHBoxLayout *editLayout;
QRadioButton *vertexModeButton;
QRadioButton *faceModeButton;
QRadioButton *borderModeButton;
QPushButton *addFaceButton;
QPushButton *deleteFaceButton;
QPushButton *addBorderButton;
QPushButton *zipButton;
QCheckBox *autoCorrectCheck;
QCheckBox *wholeBorderCheck;
QHBoxLayout *zipOptionsLayout;
QLineEdit *trianglePaneltyEdit;
QHBoxLayout *addOrClearLayout;
//QPushButton *addTempToMasterButton;
QPushButton *clearSelectionButton;
QVBoxLayout *subdivLayout;
QVBoxLayout *offsetLayout;
QVBoxLayout *colorLayout;
QComboBox *viewContent;
QPushButton *resetViewButton;
QPushButton *consolidateButton;
QPushButton *mergeButton;
QHBoxLayout *subdivLevelLayout;
QLabel *currentLevelLabel;
QSlider *subdivLevelSlider;
QHBoxLayout *offsetMinMaxLayout;
QHBoxLayout *offsetValueLayout;
QSlider *offsetValueSlider;
QLabel *currentOffsetValueLabel;
QHBoxLayout *foreColorLayout;
QHBoxLayout *backColorLayout;
QPushButton *foreColorButton;
QWidget *foreColorBox;
QPushButton *backColorButton;
QWidget *backColorBox;
float minOffset;
float maxOffset;
int offsetStep;
QLineEdit *minOffsetBox;
QLineEdit *maxOffsetBox;
QLineEdit *offsetStepBox;
QStatusBar *statusBar;
public slots:
void test(QString test);
void test(bool);
void viewContentReset();
void viewContentSetToSubdiv(int level);
void viewContentSetToSubdivOffset();
void resetMinOffset(QString minOffset);
void resetMaxOffset(QString maxOffset);
void resetOffsetStep(QString offsetStep);
void offSetSliderMoved();
void resetForeColor(bool);
void resetBackColor(bool);
void vertexModeChecked(bool);
void borderModeChecked(bool);
void faceModeChecked(bool);
void pushMerge(bool);
signals:
void makeOffsetMesh(float);
};
#endif // CONTROLPANEL_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, NOME project.
* Advised by Prof. <NAME>.
*/
#ifndef __EDGE_H__
#define __EDGE_H__
#include <glm/glm.hpp>
#include <iostream>
#include "vertex.h"
using namespace glm;
using namespace std;
class Vertex;
class Face;
//////////////////////////////////////////////////////////////////////
// Edge Class -- Edge connects Vertex A and Vertex B.
//
class Edge{
public:
// Pointer to Vertex A of this edge.
Vertex * va;
// Pointer to Vertex B of this edge.
Vertex * vb;
// Pointer to Face A of this edge.
Face * fa;
// Pointer to Face B of this edge.
Face * fb;
// Next edge on the side of Va and Fa.
Edge * nextVaFa;
// Next edge on the side of Va and Fb.
Edge * nextVaFb;
// Next edge on the side of Vb and Fa.
Edge * nextVbFa;
// Next edge on the side of Vb and Fb.
Edge * nextVbFb;
// A pointer to the edge point after makeEdgePoints in subdivision.
Vertex * edgePoint;
// A pointer to the first half edge in subdivision.
Edge * firstHalf;
// A pointer to the second half edge in subdivision.
Edge * secondHalf;
// A flag of mobius. If two faces are with same orientation, false. Otherwise, true.
bool mobius;
// True if this edge is sharp in subdivision.
bool isSharp;
// Constructor.
Edge();
// Constructor with start and end vertex.
// @param va, vb: pointers to the va and vb of this edge.
Edge(Vertex * va, Vertex * vb);
// Find the corresponding next edge given a vertex and face of this edge.
// Return an error if the vertex or face is not adjacent to this edge.
Edge * nextEdge(Vertex * v, Face * f);
// Set the corresponding next edge with a vertex and face of this edge.
// Return an error if the vertex or face is not adjacent to this edge.
void setNextEdge(Vertex * v, Face * f, Edge * nextEdge);
// Find the other point of this edge
// @param v, the known vertex
Vertex * theOtherVertex(Vertex * v);
// Find the other face of this edge
// @param f, the known face
Face * theOtherFace(Face * f);
// The next edge in a face traversal of f.
Edge * nextEdgeOfFace(Face * f);
};
#endif // __EDGE_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "mainwindow.h"
#include "nomeglwidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//SlideGLWidget s;
//s.show();
MainWindow window;
window.show();
return a.exec();
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __ZIPPER_H__
#define __ZIPPER_H__
#include <vector>
#include <math.h>
#include "glm/glm.hpp"
#include "mesh.h"
#include "polyline.h"
using namespace std;
using namespace glm;
//////////////////////////////////////////////////////////////////////
// Polyline Class -- A Polyline is a list of vertices
class Zipper
{
public:
Zipper();
/**
* @brief zip: Greedy zippering two polylines. It starts from both sides
* of the polyline and will greedily minimize the distance between vertices
* from the two polylines.
* @param b1: the first border polyline.
* @param b2: the second border polyline.
* @param trianglePenalty: the weight to penalize forming triangles.
* @return Mesh build by zipping this two polylines.
*/
Mesh zip(PolyLine * b1, PolyLine * b2, float trianglePenalty = 1.3);
/**
* @brief zip_skewness: zippering two polylines. It starts from both sides
* of the polyline and will greedily by balancing the skewness between vertices
* from the two polylines.
* @param b1: the first border polyline.
* @param b2: the second border polyline.
* @param trianglePenalty: the weight to penalize forming triangles.
* @return Mesh build by zipping this two polylines.
*/
Mesh zip_skewness(PolyLine * b1, PolyLine * b2, float penalty = 1.3);
void zip(PolyLine * b1, PolyLine * b2, Mesh &mesh, float trianglePenalty = 1.3);
};
#endif //__ZIPPER_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "polyline.h"
PolyLine::PolyLine()
{
isLoop = false;
vertices.clear();
user_set_color = false;
transformations_up.clear();
}
void PolyLine::drawLine(int start_index)
{
if(!isLoop)
{
glBegin(GL_LINE_STRIP);
}
else
{
glBegin(GL_LINE_LOOP);
}
vector<Vertex*>::iterator vIt;
for(vIt = vertices.begin(); vIt < vertices.end(); vIt ++)
{
vec3 position = (*vIt) -> position;
glVertex3f(position[0], position[1], position[2]);
}
glEnd();
}
void PolyLine::clear()
{
vertices.clear();
transformations_up.clear();
}
bool PolyLine::isEmpty()
{
return vertices.size() == 0;
}
vector<float> PolyLine::skewness()
{
if(vertices.size() < 2) {
cout<<"ERROR: Can not find the skewness of a polyline with one vertex."<<endl;
exit(0);
}
vector<float> distances;
distances.push_back(0);
vector<Vertex*>::iterator vIt;
float sum = 0;
for(vIt = vertices.begin(); vIt < vertices.end() - 1; vIt++) {
float currDistance = distance((*(vIt + 1)) -> position, (*vIt) -> position);
sum += currDistance;
distances.push_back(sum);
}
if(isLoop) {
sum += distance(vertices[0] -> position, (*vIt) -> position);
}
vector<float>::iterator dIt;
for(dIt = distances.begin(); dIt < distances.end(); dIt++) {
(*dIt) /= sum;
cout<<(*dIt)<<endl;
}
return distances;
}
void PolyLine::setColor(QColor color)
{
this -> color = color;
}
void PolyLine::addTransformation(Transformation new_transform)
{
transformations_up.push_back(new_transform);
}
void PolyLine::setTransformation(vector<Transformation> new_transform)
{
transformations_up = new_transform;
}
void PolyLine::addVertex(Vertex *v)
{
vertices.push_back(v);
}
void PolyLine::transform(Transformation *t)
{
mat4 matrix = t -> getMatrix();
vector<Vertex*>::iterator vIt;
for(vIt = vertices.begin(); vIt < vertices.end(); vIt++) {
(*vIt) -> position = vec3(matrix * vec4((*vIt) -> position, 1));
}
}
PolyLine PolyLine::makeCopy(string copy_polyline_name)
{
PolyLine newPolyline;
newPolyline.clear();
if(copy_polyline_name == "")
{
newPolyline.name = this -> name;
}
else
{
newPolyline.name = copy_polyline_name;
}
newPolyline.isLoop = this->isLoop;
newPolyline.color = color;
for(Vertex*& v: vertices)
{
Vertex* newVertex = new Vertex;
newVertex -> ID = v -> ID;
newVertex -> name = v -> name;
newVertex -> position = v -> position;
newVertex -> isParametric = v -> isParametric;
if(v -> isParametric)
{
newVertex -> x_expr = v -> x_expr;
newVertex -> y_expr = v -> y_expr;
newVertex -> z_expr = v -> z_expr;
newVertex -> influencingParams = v -> influencingParams;
newVertex -> params = v -> params;
}
newPolyline.addVertex(newVertex);
}
return newPolyline;
}
PolyLine PolyLine::makeCopyForTransform()
{
PolyLine newPolyline;
newPolyline.before_transform_polyline = this;
newPolyline.name = this -> name;
newPolyline.isLoop = this->isLoop;
newPolyline.color = color;
for(Vertex*& v: vertices)
{
Vertex* newVertex = new Vertex;
newVertex -> ID = v -> ID;
newVertex -> name = v -> name;
newVertex -> position = v -> position;
newVertex -> before_transform_vertex = v;
newPolyline.addVertex(newVertex);
}
return newPolyline;
}
void PolyLine::updateCopyForTransform()
{
transformations_up = before_transform_polyline -> transformations_up;
for(Vertex*& v: vertices)
{
v -> position = v -> before_transform_vertex -> position;
}
}
void PolyLine::drawLineWithCubes(int start_index)
{
int counter = 0;
updateCubeSizes();
for(Vertex*& v : vertices)
{
glLoadName(start_index + counter);
drawCubeAroundVertex(v, 0.1 * cubeSizes[counter]);
counter++;
}
drawLine(start_index);
}
void PolyLine::drawCubeAroundVertex(Vertex *v, float size)
{
vec3 p = v -> position;
float x = p[0];
float y = p[1];
float z = p[2];
glBegin(GL_QUADS);
glNormal3f(0, 0, 1);
glVertex3f(x + size / 2, y + size / 2, z + size / 2);
glVertex3f(x - size / 2, y + size / 2, z + size / 2);
glVertex3f(x - size / 2, y - size / 2, z + size / 2);
glVertex3f(x + size / 2, y - size / 2, z + size / 2);
glEnd();
glBegin(GL_QUADS);
glNormal3f(1, 0, 0);
glVertex3f(x + size / 2, y + size / 2, z + size / 2);
glVertex3f(x + size / 2, y - size / 2, z + size / 2);
glVertex3f(x + size / 2, y - size / 2, z - size / 2);
glVertex3f(x + size / 2, y + size / 2, z - size / 2);
glEnd();
glBegin(GL_QUADS);
glNormal3f(0, 0, -1);
glVertex3f(x + size / 2, y + size / 2, z - size / 2);
glVertex3f(x + size / 2, y - size / 2, z - size / 2);
glVertex3f(x - size / 2, y - size / 2, z - size / 2);
glVertex3f(x - size / 2, y + size / 2, z - size / 2);
glEnd();
glBegin(GL_QUADS);
glNormal3f(-1, 0, 0);
glVertex3f(x - size / 2, y + size / 2, z - size / 2);
glVertex3f(x - size / 2, y - size / 2, z - size / 2);
glVertex3f(x - size / 2, y - size / 2, z + size / 2);
glVertex3f(x - size / 2, y + size / 2, z + size / 2);
glEnd();
glBegin(GL_QUADS);
glNormal3f(0, 1, 0);
glVertex3f(x + size / 2, y + size / 2, z - size / 2);
glVertex3f(x + size / 2, y + size / 2, z + size / 2);
glVertex3f(x - size / 2, y + size / 2, z + size / 2);
glVertex3f(x - size / 2, y + size / 2, z - size / 2);
glEnd();
glBegin(GL_QUADS);
glNormal3f(0, -1, 0);
glVertex3f(x + size / 2, y - size / 2, z + size / 2);
glVertex3f(x + size / 2, y - size / 2, z - size / 2);
glVertex3f(x - size / 2, y - size / 2, z - size / 2);
glVertex3f(x - size / 2, y - size / 2, z + size / 2);
glEnd();
}
void PolyLine::updateCubeSizes()
{
cubeSizes.clear();
vector<Vertex*>::iterator vIt;
vector<float> distances;
for(vIt = vertices.begin(); vIt < vertices.end() - 1; vIt++)
{
distances.push_back(glm::distance((*vIt) -> position, (*(vIt + 1)) -> position));
}
if(isLoop)
{
distances.push_back(glm::distance((*vIt) -> position, vertices[0] -> position));
for(size_t i = 0; i < distances.size(); i++)
{
if(i == 0)
{
cubeSizes.push_back((distances[0] + *(distances.end() - 1)) / 2);
}
else
{
cubeSizes.push_back((distances[i] + distances[i - 1]) / 2);
}
}
}
else
{
for(size_t i = 0; i <= distances.size(); i++)
{
if(i == 0)
{
cubeSizes.push_back(distances[0]);
}
else if(i == distances.size())
{
cubeSizes.push_back(distances[distances.size() - 1]);
}
else
{
cubeSizes.push_back((distances[i - 1] + distances[i]) / 2);
}
}
}
}
void PolyLine::drawVertices()
{
glPointSize(10);
glBegin(GL_POINTS);
for(Vertex*& v : vertices)
{
if(v -> selected)
{
vec3 p = v -> position;
glNormal3f(p[0] * 100, p[1] * 100, p[2] * 100);
glVertex3f(p[0], p[1], p[2]);
}
}
glEnd();
}
Vertex * PolyLine::findVertexInThisPolyline(string name)
{
for(Vertex*& v: vertices)
{
if(v->name == name)
{
return v;
}
}
return NULL;
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, NOME project.
* Advised by Prof. <NAME>.
*/
#ifndef __FACE_H__
#define __FACE_H__
#include <glm/glm.hpp>
#include <vector>
#include "edge.h"
#include "vertex.h"
#include "mesh.h"
#include <QColor>
using namespace glm;
using namespace std;
/**
* @brief The Face class. The face class build for winged-
* edge data structure. A face is constructed by a seqence of
* vertices/edges.
*/
class Face
{
public:
Face();
/* The face normal.*/
vec3 normal;
/* Pointer to one edge in this face.*/
Edge *oneEdge;
/* Pointer to the face point in subdivision. */
Vertex *facePoint;
/* Indicator of whether this face is selected.*/
bool selected;
/* FaceID, is the index from the global face list.*/
int id;
/* The name of this face.*/
string name;
/* The color of this face. */
QColor color;
/* Indicate if this face has user defined color. */
bool user_defined_color;
};
#endif // __FACE_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __MERGE_H__
#define __MERGE_H__
#include <vector>
#include <unordered_map>
#include <set>
#include <queue>
#include "mesh.h"
using namespace std;
using namespace glm;
//////////////////////////////////////////////////////////////////////
// Merge Class -- A merge class contains fuctions to merge meshes.
// Return true if two vertices are very close to each other.
bool vertexMatch(Vertex * v1, Vertex * v2);
// Merge any possible boundary edges that are close for two meshes.
// @param mesh1, mesh2. The two meshes to be merged.
// Return a new mesh that contains the merged mesh.
Mesh merge(Mesh & mesh1, Mesh & mesh2);
// Merge any possible boundary edges that are close for two meshes.
// @param mesh1, mesh2. The pointers to two meshes to be merged.
// Return a new mesh that contains the merged mesh.
Mesh merge(Mesh * mesh1, Mesh * mesh2);
// Merge any possible boundary edges that are close for multiple meshes.
// @param meshes. The list of meshes to be merged.
// All facets and vertices of mesh2 will be added to mesh1.
// Return a new mesh that contains the merged mesh.
Mesh merge(vector<Mesh> &meshes);
// Merge any possible boundary edges that are close for multiple meshes.
// @param meshes. The pointers to list of meshes to be merged.
// All facets and vertices of mesh2 will be added to mesh1.
// Return a new mesh that contains the merged mesh.
Mesh merge(vector<Mesh*> &meshes);
#endif // __MESH_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "nomeglwidget.h"
SlideGLWidget::SlideGLWidget(QWidget *parent) :
QGLWidget(parent)
{
generalSetup();
makeDefaultMesh();
updateGlobalIndexList();
}
SlideGLWidget::SlideGLWidget(string name, QWidget *parent) :
QGLWidget(parent)
{
generalSetup();
makeSIFMesh(name);
updateGlobalIndexList();
}
SlideGLWidget::SlideGLWidget(Group &group, QWidget *parent) :
QGLWidget(parent)
{
generalSetup();
hierarchical_scene = &group;
makeSLFMesh();
updateGlobalIndexList();
}
void SlideGLWidget::generalSetup()
{
startTimer(0);
cameraDistance = 4;
last_mx = last_my = cur_mx = cur_my = 0;
arcball_on = false;
wireframe = false;
backface = true;
smoothshading = false;
selection_mode = 1;
object2world = mat4(1);
foreColor = QColor(255,0,0);
backColor = QColor(0,0,0);
tempColor = QColor(255, 255, 0);
whole_border = true;
errorMsg = new QMessageBox();
resize(600, 480);
viewer_mode = 0;
work_phase = 0;
temp_mesh.color = Qt::yellow;
temp_mesh.clear();
temp_mesh.type = 99;
consolidate_mesh.color = QColor(255, 69, 0);
consolidate_mesh.clear();
consolidate_mesh.isConsolidateMesh = true;
consolidate_mesh.type = 99;
group_from_consolidate_mesh = NULL;
trianglePanelty = 1.3;
}
void SlideGLWidget::makeDefaultMesh()
{
makeCube(master_mesh,0.5,0.5,0.5);
master_mesh.computeNormals();
master_mesh.color = foreColor;
global_mesh_list.push_back(&master_mesh);
global_mesh_list.push_back(&consolidate_mesh);
global_mesh_list.push_back(&temp_mesh);
}
void SlideGLWidget::makeSIFMesh(string name)
{
/* Figure out the QuadSIF or SIF later.*/
makeWithSIF(master_mesh,name);
//makeWithQuadSIF(master_mesh,name);
master_mesh.computeNormals();
master_mesh.color = foreColor;
global_mesh_list.push_back(&master_mesh);
global_mesh_list.push_back(&consolidate_mesh);
global_mesh_list.push_back(&temp_mesh);
}
void SlideGLWidget::makeSLFMesh()
{
hierarchical_scene_transformed.clearAndDelete();
hierarchical_scene_transformed = hierarchical_scene->makeCopyForTransform();
transform_meshes_in_scene();
hierarchical_scene_transformed.setColor(foreColor);
hierarchical_scene_transformed.assignColor();
hierarchical_scene_transformed.updateGroupElementName();
}
void SlideGLWidget::transform_meshes_in_scene()
{
hierarchical_scene_transformed.updateCopyForTransform();
global_mesh_list = hierarchical_scene_transformed.flattenedMeshes();
global_polyline_list = hierarchical_scene_transformed.flattenedPolylines();
global_mesh_list.push_back(&consolidate_mesh);
global_mesh_list.push_back(&temp_mesh);
}
void SlideGLWidget::mergeAll()
{
work_phase = glm::max(work_phase, 1);
global_mesh_list.pop_back();
merged_mesh.clearAndDelete();
merged_mesh = merge(global_mesh_list);
global_mesh_list.push_back(&temp_mesh);
merged_mesh.color = foreColor;
merged_mesh.computeNormals();
}
void SlideGLWidget::mergeCalled(bool)
{
viewer_mode = 1;
mergeAll();
repaint();
}
void SlideGLWidget::saveMesh(string name)
{
// Figure out the QuadSIF or SIF later/
STL *stl = new STL;
if(!offset_mesh.isEmpty()) {
stl -> STLOutput(offset_mesh, name);
} else {
emit feedback_status_bar(tr("Offset is empty, can't save file!"),0);
}
}
vec3 SlideGLWidget::get_arcball_vector(int x, int y)
{
vec3 p = vec3(1.0 * x / this->width() * 2 - 1.0,
1.0 * y / this->height() * 2 - 1.0, 0);
p.y = - p.y;
float op_squared = p.x * p.x + p.y * p.y;
if (op_squared <= 1 * 1) {
p.z = sqrt(1 * 1 - op_squared);
} else {
p = normalize(p); // nearest point
}
return p;
}
void SlideGLWidget::set_to_editing_mode(bool in_editing_mode)
{
hierarchical_scene_transformed.in_editing_mode = in_editing_mode;
for(Mesh*& mesh : global_mesh_list)
{
mesh->in_editing_mode = in_editing_mode;
}
}
void SlideGLWidget::mouse_select(int x, int y)
{
if(viewer_mode != 0) {
return;
}
set_to_editing_mode(true);
GLuint buff[64] = {0};
GLint hits, view[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
glSelectBuffer(64, buff);
glGetIntegerv(GL_VIEWPORT, view);
// Find the 3D points of the current clicked point
glGetDoublev(GL_MODELVIEW_MATRIX, modelview );
glGetDoublev(GL_PROJECTION_MATRIX, projection );
winX = (double) x;
winY = (double) view[3] - (double)y;
glReadPixels( x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );
//cout<<"winX "<<winX<<" "<<"winY "<<winY<<" "<<"winZ "<<winZ<<endl;
gluUnProject( winX, winY, winZ, modelview, projection,
view, &posX, &posY, &posZ);
//cout<<"X: "<<posX<<" Y: "<<posY<<" Z: "<<posZ<<endl;
// Find the face selected.
glRenderMode(GL_SELECT);
//glClearColor(0, 0, 0, 1);
glInitNames();
glPushName(0);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(x, view[3] - y, 1.0, 1.0, view);
gluPerspective(45, (float) this -> width() / this -> height(), 0.1, 100);
glMatrixMode(GL_MODELVIEW);
repaint();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
hits = glRenderMode(GL_RENDER);
//cout<<posX<<" "<<posY<<" "<<posZ<<endl;
//mySelect.list_hits(hits, buff);
if(selection_mode == 0)
{
mySelect.selectFace(global_mesh_list,
global_polyline_list,
global_name_index_list,
global_polyline_name_index_list,
hits, buff, posX, posY, posZ);
}
else if(selection_mode == 1)
{
mySelect.selectVertex(global_mesh_list,
global_polyline_list,
global_name_index_list,
global_polyline_name_index_list,
hits, buff, posX, posY, posZ);
}
else if(selection_mode == 2)
{
mySelect.selectWholeBorder(global_mesh_list,
global_polyline_list,
global_name_index_list,
global_polyline_name_index_list,
hits, buff, posX, posY, posZ);
}
else if(selection_mode == 3)
{
mySelect.selectPartialBorder(global_mesh_list,
global_polyline_list,
global_name_index_list,
global_polyline_name_index_list,
hits, buff, posX, posY, posZ);
}
glMatrixMode(GL_MODELVIEW);
repaint();
}
SlideGLWidget::~SlideGLWidget()
{
}
void SlideGLWidget::initializeGL()
{
//Smooth Shading
glShadeModel(GL_SMOOTH);
// Two sided pr ones side;
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
//glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//glEnable(GL_LIGHT1);
GLfloat light_ambient0[] = { 0.3f, 0.3f, 0.3f, 0.0f };
GLfloat light_diffuse0[] = { 0.6f, 0.6f, 0.6f, 0.0f };
GLfloat light_specular0[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat light_position0[] = { 1, 1, 1, 0.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse0);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular0);
glLightfv(GL_LIGHT0, GL_POSITION, light_position0);
GLfloat light_ambient1[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat light_diffuse1[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat light_specular1[] = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat light_position1[] = { -1, -1, -1, 0.0 };
glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient1);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse1);
glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular1);
glLightfv(GL_LIGHT1, GL_POSITION, light_position1);
transforms[MODE_CAMERA] = lookAt(vec3(0.0, 0.0, 10.0),
vec3(0.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0));
}
void SlideGLWidget::resizeGL(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, (float) w / h, 0.1, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void SlideGLWidget::draw_mesh(int start_index, Mesh *mesh)
{
mesh -> drawMesh(start_index, smoothshading);
}
void SlideGLWidget::draw_polyline(int start_index, PolyLine *polyline)
{
QColor color = polyline -> color;
GLfloat fcolor[] = {1.0f * color.red() / 255,
1.0f * color.green() / 255,
1.0f * color.blue() / 255,
1.0f * color.alpha() /255};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, fcolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, fcolor);
polyline -> drawLineWithCubes(start_index);
}
void SlideGLWidget::draw_scene()
{
vector<PolyLine*>::iterator pIt;
vector<Mesh*>::iterator mIt;
vector<int>::iterator nIt;
for(mIt = global_mesh_list.begin(), nIt = global_name_index_list.begin();
nIt < global_name_index_list.end(); nIt++, mIt++)
{
draw_mesh(*nIt, *mIt);
}
for(pIt = global_polyline_list.begin(), nIt = global_polyline_name_index_list.begin();
pIt != global_polyline_list.end(); nIt++, pIt++)
{
draw_polyline(*nIt, *pIt);
}
GLfloat afcolor[] = {0.0f, 1.0f, 1.0f, 1.0f};
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, afcolor);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, afcolor);
for(mIt = global_mesh_list.begin(); mIt != global_mesh_list.end(); mIt++)
{
Mesh * currentMesh = (*mIt);
currentMesh -> drawVertices();
}
for(pIt = global_polyline_list.begin(); pIt != global_polyline_list.end(); pIt++)
{
PolyLine * currentPolyline = (*pIt);
currentPolyline -> drawVertices();
}
if(!border1.isEmpty() || !border2.isEmpty())
{
glLineWidth(4.0);
border1.drawLine();
if(!border2.isEmpty()) {
border2.drawLine();
}
glLineWidth(1.0);
}
}
void SlideGLWidget::paintGL()
{
glClearColor(1.0f * backColor.red() / 255,
1.0f * backColor.green() / 255,
1.0f * backColor.blue() / 255,
1.0f * backColor.alpha() / 255);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(0, 0, cameraDistance, 0, 0, 0, 0, 1, 0);
glMultMatrixf(&object2world[0][0]);
switch(viewer_mode)
{
/* When we are at editing mode. */
case 0:
draw_scene();
break;
case 1:
if(work_phase > 0)
{
draw_mesh(0, &merged_mesh);
}
break;
case 2:
if(work_phase > 1)
{
draw_mesh(0, &subdiv_mesh);
}
break;
case 3:
if(work_phase > 2)
{
draw_mesh(0, &offset_mesh);
}
break;
}
}
void SlideGLWidget::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() & Qt::LeftButton)
{
arcball_on = true;
last_mx = cur_mx = event -> x();
last_my = cur_my = event -> y();
}
else
{
arcball_on = false;
}
if (event->buttons() & Qt::RightButton)
{
mouse_select(event -> x(), event -> y());
}
}
void SlideGLWidget::mouseMoveEvent(QMouseEvent* event)
{
if(arcball_on)
{
cur_mx = event -> x();
cur_my = event -> y();
}
}
void SlideGLWidget::timerEvent(QTimerEvent *event) {
if(last_mx != cur_mx || last_my != cur_my) {
vec3 va = get_arcball_vector(last_mx, last_my);
vec3 vb = get_arcball_vector( cur_mx, cur_my);
float angle = acos(glm::min(1.0f, dot(va, vb)));
vec3 axis_in_camera_coord = cross(va, vb);
mat3 camera2object = inverse(mat3(transforms[MODE_CAMERA]) * mat3(object2world));
vec3 axis_in_object_coord = camera2object * axis_in_camera_coord;
object2world = rotate(object2world, (float) ROTATION_SPEED * angle, axis_in_object_coord);
last_mx = cur_mx;
last_my = cur_my;
repaint();
}
}
void SlideGLWidget::keyPressEvent(QKeyEvent* event)
{
switch(event->key())
{
case Qt::Key_Escape:
mySelect.clearSelection();
break;
case Qt::Key_W:
wireframe = !wireframe;
if (wireframe)
{
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
}
else
{
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
}
break;
case Qt::Key_X:
backface = !backface;
if (backface)
{
glPolygonMode( GL_BACK, GL_FILL );
}
else
{
glPolygonMode( GL_BACK, GL_LINE );
}
break;
case Qt::Key_I:
zoom_in();
break;
case Qt::Key_O:
zoom_out();
break;
case Qt::Key_S:
if (smoothshading)
{
glShadeModel(GL_FLAT);
}
else
{
glShadeModel(GL_SMOOTH);
}
smoothshading = !smoothshading;
break;
default:
event->ignore();
break;
}
repaint();
}
void SlideGLWidget::subdivide(int level)
{
if(level <= 0) {
subdiv_mesh = merged_mesh.makeCopy();
return;
}
//int cachedLevel = cache_subdivided_meshes.size();
//if(cachedLevel >= level)
//{
// subdiv_mesh = cache_subdivided_meshes[level - 1];
//}
//else
//{
// if(cachedLevel == 0)
// {
// subdiv_mesh = merged_mesh;
// }
// else
// {
// subdiv_mesh = cache_subdivided_meshes[cachedLevel - 1];
// }
// while(cachedLevel <= level)
// {
// subdiv_mesh = subdiv_mesh.makeCopy();
// subdivider = new Subdivision(subdiv_mesh);
// subdiv_mesh = subdivider->ccSubdivision(1);
// subdiv_mesh.computeNormals();
// cache_subdivided_meshes.push_back(subdiv_mesh);
// cachedLevel++;
// }
//}
subdivider = new Subdivision(merged_mesh);
subdiv_mesh.clearAndDelete();
subdiv_mesh = subdivider->ccSubdivision(level);
subdiv_mesh.computeNormals();
subdiv_mesh.color = foreColor;
}
void SlideGLWidget::offset(float value)
{
work_phase = glm::max(work_phase, 3);
if(value == 0)
{
offset_mesh = merged_mesh.makeCopy();
return;
}
if(subdiv_mesh.isEmpty())
{
subdiv_mesh = merged_mesh.makeCopy();
}
offseter = new Offset(subdiv_mesh, value);
offseter -> makeFullOffset();
offset_mesh.clearAndDelete();
offset_mesh = offseter->offsetMesh;
}
void SlideGLWidget::viewContentChanged(int viewer_mode)
{
this -> viewer_mode = viewer_mode;
repaint();
}
void SlideGLWidget::levelChanged(int new_level)
{
work_phase = glm::max(work_phase, 2);
subdiv_level = new_level;
subdivide(new_level);
offset_mesh.clearAndDelete();
subdiv_offset_mesh.clearAndDelete();
viewer_mode = 2;
repaint();
//emit feedback_status_bar(tr("Subdivision Finished. Level: ")
// + QString::number(new_level), 0);
}
void SlideGLWidget::offsetValueChanged(float new_offset_value)
{
viewer_mode = 3;
offset_value = new_offset_value;
offset(new_offset_value);
subdiv_offset_mesh.clearAndDelete();
repaint();
}
void SlideGLWidget::resetViewDirection(bool)
{
object2world = mat4(1);
repaint();
}
void SlideGLWidget::zoom_in()
{
if(cameraDistance > 0.001)
{
cameraDistance *= 0.9;
}
}
void SlideGLWidget::zoom_out()
{
if(cameraDistance < 200)
{
cameraDistance *= 1.1;
}
}
void SlideGLWidget::wheelEvent(QWheelEvent *event)
{
QPoint numDegrees = event->angleDelta() / 8;
int numZoomIn = numDegrees.y() / 15;
if(numZoomIn >= 1) {
for(int i = 0; i < numZoomIn; i++) {
zoom_in();
}
} else if(numZoomIn <= -1) {
for(int i = 0; i < -numZoomIn; i++) {
zoom_out();
}
}
event->accept();
repaint();
}
void SlideGLWidget::setForeColor(QColor color)
{
foreColor = color;
master_mesh.color = foreColor;
merged_mesh.color = foreColor;
subdiv_mesh.color = foreColor;
offset_mesh.color = foreColor;
hierarchical_scene_transformed.setColor(foreColor);
hierarchical_scene_transformed.assignColor();
repaint();
}
void SlideGLWidget::setBackColor(QColor color)
{
backColor = color;
repaint();
}
void SlideGLWidget::vertexModeChecked(bool checked)
{
if(checked)
{
selection_mode = 1;
}
}
void SlideGLWidget::borderModeChecked(bool checked)
{
if(checked)
{
if(whole_border)
{
selection_mode = 2;
}
else
{
selection_mode = 3;
}
}
}
void SlideGLWidget::faceModeChecked(bool checked)
{
if(checked)
{
selection_mode = 0;
}
}
void SlideGLWidget::autoCorrectChecked(bool checked)
{
auto_check = checked;
}
void SlideGLWidget::wholeBorderSelectionChecked(bool checked)
{
whole_border = checked;
if(checked)
{
selection_mode = 2;
} else
{
selection_mode = 3;
}
clearSelection();
}
void SlideGLWidget::addToTempCalled(bool)
{
mySelect.addSelectedToMesh(temp_mesh);
updateGlobalIndexList();
repaint();
}
void SlideGLWidget::zipToTempCalled(bool)
{
if(border1.isEmpty() || border2.isEmpty()) {
emit feedback_status_bar(tr("Please select two borders to zip!"), 0);
return;
}
zipper->zip(&border1, &border2, temp_mesh, 1.3);
//new_temp_mesh.color = temp_mesh.color;
//temp_mesh = merge(temp_mesh, new_temp_mesh);
temp_mesh.computeNormals();
//temp_mesh.color = new_temp_mesh.color;
updateGlobalIndexList();
mySelect.clearSelection();
border1.clear();
border2.clear();
repaint();
}
void SlideGLWidget::consolidateTempMesh(bool)
{
unordered_map<Vertex*, Vertex*> tempToConsolidateMap;
Vertex * foundVertex;
for(Vertex*& v : temp_mesh.vertList)
{
foundVertex = NULL;
for(Vertex *& vc : consolidate_mesh.vertList)
{
if(vc -> source_vertex == v -> source_vertex)
{
foundVertex = vc;
tempToConsolidateMap[v] = vc;
break;
}
}
if(foundVertex == NULL)
{
Vertex * newVertex = new Vertex;
newVertex -> ID = consolidate_mesh.vertList.size();
newVertex -> position = v -> position;
newVertex -> name = v -> name;
if(v -> source_vertex != NULL)
{
newVertex -> source_vertex = v -> source_vertex;
}
tempToConsolidateMap[v] = newVertex;
consolidate_mesh.addVertex(newVertex);
}
}
for(Face*& f : temp_mesh.faceList)
{
Edge * firstEdge = f -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
vector<Vertex*> vertices;
Vertex * tempv;
vertices.clear();
do {
if(f == currEdge -> fa)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
}
else
{
if(currEdge -> mobius)
{
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
}
else
{
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
vertices.push_back(tempToConsolidateMap[tempv]);
currEdge = nextEdge;
} while (currEdge != firstEdge);
consolidate_mesh.addPolygonFace(vertices);
}
consolidate_mesh.buildBoundary();
consolidate_mesh.computeNormals();
clearSelection();
updateGlobalIndexList();
repaint();
}
void SlideGLWidget::addTempToMaster()
{
Mesh newMesh;
vector<Vertex*>::iterator vIt;
for(vIt = master_mesh.vertList.begin();
vIt < master_mesh.vertList.end(); vIt ++)
{
Vertex * vertCopy = new Vertex;
vertCopy -> ID = (*vIt) -> ID;
vertCopy -> position = (*vIt) -> position;
newMesh.addVertex(vertCopy);
}
vector<Face*>::iterator fIt;
for(fIt = master_mesh.faceList.begin();
fIt < master_mesh.faceList.end(); fIt ++)
{
Face * tempFace = *fIt;
Edge * firstEdge = tempFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
vector<Vertex*> vertices;
Vertex * tempv;
vertices.clear();
do {
if(tempFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
vertices.push_back(newMesh.vertList[tempv -> ID]);
currEdge = nextEdge;
} while (currEdge != firstEdge);
newMesh.addPolygonFace(vertices);
}
for(fIt = temp_mesh.faceList.begin();
fIt < temp_mesh.faceList.end(); fIt ++)
{
Face * tempFace = *fIt;
Edge * firstEdge = tempFace -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
vector<Vertex*> vertices;
Vertex * tempv;
vertices.clear();
do {
if(tempFace == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
vertices.push_back(newMesh.vertList[tempv -> ID]);
currEdge = nextEdge;
} while (currEdge != firstEdge);
newMesh.addPolygonFace(vertices);
}
newMesh.color = master_mesh.color;
master_mesh = newMesh;
master_mesh.buildBoundary();
master_mesh.computeNormals();
repaint();
}
void SlideGLWidget::addTempToMasterCalled(bool) {
if(temp_mesh.isEmpty())
{
emit feedback_status_bar(tr("Current temp mesh is empty."), 0);
return;
}
addTempToMaster();
clearSubDivisionAndOffset();
clearSelectionCalled(true);
updateGlobalIndexList();
emit feedback_status_bar(tr("Joining temp mesh into initial mesh"), 0);
repaint();
}
void SlideGLWidget::addBorderCalled(bool)
{
if(border1.isEmpty())
{
border1 = mySelect.addSelectedToPolyline(whole_border);
emit feedback_status_bar(tr("First border added."), 0);
}
else if(border2.isEmpty())
{
border2 = mySelect.addSelectedToPolyline(whole_border);
emit feedback_status_bar(tr("Second border added."), 0);
}
else
{
emit feedback_status_bar(tr("The two borders are added."
"You are ready to zip."), 0);
}
repaint();
}
void SlideGLWidget::clearSubDivisionAndOffset() {
subdiv_mesh.clearAndDelete();
offset_mesh.clearAndDelete();
subdiv_offset_mesh.clearAndDelete();
//cache_subdivided_meshes.clear();
}
void SlideGLWidget::clearSelection()
{
mySelect.clearSelection();
border1.clear();
border2.clear();
temp_mesh.clearAndDelete();
if(temp_mesh.isEmpty() && consolidate_mesh.isEmpty())
{
set_to_editing_mode(false);
}
repaint();
}
void SlideGLWidget::clearSelectionCalled(bool)
{
clearSelection();
}
void SlideGLWidget::updateGlobalIndexList()
{
int count = 0;
vector<Mesh*>::iterator mIt;
vector<PolyLine*>::iterator pIt;
global_name_index_list.clear();
global_polyline_name_index_list.clear();
for(mIt = global_mesh_list.begin(); mIt < global_mesh_list.end(); mIt++)
{
global_name_index_list.push_back(count);
count += (*mIt) -> faceList.size();
}
for(pIt = global_polyline_list.begin(); pIt < global_polyline_list.end(); pIt++)
{
global_polyline_name_index_list.push_back(count);
count += (*pIt) -> vertices.size();
}
}
void SlideGLWidget::resetTrianglePanelty(QString new_value)
{
trianglePanelty = new_value.toFloat();
}
void SlideGLWidget::paramValueChanged(float)
{
if(hierarchical_scene_transformed.in_editing_mode)
{
transform_meshes_in_scene();
}
else
{
makeSLFMesh();
}
updateTempMesh();
updateConsolidateMesh();
updateSavedConsolidatedMesh();
updateGlobalIndexList();
if(work_phase >= 1)
{
mergeAll();
}
if(work_phase >= 2)
{
//cache_subdivided_meshes.clear();
subdivide(subdiv_level);
}
if(work_phase >= 3)
{
offset(offset_value);
}
repaint();
}
void SlideGLWidget::updateSavedConsolidatedMesh()
{
if(group_from_consolidate_mesh != NULL && group_from_consolidate_mesh->myMeshes.size() != 0)
{
for(Mesh& mesh : group_from_consolidate_mesh->myMeshes)
{
for(Vertex*& v: mesh.vertList)
{
v -> position = v -> source_vertex -> position;
}
}
vector<Mesh*> append_list = group_from_consolidate_mesh -> flattenedMeshes();
global_mesh_list.pop_back();
global_mesh_list.insert(global_mesh_list.end(), append_list.begin(), append_list.end());
global_mesh_list.push_back(&temp_mesh);
}
}
void SlideGLWidget::updateFromSavedMesh()
{
consolidate_mesh.computeNormals();
vector<Mesh*> append_list = group_from_consolidate_mesh -> flattenedMeshes();
global_mesh_list.pop_back();
global_mesh_list.insert(global_mesh_list.end(), append_list.begin(), append_list.end());
global_mesh_list.push_back(&temp_mesh);
updateGlobalIndexList();
if(group_from_consolidate_mesh != NULL && group_from_consolidate_mesh->myMeshes.size() > 0)
{
set_to_editing_mode(true);
}
repaint();
}
void SlideGLWidget::deleteFaceCalled(bool)
{
mySelect.deleteSelectedFaces(deletedFaces);
updateGlobalIndexList();
repaint();
}
void SlideGLWidget::updateTempMesh()
{
for(Vertex * v : temp_mesh.vertList)
{
if(v -> source_vertex != NULL)
{
v -> position = v -> source_vertex -> position;
}
}
}
void SlideGLWidget::updateConsolidateMesh()
{
for(Vertex * v : consolidate_mesh.vertList)
{
if(v -> source_vertex != NULL)
{
v -> position = v -> source_vertex -> position;
}
}
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __MAKEMESH_H__
#define __MAKEMESH_H__
#include <regex>
#include <fstream>
#include <glm/glm.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtc/constants.hpp>
#include "mesh.h"
#include "merge.h"
#include "transformation.h"
using namespace glm;
using namespace std;
//////////////////////////////////////////////////////////////////////
// MakeMesh Class -- Create Initial Meshes.
void makeSquare(Mesh &mesh);
Mesh mergeTwoMeshes1();
Mesh mergeTwoMeshes2();
Mesh mergeTwoMeshes3();
Mesh mergeTwoMeshes8();
Mesh mergeTwoMeshes4();
Mesh mergeTwoMeshes7();
Mesh mergeTwoMeshes6();
Mesh mergeTwoMeshes5();
Mesh mirrorTest();
void makePyramid(Mesh &mesh);
void makeCube(Mesh &mesh);
void makeCube(Mesh &mesh, float x, float y, float z);
void makeOpenCube(Mesh &mesh);
void makeRing(Mesh &mesh);
void makeSharpCube(Mesh &mesh);
void makeOctahedron(Mesh &mesh);
void makeSharpOctahedron(Mesh &mesh);
void makeNormalStrip(Mesh &mesh);
void makeMobius(Mesh &mesh);
void makeCircleSweep(Mesh &mesh);
void makeWithSIF(Mesh &mesh, string inputSIF);
void makeWithQuadSIF(Mesh &mesh, string inputSIF);
#endif // __MAKEMESH_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "controlpanel.h"
ControlPanel::ControlPanel()
{
setupLayout();
//buildConnection();
}
ControlPanel::ControlPanel(SlideGLWidget * canvas)
{
setupLayout();
this -> canvas = canvas;
buildConnection();
resize(300, 600);
}
void ControlPanel::buildConnection()
{
/* Build our connections. */
connect(viewContent, SIGNAL(activated(int)), canvas, SLOT(viewContentChanged(int)));
connect(mergeButton, SIGNAL(clicked(bool)), canvas, SLOT(mergeCalled(bool)));
connect(mergeButton, SIGNAL(clicked(bool)), this, SLOT(pushMerge(bool)));
connect(subdivLevelSlider,SIGNAL(valueChanged(int)), canvas, SLOT(levelChanged(int)));
connect(subdivLevelSlider, SIGNAL(valueChanged(int)), this, SLOT(viewContentSetToSubdiv(int)));
connect(resetViewButton, SIGNAL(clicked(bool)), canvas, SLOT(resetViewDirection(bool)));
connect(minOffsetBox, SIGNAL(textChanged(QString)), this, SLOT(resetMinOffset(QString)));
connect(maxOffsetBox, SIGNAL(textChanged(QString)), this, SLOT(resetMaxOffset(QString)));
connect(offsetStepBox, SIGNAL(textChanged(QString)), this, SLOT(resetOffsetStep(QString)));
connect(offsetValueSlider, SIGNAL(sliderReleased()), this, SLOT(offSetSliderMoved()));
connect(this, SIGNAL(makeOffsetMesh(float)), canvas, SLOT(offsetValueChanged(float)));
connect(foreColorButton, SIGNAL(clicked(bool)), this, SLOT(resetForeColor(bool)));
connect(backColorButton, SIGNAL(clicked(bool)), this, SLOT(resetBackColor(bool)));
connect(vertexModeButton, SIGNAL(clicked(bool)), this, SLOT(vertexModeChecked(bool)));
connect(borderModeButton, SIGNAL(clicked(bool)), this, SLOT(borderModeChecked(bool)));
connect(faceModeButton, SIGNAL(clicked(bool)), this, SLOT(faceModeChecked(bool)));
connect(canvas, SIGNAL(feedback_status_bar(QString, int)), statusBar, SLOT(showMessage(QString,int)));
connect(vertexModeButton, SIGNAL(clicked(bool)), canvas, SLOT(vertexModeChecked(bool)));
connect(borderModeButton, SIGNAL(clicked(bool)), canvas, SLOT(borderModeChecked(bool)));
connect(faceModeButton, SIGNAL(clicked(bool)), canvas, SLOT(faceModeChecked(bool)));
connect(addFaceButton, SIGNAL(clicked(bool)), canvas, SLOT(addToTempCalled(bool)));
connect(deleteFaceButton, SIGNAL(clicked(bool)), canvas, SLOT(deleteFaceCalled(bool)));
connect(addBorderButton, SIGNAL(clicked(bool)), canvas, SLOT(addBorderCalled(bool)));
connect(zipButton, SIGNAL(clicked(bool)), canvas, SLOT(zipToTempCalled(bool)));
connect(clearSelectionButton,SIGNAL(clicked(bool)), canvas, SLOT(clearSelectionCalled(bool)));
//connect(addTempToMasterButton, SIGNAL(clicked(bool)), canvas, SLOT(addTempToMasterCalled(bool)));
connect(wholeBorderCheck,SIGNAL(clicked(bool)), canvas, SLOT(wholeBorderSelectionChecked(bool)));
connect(trianglePaneltyEdit, SIGNAL(textChanged(QString)), canvas, SLOT(resetTrianglePanelty(QString)));
connect(consolidateButton, SIGNAL(clicked(bool)), canvas, SLOT(consolidateTempMesh(bool)));
}
void ControlPanel::setupLayout()
{
/* Main Layout.
* Contains view, mode, subdivision, offset, color, status.*/
setLayout(mainLayout = new QVBoxLayout);
mainLayout -> setMargin(10);
mainLayout->setSpacing(5);
mainLayout -> addWidget(new QLabel("VIEW MODE"));
mainLayout -> addLayout(viewLayout = new QVBoxLayout);
mainLayout -> addWidget(new QLabel("EDIT MODE"));
mainLayout -> addLayout(modeLayout = new QVBoxLayout);
mainLayout -> addWidget(new QLabel("SUBDIVISION"));
mainLayout -> addLayout(subdivLayout = new QVBoxLayout);
mainLayout -> addWidget(new QLabel("OFFSET"));
mainLayout -> addLayout(offsetLayout = new QVBoxLayout);
mainLayout -> addWidget(new QLabel("COLOR"));
mainLayout -> addLayout(colorLayout = new QVBoxLayout);
/* View layout. */
viewLayout -> addWidget(viewContent = new QComboBox);
viewContent -> addItem("Hirachical Scene");
viewContent -> addItem("Merged Mesh");
viewContent -> addItem("Subdivision Mesh");
viewContent -> addItem("Offset Mesh");
viewContent -> addItem("Subdivision on Offset Mesh");
viewContent -> setCurrentIndex(0);
viewLayout -> addWidget(resetViewButton = new QPushButton(tr("Reset Arcball View")));
/* Mode layout.*/
modeLayout -> addLayout(selectionLayout = new QHBoxLayout);
modeLayout -> addLayout(editLayout = new QHBoxLayout);
modeLayout -> addLayout(zipOptionsLayout = new QHBoxLayout);
selectionLayout -> addWidget(faceModeButton = new QRadioButton(tr("Select Face")));
selectionLayout -> addWidget(vertexModeButton = new QRadioButton(tr("Select Vertex")));
vertexModeButton -> setChecked(true);
selectionLayout -> addWidget(borderModeButton = new QRadioButton(tr("Select Border")));
editLayout -> addWidget(addFaceButton = new QPushButton(tr("Add Polygon")));
editLayout -> addWidget(addBorderButton = new QPushButton(tr("Add One Border")));
editLayout -> addWidget(deleteFaceButton = new QPushButton(tr("Delete Face")));
zipOptionsLayout -> addWidget(new QLabel(tr("Triangle Panelty")));
zipOptionsLayout -> addWidget(trianglePaneltyEdit = new QLineEdit(tr("1.3")));
zipOptionsLayout -> addWidget(zipButton = new QPushButton(tr("Zip Two Mesh Borders")));
modeLayout -> addLayout(addOrClearLayout = new QHBoxLayout);
modeLayout-> addWidget(autoCorrectCheck = new QCheckBox(tr("Auto Correct Adding Face Oreinataion")));
autoCorrectCheck -> setChecked(true);
modeLayout-> addWidget(wholeBorderCheck = new QCheckBox(tr("Zip Whole Border Loop")));
wholeBorderCheck -> setChecked(true);
wholeBorderCheck -> setEnabled(false);
//addOrClearLayout->addWidget(addTempToMasterButton = new QPushButton(tr("Add to Initial Mesh")));
addOrClearLayout->addWidget(clearSelectionButton = new QPushButton(tr("Clear Selection")));
modeLayout -> addWidget(consolidateButton = new QPushButton(tr("Consolidate Temp Mesh")));
modeLayout -> addWidget(mergeButton = new QPushButton(tr("Merge All")));
/* Subdivision layout. */
subdivLayout -> addLayout(subdivLevelLayout = new QHBoxLayout);
subdivLevelLayout -> addWidget(new QLabel("Level 0"));
subdivLevelLayout -> addWidget(subdivLevelSlider = new QSlider(Qt::Horizontal));
subdivLevelLayout -> addWidget(new QLabel("Level 5"));
subdivLayout -> addWidget(currentLevelLabel = new QLabel(tr("Current Subdivision Level: 0")));
subdivLevelSlider -> setMinimum(0);
subdivLevelSlider -> setMaximum(5);
subdivLevelSlider -> setValue(0);
/* Offset Layout. */
maxOffset = 0.005;
minOffset = 0.001;
offsetStep = 4;
offsetLayout -> addLayout(offsetMinMaxLayout = new QHBoxLayout);
offsetMinMaxLayout -> addWidget((new QLabel(tr("Min"))));
offsetMinMaxLayout -> addWidget(minOffsetBox = new QLineEdit(QString::number(minOffset)));
offsetMinMaxLayout -> addWidget((new QLabel(tr("Max"))));
offsetMinMaxLayout -> addWidget(maxOffsetBox = new QLineEdit(QString::number(maxOffset)));
offsetMinMaxLayout -> addWidget((new QLabel(tr("Step"))));
offsetMinMaxLayout -> addWidget(offsetStepBox = new QLineEdit(QString::number(offsetStep)));
offsetLayout -> addLayout(offsetValueLayout = new QHBoxLayout);
offsetValueLayout -> addWidget(offsetValueSlider = new QSlider(Qt::Horizontal));
offsetValueSlider -> setMinimum(0);
offsetValueSlider -> setMaximum(offsetStep);
offsetValueSlider -> setValue(0);
offsetLayout -> addWidget(currentOffsetValueLabel = new QLabel(tr("Current Offset Value: ")));
/* Color Layout. */
colorLayout -> addLayout(foreColorLayout = new QHBoxLayout);
colorLayout -> addLayout(backColorLayout = new QHBoxLayout);
colorLayout -> setSpacing(2);
foreColorLayout -> addWidget(foreColorButton = new QPushButton(tr("Foreground Color")));
foreColorLayout -> addWidget(foreColorBox = new QWidget());
foreColorBox -> resize(5,5);
QPalette forePal = foreColorBox->palette();
forePal.setColor(foreColorBox->backgroundRole(), QColor(255,0,0));
foreColorBox->setPalette(forePal);
foreColorBox -> setAutoFillBackground(true);
backColorLayout -> addWidget(backColorButton = new QPushButton(tr("Background Color")));
backColorLayout -> addWidget(backColorBox = new QWidget());
QPalette backPal = foreColorBox->palette();
backPal.setColor(backColorBox->backgroundRole(), QColor(0,0,0));
backColorBox->setPalette(backPal);
backColorBox -> setAutoFillBackground(true);
backColorBox -> resize(5,5);
mainLayout -> addWidget(statusBar = new QStatusBar);
}
void ControlPanel::test(QString test)
{
cout<<test.toStdString()<<endl;
}
void ControlPanel::test(bool checked)
{
cout<<"Hello!"<<endl;
}
void ControlPanel::viewContentReset()
{
viewContent ->setCurrentIndex(1);
}
void ControlPanel::viewContentSetToSubdiv(int level)
{
viewContent -> setCurrentIndex(2);
currentLevelLabel -> setText(tr("Current Subdivision Level: "
) + QString::number(level));
}
void ControlPanel::resetMinOffset(QString minOffset)
{
this->minOffset = minOffset.toFloat();
}
void ControlPanel::resetMaxOffset(QString maxOffset)
{
this->maxOffset = maxOffset.toFloat();
}
void ControlPanel::resetOffsetStep(QString offsetStep)
{
this->offsetStep = offsetStep.toInt();
offsetValueSlider->setMaximum(this->offsetStep);
}
void ControlPanel::offSetSliderMoved()
{
int value = offsetValueSlider ->value();
float realOffsetValue = minOffset + (maxOffset - minOffset) / offsetStep * value;
emit makeOffsetMesh(realOffsetValue);
viewContent -> setCurrentIndex(3);
currentOffsetValueLabel -> setText(tr("Current Offset Value: "
) + QString::number(realOffsetValue));
}
void ControlPanel::viewContentSetToSubdivOffset()
{
viewContent -> setCurrentIndex(4);
}
void ControlPanel::resetForeColor(bool)
{
QColor newColor = QColorDialog::getColor();
QPalette forePal = foreColorBox->palette();
forePal.setColor(foreColorBox->backgroundRole(), newColor);
foreColorBox->setPalette(forePal);
canvas -> setForeColor(newColor);
}
void ControlPanel::resetBackColor(bool)
{
QColor newColor = QColorDialog::getColor();
QPalette backPal = backColorBox->palette();
backPal.setColor(backColorBox->backgroundRole(), newColor);
backColorBox->setPalette(backPal);
canvas -> setBackColor(newColor);
}
void ControlPanel::vertexModeChecked(bool checked)
{
autoCorrectCheck->setEnabled(checked);
wholeBorderCheck->setEnabled(!checked);
statusBar -> showMessage(tr("Switch to Vertex Selection Mode"));
}
void ControlPanel::borderModeChecked(bool checked)
{
autoCorrectCheck->setEnabled(!checked);
wholeBorderCheck->setEnabled(checked);
statusBar -> showMessage(tr("Switch to Border Selection Mode"));
}
void ControlPanel::faceModeChecked(bool checked)
{
autoCorrectCheck->setEnabled(!checked);
wholeBorderCheck->setEnabled(!checked);
statusBar -> showMessage(tr("Switch to Face Selection Mode"));
}
void ControlPanel::pushMerge(bool)
{
viewContent -> setCurrentIndex(1);
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#include "mainwindow.h"
MainWindow::MainWindow()
{
createActions();
createMenus();
//createControlPanel(canvas);
//setCentralWidget(controls);
}
void MainWindow::open()
{
QString fileName = QFileDialog::getOpenFileName(this,
tr("Import Input File"), "/", tr("Geometry Files (*.nom *.sif *.anom)"));
if(fileName == "")
{
return;
}
createCanvas(fileName);
}
void MainWindow::save()
{
QString fileName = QFileDialog::getSaveFileName(this,
tr("Save Output File"), "/", tr("Output Files (*.stl *.nom *.anom)"));
if(fileName == "")
{
return;
}
else if(canvas == NULL)
{
cout<<"Error: No work to be saved!"<<endl;
return;
}
else if(fileName.right(3).toLower() == "stl")
{
canvas -> saveMesh(fileName.toStdString());
}
else if(fileName.right(4).toLower() == "anom")
{
save_current_status_anom(fileName.toStdString());
}
else
{
save_current_status_nome(fileName.toStdString());
}
}
void MainWindow::close()
{
if(canvas != NULL) {
canvas -> hierarchical_scene_transformed.clearAndDelete();
canvas -> master_mesh.clearAndDelete();
//canvas -> temp_mesh.clearAndDelete();
//canvas -> consolidate_mesh.clearAndDelete();
//canvas -> merged_mesh.clearAndDelete();
//canvas -> subdiv_mesh.clearAndDelete();
//canvas -> offset_mesh.clearAndDelete();
canvas -> close();
scene.clearAndDelete();
append_scene.clearAndDelete();
nomeParser = NULL;
delete(canvas);
canvas = NULL;
controls -> close();
delete(controls);
controls = NULL;
for(SliderPanel*& panel: slider_panels)
{
panel->close();
delete(panel);
panel = NULL;
}
slider_panels.clear();
banklines.clear();
colorlines.clear();
geometrylines.clear();
postProcessingLines.clear();
banks.clear();
params.clear();
}
}
void MainWindow::quit()
{
exit(1);
}
void MainWindow::createActions()
{
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open a SIF or NOME file"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
saveAct = new QAction(tr("&Save..."), this);
saveAct->setShortcuts(QKeySequence::Save);
saveAct->setStatusTip(tr("Save your work as a NOME or STL file"));
connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
closeAct = new QAction(tr("&Close..."), this);
closeAct->setShortcuts(QKeySequence::Close);
closeAct->setStatusTip(tr("Close the file and canvas"));
connect(closeAct, SIGNAL(triggered()), this, SLOT(close()));
quitAct = new QAction(tr("&Quit..."), this);
quitAct->setShortcuts(QKeySequence::Quit);
quitAct->setStatusTip(tr("Open an existing file"));
connect(quitAct, SIGNAL(triggered()), this, SLOT(quit()));
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
fileMenu->addAction(saveAct);
fileMenu->addAction(closeAct);
fileMenu->addAction(quitAct);
}
void MainWindow::createCanvas(QString name)
{
if(name.right(3).toLower() == "sif")
{
canvas = new SlideGLWidget(name.toStdString());
canvas -> move(0, 50);
canvas -> show();
createControlPanel(canvas);
}
else if(name.right(4).toLower() == "anom")
{
if(canvas == NULL)
{
cout<<"Warning: you need an existing working slf file to open this file.\n";
return;
}
else
{
canvas -> group_from_consolidate_mesh = &append_scene;
nomeParser->appendWithANOM(params, append_scene, canvas, name.toStdString());
}
}
else if (name.right(3).toLower() == "nom")
{
nomeParser->makeWithNome(banks, params, scene, name.toStdString(),
colorlines, banklines, geometrylines, postProcessingLines);
canvas = new SlideGLWidget(scene);
canvas -> group_from_consolidate_mesh = &append_scene;
nomeParser->postProcessingWithNome(params, postProcessingLines, canvas, append_scene, name.toStdString());
createSliderPanel(canvas);
canvas -> move(0, 50);
canvas -> show();
createControlPanel(canvas);
}
else
{
cout<<"File type not supported!";
}
}
void MainWindow::createSliderPanel(SlideGLWidget * canvas)
{
for(size_t i = 0; i < banks.size(); i++)
{
SliderPanel *newPanel = new SliderPanel(&banks[i], canvas);
newPanel -> show();
newPanel -> move(10, 10);
slider_panels.push_back(newPanel);
}
}
void MainWindow::createControlPanel(SlideGLWidget * canvas)
{
controls = new ControlPanel(canvas);
controls -> move(900, 50);
controls -> show();
}
void MainWindow::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
menu.exec(event->globalPos());
}
void MainWindow::save_current_status_anom(string out_put_file)
{
ofstream file(out_put_file);
if (!file.is_open())
{
cout <<"Error: COULD NOT OPEN THE FILE.\n";
}
else
{
file<<"savedparameter\n";
for(ParameterBank& bank : banks)
{
for(Parameter*& p : bank.parameters)
{
file<<" "<<(p->name).toStdString()<<" "<<to_string(p->value)<<"\n";
}
}
file<<"endsavedparameter\n";
if(!(canvas->consolidate_mesh).isEmpty())
{
file<<"\n";
file<<"consolidate\n";
for(Face*& face: (canvas->consolidate_mesh).faceList)
{
file<<" consolidateface\n";
Edge * firstEdge = face -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(face == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
file<<" vertex "<<tempv->name<<" endvertex\n";
currEdge = nextEdge;
} while (currEdge != firstEdge);
file<<" endconsolidateface\n";
}
file<<"endconsolidate\n";
}
}
}
void MainWindow::save_current_status_nome(string out_put_file)
{
ofstream file(out_put_file);
if (!file.is_open())
{
cout <<"Error: COULD NOT OPEN THE FILE.\n";
}
else
{
string bankname = "";
if(colorlines.size() > 0)
{
file<<"#### Some Surface colors #####\n";
for(string& line : colorlines)
{
file<<line<<'\n';
}
file<<"\n";
}
for(string& line : banklines)
{
istringstream iss(line);
vector<string> tokens;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(tokens));
//file << line <<'\n';
if(tokens[0] == "bank")
{
bankname = tokens[1];
}
if(tokens[0] == "set")
{
file << " ";
for(int i = 0; i < tokens.size(); i++)
{
if(i == 2)
{
file << params[bankname + "_" + tokens[1]].value;
}
else
{
file << tokens[i];
}
file<<'\t'<<'\t';
}
file << '\n';
}
else
{
file << line <<'\n';
}
}
for(string& line : geometrylines)
{
file<<line<<'\n';
}
}
if(!(canvas->consolidate_mesh).isEmpty() || (canvas -> deletedFaces).size() > 0)
{
file<<"\n##### The following is the saved work of last time. #####\n"<<endl;
}
if(!(canvas->consolidate_mesh).isEmpty())
{
file<<"##### The added faces. #####\n";
file<<"mesh consolidatedmesh\n";
int counter = 0;
for(Face*& face: (canvas->consolidate_mesh).faceList)
{
file<<" face";
file<<" consolidatedface"<<counter++<<" (";
Edge * firstEdge = face -> oneEdge;
Edge * currEdge = firstEdge;
Edge * nextEdge;
Vertex * tempv;
do {
if(face == currEdge -> fa) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFa;
} else {
if(currEdge -> mobius) {
tempv = currEdge -> vb;
nextEdge = currEdge -> nextVbFb;
} else {
tempv = currEdge -> va;
nextEdge = currEdge -> nextVaFb;
}
}
file<<tempv->source_vertex->name<<" ";
currEdge = nextEdge;
} while (currEdge != firstEdge);
file<<") endface\n";
}
file<<"endmesh\n";
}
if((canvas -> deletedFaces).size() > 0)
{
file<<"\n##### The deleted faces #####\n";
file<<"delete\n";
for(string deletedFace : (canvas->deletedFaces))
{
file<<" face "<<deletedFace<<" endface\n";
}
file<<"enddelete\n";
}
if(!(canvas->consolidate_mesh).isEmpty())
{
file<<"\n####Create an instance of the consolidated mesh here.####\n"<<endl;
file<<"instance cm1 consolidatedmesh endinstance\n";
}
}
<file_sep>#include "makegroup.h"
void makeGroupTest1(Group)
{
}
void makeGroupTest2(Group &group)
{
Mesh oneMesh;
makeCube(oneMesh,0.5,0.5,0.5);
oneMesh.setColor(QColor(255, 255, 0));
oneMesh.computeNormals();
Transformation oneTransform(1, 1, 1, 1, PI/2);
oneMesh.addTransformation(oneTransform);
group.addMesh(oneMesh);
}
void makeGroupTest3(Group &group)
{
Mesh oneMesh;
makeCube(oneMesh,0.5,0.5,0.5);
oneMesh.computeNormals();
Transformation oneTransform(3, 1, 1, 1);
Transformation secondTransform(3, -1, -1, -1);
oneMesh.setColor(Qt::green);
Mesh secondMesh = oneMesh.makeCopy();
secondMesh.setColor(Qt::blue);
secondMesh.computeNormals();
oneMesh.addTransformation(oneTransform);
secondMesh.addTransformation(secondTransform);
group.addMesh(oneMesh);
group.addMesh(secondMesh);
}
void makeGroupTest4(Group &group)
{
Mesh oneMesh;
Group subGroup1;
makeCube(oneMesh,0.5,0.5,0.5);
Transformation oneTransform(3, 1, 1, 1);
Transformation secondTransform(3, -1, -1, -1);
oneMesh.computeNormals();
Mesh secondMesh = oneMesh.makeCopy();
oneMesh.addTransformation(oneTransform);
secondMesh.addTransformation(secondTransform);
subGroup1.addMesh(oneMesh);
group.addGroup(subGroup1);
group.addMesh(secondMesh);
group.setColor(Qt::white);
group.assignColor();
}
void makeGroupTest5(Group &group)
{
Mesh oneMesh;
Group subGroup1;
Group subGroup2;
makeCube(oneMesh,0.5,0.5,0.5);
oneMesh.computeNormals();
Transformation oneTransform(3, 0, 0, 0.5);
Transformation secondTransform(3, 0, 0, -0.5);
Mesh secondMesh = oneMesh.makeCopy();
oneMesh.addTransformation(oneTransform);
secondMesh.addTransformation(secondTransform);
subGroup1.addMesh(oneMesh);
subGroup2.addMesh(secondMesh);
group.addGroup(subGroup1);
group.addGroup(subGroup2);
group.setColor(Qt::red);
group.assignColor();
}
void makeGroupTest6(Group &group)
{
Mesh oneMesh;
Group subGroup1;
Group subGroup1_1;
makeCube(oneMesh,0.5,0.5,0.5);
oneMesh.computeNormals();
Transformation oneTransform(3, 0, 0, 0.5);
Transformation secondTransform(3, 0, 0, -0.5);
Mesh secondMesh = oneMesh.makeCopy();
oneMesh.addTransformation(oneTransform);
secondMesh.addTransformation(secondTransform);
secondMesh.computeNormals();
subGroup1.addMesh(oneMesh);
subGroup1_1.addMesh(secondMesh);
subGroup1.addGroup(subGroup1_1);
group.addGroup(subGroup1);
group.setColor(Qt::blue);
group.assignColor();
}
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef SLIDEGLWIDGET_H
#define SLIDEGLWIDGET_H
#include <QMainWindow>
#include <QtOpenGL>
#define ROTATION_SPEED (1.0)
#if __linux__
#include <GL/glut.h>
#include <GL/gl.h>
#define ROTATION_SPEED (50.0)
#elif __APPLE__
#include <GLUT/GLUT.h>
#define ROTATION_SPEED (1.0)
#endif
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <gl\gl.h>
#include <gl\glu.h>
#endif
#include "mesh.h"
#include "makeMesh.h"
#include "polyline.h"
#include "group.h"
#include "makegroup.h"
#include "myselection.h"
#include "subdivison.h"
#include "stl.h"
#include "offset.h"
#include "zipper.h"
#include "parameter.h"
#include "parameterbank.h"
#include <QMessageBox>
#include <QColor>
#include <QString>
class SlideGLWidget: public QGLWidget
{
Q_OBJECT
public:
explicit SlideGLWidget(QWidget *parent = 0);
SlideGLWidget(string name, QWidget *parent = 0);
SlideGLWidget(Group &group, QWidget *parent = 0);
~SlideGLWidget();
/**
* Save the current master_mesh in a STL file.
*/
void saveMesh(string name);
/**
* @brief subdivide: for certain level.
* @param level, level of subdivision.
*/
void subdivide(int level);
/**
* @brief offset: create offset mesh with given value.
* @param value: the value of this offset.
*/
void offset(float value);
/**
* @brief setForeColor, set default foreground color.
* @param color, the color to be set.
*/
void setForeColor(QColor color);
/**
* @brief setBackColor, set default background color.
* @param color, the color to be set.
*/
void setBackColor(QColor color);
/* The master mesh. As a result of SIF parser. */
Mesh master_mesh;
/* The mesh that contains temporary added meshes.*/
Mesh temp_mesh;
/* The mesh confirmed by the user and become permenant change. */
Mesh consolidate_mesh;
/* The merged result of all meshes in the scene and consolidate mesh. */
Mesh merged_mesh;
/* The current subdivided mesh. */
Mesh subdiv_mesh;
/* The pointer to the whole scene. */
Group * hierarchical_scene;
/* A copy of the hierarchical_scene, with all meshes transformed. */
Group hierarchical_scene_transformed;
/* The group from saved consolidate mesh. It is created from aslf file. */
Group * group_from_consolidate_mesh;
/* Update the canvas after reading in the aslf file. */
void updateFromSavedMesh();
/* Set the in_editing_mode of scene shown and all leave meshes.*/
void set_to_editing_mode(bool in_editing_mode);
/* Record the list of the name of faces deleted by the user.
* (Not including the consolidated mesh or temprary mesh. */
vector<string> deletedFaces;
private:
/* Viewer variables.*/
enum MODES { MODE_OBJECT, MODE_CAMERA, MODE_LIGHT, MODE_LAST } view_mode;
mat4 transforms[MODE_LAST];
float cameraDistance;
/* Support arcball feature.*/
int last_mx, last_my, cur_mx, cur_my;
/* Support arcball feature. */
int arcball_on;
/* object2world matrix for arcball.*/
mat4 object2world;
/* control of the wireframe mode. */
bool wireframe;
/* control of the backface illuminiation. */
bool backface;
/* control of the shading mode. */
bool smoothshading;
/**
* @brief makeDefaultMesh: Make a default mesh of a cube.
*/
void makeDefaultMesh();
/**
* @brief makeSIFMesh: Make a mesh by reading in a SIF file.
* @param name: The path to the input file.
*/
void makeSIFMesh(string name);
/**
* @brief makeSLFMesh: Make a mesh by the output of SLF file parser.
*/
void makeSLFMesh();
/* A subdivider to handle subdivision.*/
Subdivision *subdivider;
/* An offseter to handle offsetting.*/
Offset *offseter;
/**
* The cache of mesh that has been subdivided.
* The index in this vector = subdivision level - 1.
*/
vector<Mesh> cache_subdivided_meshes;
/* A pointer to the offset mesh. */
Mesh offset_mesh;
/* A pointer to the subdivided offset mesh. */
Mesh subdiv_offset_mesh;
/*
* Selection object to handle mouse selection.
* Only works for interactive editing mode.
*/
MySelection mySelect;
/**
* Get a normalized vector from the center of the virtual ball O to a
* point P on the virtual ball surface, such that P is aligned on
* screen's (X,Y) coordinates. If (X,Y) is too far away from the
* sphere, return the nearest point on the virtual ball surface.
*/
vec3 get_arcball_vector(int x, int y);
/**
* A wrapper function for selection with mouse
* @param x, the x coordinate of the mouse clicked
* @param y, the y coordinate of the mouse clicked
* @param mode, the mode of selection.
*/
void mouse_select(int x, int y);
/**
* selection_mode = 0: face selection;
* selection_mode = 1: vertex selection
* selection_mode = 2: whole border selection (line loop)
* selection_mode = 3: partial border selection (line strip)
*/
int selection_mode;
/* Called by constructor to setup general background parameters. */
void generalSetup();
/* A message box that deliver error message.*/
QMessageBox *errorMsg;
/* Zoom in in the current view. */
void zoom_in();
/* Zoom out in the current view. */
void zoom_out();
/*
* The foreground color.
*/
QColor foreColor;
/*
* The background color.
*/
QColor backColor;
/*
* The temp mesh color.
*/
QColor tempColor;
/* Auto check if the newly added face can have
* same orientation with master_mesh. */
bool auto_check;
/* Check if whole border selection is on.*/
bool whole_border;
/* The zipper.*/
Zipper *zipper;
/* The first border to zip.*/
PolyLine border1;
/* The second border to zip. */
PolyLine border2;
/**
* @brief clearSubDivisionAndOffset: Clear the subdiv_mesh
* and offset_mesh.
*/
void clearSubDivisionAndOffset();
/**
* @brief clearSelection: clear the selected items.
*/
void clearSelection();
/* A flattened view of meshes in the current scene. */
vector<Mesh*> global_mesh_list;
/* A flattened view of polylines in the current scene. */
vector<PolyLine*> global_polyline_list;
/* Index list of where the name buffer start for every mesh.*/
vector<int> global_name_index_list;
/* Index list of where the name buffer start for every polyline.*/
vector<int> global_polyline_name_index_list;
/* Update the global name index list.*/
void updateGlobalIndexList();
/* A wrapper class to draw the whole scene.
* The drawing result depends on the viewer_mode.
*/
void draw_scene();
/* The trianglePanelty for zipping function. */
float trianglePanelty;
/* Create the hierarchical_scene_transformed. */
void transform_meshes_in_scene();
/* The current mode of view.
* 1: Hierarchical Scene.
* SLF will read in the scene with parameters set up.
* SIF will read in just one mesh.
* This is the interactive editing mode.
* 2: Merged Modified Mesh
* This is the merged result of the modified mesh. It is a perfect
* 2-manifold to serve as the input of the subdivision.
* 3: Subdivied Mesh
* 4: Offseted Mesh
*/
int viewer_mode;
/* A wrapper function to draw the viewed mesh. */
void draw_mesh(int start_index, Mesh *mesh);
/* A wrapper function to draw the viewed polyline. */
void draw_polyline(int start_index, PolyLine *polyline);
/* Current work phase. */
int work_phase;
/* The current subdivision level.*/
int subdiv_level;
/* The current offset value. */
float offset_value;
/* Merge all meshes from global_mesh_list into master_mesh.*/
void mergeAll();
/* Update the temprary mesh.*/
void updateTempMesh();
/* Update the consolidate mesh.*/
void updateConsolidateMesh();
/* Update the saved consolidated mesh. */
void updateSavedConsolidatedMesh();
protected:
void initializeGL();
void resizeGL(int w, int h);
void paintGL();
void mousePressEvent(QMouseEvent*);
void mouseMoveEvent(QMouseEvent*);
void keyPressEvent(QKeyEvent*);
/**
* @brief timerEvent: Timer Event for this MainWindow.
* Similar to OnIdleFunc of GLUT.
*/
void timerEvent(QTimerEvent *event);
/**
* @brief wheelEvent: Handles mouse wheel event.
* Will zoom in or zoom out in the scene.
* @param event: The qt wheel event.
*/
void wheelEvent(QWheelEvent *event);
public slots:
/**
* @brief viewContentChanged: Change the current view mesh.
* @param viewer_mode, the mode for the viewer.
*/
void viewContentChanged(int viewer_mode);
/* Receive the signal from control panel to do subdivision.*/
void levelChanged(int);
/* Receive the signal to reset the viewing direction. */
void resetViewDirection(bool);
/* Receive the signal of offset value changed. */
void offsetValueChanged(float);
/* Recevie the signal of changing to vertex selection mode. */
void vertexModeChecked(bool);
/* Recevie the signal of changing to border selection mode. */
void borderModeChecked(bool);
/* Recevie the signal of changing to face selection mode. */
void faceModeChecked(bool);
/* Receive the signal auto correct orientation in adding mode. */
void autoCorrectChecked(bool);
/* Receive the signal whole border selection in zipping mode. */
void wholeBorderSelectionChecked(bool);
/* Receive the signal to add a polygon to temp_mesh. */
void addToTempCalled(bool);
/* Receive the signal to zip two borders.
* And add the result polygons to temp_mesh. */
void zipToTempCalled(bool);
/* Recieve signal to add the temp_mesh to master_mesh.*/
void addTempToMasterCalled(bool);
/* Recieve signal to add the temp_mesh to consolidated_mesh. */
void consolidateTempMesh(bool);
/* Add temp_mesh to master_mesh. */
void addTempToMaster();
/* Receive the signal to add a border. Add border1 first*/
void addBorderCalled(bool);
/* Receive the signal to clear all selections.
* Including selected vertices and border. */
void clearSelectionCalled(bool);
/* Reset the triangle panelty of zipping function. */
void resetTrianglePanelty(QString);
/* @brief mergeCalled: Recieve the signal from control panel to merge. */
void mergeCalled(bool);
/* Slider value changed.*/
void paramValueChanged(float);
/* Delete the selected faces called. */
void deleteFaceCalled(bool);
signals:
/* A feedback signal send back to control panel statusBar.*/
void feedback_status_bar(QString, int);
};
#endif // SLIDEGLWIDGET_H
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __SUBDIVISION_H__
#define __SUBDIVISION_H__
#include "mesh.h"
#include "merge.h"
#include "makeMesh.h"
using namespace glm;
using namespace std;
//////////////////////////////////////////////////////////////////////
// Subdivision Class -- Functions to perform the subdivision for a mesh
class Subdivision{
public:
// The mesh to be subdivide;
Mesh currMesh;
// Constructor.
Subdivision();
// Constructor.
// @param mesh: the reference of given mesh.
Subdivision(Mesh mesh);
// The integration of subdivision.
// @param level: level of Catmull-Clark subdivision.
Mesh ccSubdivision(int level);
private:
// Construct face points in Catmull-Clark subdivision.
// Computed values are stored in face.facepoint. Add new Vertices to vertTable.
// @param newVertList: The list of vertices for next level mesh.
void makeFacePoints(vector<Vertex*> &newVertList);
// Construct edge points in Catmull-Clark subdivision.
// Computed values are stored in edge.edgepoint. Add new Vertices to vertTable.
// @param newVertList: The list of vertices for next level mesh.
void makeEdgePoints(vector<Vertex*> &newVertList);
// Construct vertex points in Catmull-Clark subdivision with DeRose et al's Equation.
// By modifying the original position and pointers of the vertex.
// @param newVertList: The list of vertices for next level mesh.
void makeVertexPointsD(vector<Vertex*> &newVertList);
// Similar to the above function, but with Catmull-Clark's equation.
// @param newVertList: The list of vertices for next level mesh.
void makeVertexPointsC(vector<Vertex*> &newVertList);
// Construct a new mesh after given new facepoints, edgepoints, and vertexpoints.
// @param newFaceList: the list of faces for the next level mesh.
void compileNewMesh(vector<Face*> &newFaceList);
// In order to redo the subdivision, we need to set all next level subdivision to null
void setAllNewPointPointersToNull();
};
#endif // __SUBDIVISION_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __STL_H__
#define __STL_H__
#include <vector>
#include <iomanip>
#include <fstream>
#include "mesh.h"
using namespace glm;
using namespace std;
// Forward declarations
class Vertex;
class Face;
//////////////////////////////////////////////////////////////////////
// STL Class -- Input and Output with STL Format Files.
//
class STL{
public:
STL(){};
void STLOutput(vector<Mesh> &meshes, string outputSTL);
void STLOutput(Mesh &mesh, string outputSTL);
};
// Get a triangular surface normal.
// @param v1 v2 v3: three vertices of the triangle.
vec3 getTriFaceNormal(Vertex * va, Vertex * vb, Vertex * vc);
#endif// __STL_H__
<file_sep>/**
* @author <NAME>, UC Berkeley.
* Copyright 2016 reserve.
* UC Berkeley, Slide_2016 project.
* Advised by Prof. <NAME>.
*/
#ifndef __TRANSFORMATION_H__
#define __TRANSFORMATION_H__
#include <vector>
#include <string>
#include <unordered_map>
#include "utils.h"
#include <glm/gtx/transform.hpp>
#include <glm/gtc/constants.hpp>
using namespace std;
using namespace glm;
//////////////////////////////////////////////////////////////////////
// Transformation Class -- A class to create a new mesh by transformation.
class Transformation
{
public:
Transformation();
Transformation(int type, float x, float y, float z);
Transformation(int type, float x, float y, float z, float w);
Transformation(int type, unordered_map<string, Parameter> *params, string input1, string input2 = "");
/**
* @brief type: The type of this transformation.
* 0: Nothing, matrix is an identity matrix.
* 1: Rotation
* 2: Scaling
* 3: Translation
* 4: Mirroring
*/
int type;
/**
* @brief x: The first parameter of this transformation.
* Roation: the x for rotation axis
* Scale: scaling factor in x direction.
* Translation: translation in x direction.
* Mirroring: the constant for x of mirroring plane.
*/
float x;
/**
* @brief y: The second parameter of this transformation.
* Roation: the y for rotation axis
* Scale: scaling factor in y direction.
* Translation: translation in y direction.
* Mirroring: the constant for y of mirroring plane.
*/
float y;
/**
* @brief z: The third parameter of this transformation.
* Roation: the z for rotation axis
* Scale: scaling factor in z direction.
* Translation: translation in z direction.
* Mirroring: the constant for z of mirroring plane.
*/
float z;
/**
* @brief x: The first parameter of this transformation.
* Roation: angle for rotation axis
* Scale: don't have this parameter.
* Translation: don't have this parameter
* Mirroring: the constant of intercept of mirroring plane.
*/
float w;
/* Indicate if this transformation is parametric. */
bool isParametric;
/* The string expression of parameter x. */
string x_expr;
/* The string expression of parameter y. */
string y_expr;
/* The string expression of parameter z. */
string z_expr;
/* The string expression of parameter w. */
string w_expr;
/* A pointer to the global parameter. */
unordered_map<string, Parameter> *params;
/* Set the global parameter pointer for this mesh. */
void setGlobalParameter(unordered_map<string, Parameter> *params);
/* The stored transformation matrix.*/
mat4 matrix;
/**
* @brief rotate: Create the rotation matrix based on parameters.
*/
void rotate();
/**
* @brief scale: Create the scaling matrix based on parameters.
*/
void scale();
/**
* @brief translate: Create the translation matrix based on parameters.
*/
void translate();
/**
* @brief mirror: Create the mirror matrix based on parameters.
*/
void mirror();
/**
* @brief getMatrix: Get a 4X4 matrix for this transformation.
* @return the transformation matrix.
*/
mat4 getMatrix();
/**
* @brief updateParameter: Update the parameters of this transformation.
*/
void updateParameter();
/**
* @brief updateMatrix: Update the matrix.
*/
void updateMatrix();
/**
* @brief update: Update this transformation.
*/
void update();
/* A list of parameters influencing this transformation.*/
vector<Parameter*> influencingParams;
/* Add a parameter that influence this transformation. */
void addParam(Parameter*);
};
#endif // TRANSFORMATION_H
<file_sep>#include "myslider.h"
#include "parameter.h"
MySlider::MySlider()
{
}
MySlider::MySlider(Parameter *param)
{
setParameter(param);
generalSetup();
}
void MySlider::generalSetup()
{
QVBoxLayout *mainLayout = new QVBoxLayout;
setLayout(mainLayout);
mainLayout -> addWidget(currValue = new QLabel((param -> name) + QString(" : ") +QString::number(param -> value)));
QHBoxLayout *sliderLayout;
mainLayout -> addLayout(sliderLayout = new QHBoxLayout);
sliderLayout -> addWidget(new QLabel(QString::number(param -> start)));
sliderLayout -> addWidget(slider = new QSlider(Qt::Horizontal));
slider -> setMinimum(0);
slider -> setMaximum(int((param -> end - param -> start) / param -> stepsize));
slider -> setValue(int((param -> value - param -> start) / param -> stepsize));
sliderLayout -> addWidget(new QLabel(QString::number(param -> end)));
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(changeValue(int)));
}
void MySlider::setParameter(Parameter *param)
{
this -> param = param;
}
void MySlider::changeValue(int newValue)
{
param -> value = newValue * (param -> stepsize) + param -> start;
param -> update();
currValue-> setText((param -> name) + QString(" : ") +QString::number(param -> value));
emit paramValueChanged(param -> value);
}
| a312c3175a647b14b2881af10c46ce70b9c37440 | [
"Markdown",
"C++"
] | 47 | C++ | andyatcal/nome | 86c44fab6810ef735854f23088896d1ff7ac9db5 | 0de30b4b5f1558394111cb0c24be5d73c219d603 |
refs/heads/master | <file_sep>// Async function to make a promise to resolve or reject the promise
const fetchData = () => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done');
}, 1500);
});
return promise;
}
// async code run when time runs out, calls the promise code and logs the result, chaining promises
setTimeout(() => {
console.log("timer finished");
fetchData().then(text => {
console.log(text);
return fetchData()
})
.then(text2 => {
console.log(text2);
});
}, 2000);
// synch code runs in procedural manner
console.log('Before Timer');<file_sep>const person = {
name: "jp",
age: 23,
//creating a function inside of a constant as a property
greet() {
console.log("Hi, I am " + this.name);
}
}
// Object destructuring, receiving only a property name from the js object
const printName = ({name}) => {
console.log(name);
}
printName(person);
// Object destructuring, set constants of properties - names must be same
const {name, age} = person;
console.log(name, age);
// spread operator to create a copy of an object
const copiedPerson = {...person};
console.log(copiedPerson);
// Spread operator to create a copy of an array
const hobbies = ["soccer","coding"];
const copiedHobbies = [...hobbies];
console.log(copiedHobbies);
// Rest operator to return variable length arguments as an array
function toArray(...args) {
return args;
}
console.log(toArray(1,2,3));
// array destructuring, taken from list in order
const [hobby1, hobby2] = hobbies;
console.log(hobby1, hobby2);
| 649bdeea613b5433bdbf671d2e080259bdc3785b | [
"JavaScript"
] | 2 | JavaScript | KeomalaP/TestNodeJs | e284d71a4a8d4fca2963feb48fbaf1cea1a5e771 | 5143da38b30446e6260097fecb4342ffcefb2be2 |
refs/heads/master | <repo_name>marqsm/phonebook_py<file_sep>/phonebook.py
import os
class Phonebook():
myvar = [1, 2, 3]
def __init__(self):
self.phonebook = {}
@staticmethod
def pb_parse_input_row(row):
"""parse one row from file input"""
row = row.rstrip('\n') # remove digits
name = ''.join([c for c in row if not c.isdigit()]).strip()
number = ''.join([c for c in row if c.isdigit()]).strip()
return name, number
@staticmethod
def pb_parse_output_row(name, number):
"""parse output string from name & number"""
return name + ' ' + number + '\n'
def print_results(self, rows):
"""parse all results (accepts list of key-value pairs)"""
if len(rows) > 0:
for name, number in rows.iteritems():
print name + ' ' + number
else:
print 'No results'
def pb_load(self, filename):
"""load phonebook from file"""
pb = {}
with open(filename, 'r') as f:
for line in f:
name, number = self.pb_parse_input_row(line)
pb[name] = number
self.phonebook = pb
return pb
def pb_save(self, filename):
"""save phonebook to a file"""
with open(filename, 'w') as f:
for name, number in self.phonebook.iteritems():
f.write(self.pb_parse_output_row(name, number))
def pb_create(self, filename):
if not os.path.isfile(filename):
f = open(filename, 'w')
f.close()
return True
print('Created phonebook %s in current directory' % (filename))
else:
print('Error: file %s already exists!' % (filename))
return False
def pb_lookup(self, name_lookup):
"""find by text partial match to name string"""
results = {}
search_name = name_lookup.lower()
for name, num in self.phonebook.iteritems():
if search_name in name.lower():
results[name] = num
return results
def pb_reverse_lookup(self, number):
"""find by phone number (exact match)"""
results = {}
canonical_num = "".join([c for c in number if c.isdigit()])
for name, num in self.phonebook.iteritems():
if num.strip() == canonical_num:
results[name] = num
return results
def pb_add(self, name, number):
"""check if row exists. Return false if already exists"""
if name in self.phonebook:
return False
self.phonebook[name] = number
return True
def pb_change(self, name, number):
print(name, number, self.phonebook)
if name in self.phonebook:
self.phonebook[name] = number
return True
else:
return False
def pb_remove(self, name):
"""phonebook remove '<NAME>' hsphonebook.pb"""
if name in self.phonebook:
self.phonebook.pop(name, None)
return True
else:
return False
<file_sep>/phonebook_tests.py
import unittest
import os
import phonebook
phonebook = phonebook.Phonebook()
class TestPhonebook(unittest.TestCase):
fx_pb = {}
fx_filename = 'phonebook_fixtures.pb'
def setUp(self):
self.fx_pb = phonebook.pb_load(self.fx_filename)
def test_pb_load(self):
pb = phonebook.pb_load(self.fx_filename)
self.assertEqual(pb, {'<NAME>': '1234567890',
'<NAME>': '5091234567',
'<NAME>': '987654321'}
)
def test_pb_parse_input_row(self):
actual = phonebook.pb_parse_input_row('jaska 123456')
self.assertEqual(actual, ('jaska', '123456'))
def test_pb_parse_output_row(self):
actual = phonebook.pb_parse_output_row('jaska jokunen', '123 456')
self.assertEqual(actual, 'jaska jokunen 123 456\n')
def test_pb_create(self):
filename = '_phonebook_create_test_xxxxx.pb'
phonebook.pb_create(filename)
self.assertTrue(os.path.isfile(filename))
os.remove(filename)
self.assertFalse(os.path.isfile(filename))
if __name__ == '__main__':
unittest.main(exit=False)
<file_sep>/README.md
phonebook_py
============
Simple phone book management app. Main purpose to learn python.
<file_sep>/phonebook_handler.py
#!/usr/bin/env python
import argparse
import phonebook
phonebook = phonebook.Phonebook()
# command line handler functions
def handle_rev_lookup(args):
results = phonebook.pb_reverse_lookup(args.number)
if results:
phonebook.print_results(results)
else:
print('No search results for %s' % (args.number))
def handle_lookup(args):
results = phonebook.pb_lookup(args.name)
if results:
phonebook.print_results(results)
else:
print('No search results for %s' % (args.name))
def handle_add(args):
if phonebook.pb_add(args.name, args.number):
print('Added "%s %s to phonebook %s' %
(args.name, args.number, args.phone_file))
phonebook.pb_save(args.phone_file, args.phonebook)
else:
print('A person called %s already in phonebook %s. Changes ignored.' %
(args.name, args.phone_file))
def handle_change(args):
if phonebook.pb_change(args.name, args.number):
print('Change number for "%s" to "%s" in phonebook %s' %
(args.name, args.number, args.phone_file))
phonebook.pb_save(args.phone_file, args.phonebook)
else:
print('No person called %s in phonebook %s. Changes ignored.' %
(args.name, args.phone_file))
def handle_remove(args):
if phonebook.pb_remove(args.name):
print('Removed "%s" from phonebook %s' % (args.name, args.phone_file))
phonebook.pb_save(args.phone_file)
else:
print('No person called %s in phonebook %s. Changes ignored.' %
(args.name, args.phone_file))
def handle_create(args):
phonebook.pb_create(args.name)
"""get argumets, make sure the py file is not the first one."""
parser = argparse.ArgumentParser(description="Manage those phonebooks.")
subparsers = parser.add_subparsers(dest="command")
create_parser = subparsers.add_parser("create", help="Create a new phonebook.")
create_parser.add_argument("phone_file",
help="Name of the phonebook file to create.")
create_parser.set_defaults(func=handle_create)
lookup_parser = subparsers.add_parser("lookup",
help="Lookup a person in a phonebook.")
lookup_parser.add_argument("name", help="name of person to lookup.")
lookup_parser.add_argument("phone_file", help="phonebook to look up in.")
lookup_parser.set_defaults(func=handle_lookup)
add_parser = subparsers.add_parser("add",
help="Add a new person to phonebook.")
add_parser.add_argument("name", help="name of person to add")
add_parser.add_argument("number", help="their number")
add_parser.add_argument("phone_file", help="phonebook to look up in.")
add_parser.set_defaults(func=handle_add)
change_parser = subparsers.add_parser("change",
help="Change someone's phone number.")
change_parser.add_argument("name",
help="name of person whose number to change.")
change_parser.add_argument("number", help="new number")
change_parser.add_argument("phone_file", help="phonebook to change in.")
change_parser.set_defaults(func=handle_change)
remove_parser = subparsers.add_parser("remove",
help="Remove someone.")
remove_parser.add_argument("name", help="name of person to remove.")
remove_parser.add_argument("phone_file", help="phonebook to remove them from.")
remove_parser.set_defaults(func=handle_remove)
rev_lookup_parser = subparsers.add_parser("reverse-lookup",
help="Look someone up by number.")
rev_lookup_parser.add_argument("number", help="number of person to look up.")
rev_lookup_parser.add_argument("phone_file", help="phonebook to lookup in.")
rev_lookup_parser.set_defaults(func=handle_rev_lookup)
if __name__ == "__main__":
args = parser.parse_args()
if args.command != "create":
args.phonebook = phonebook.pb_load(args.phone_file)
args.func(args)
| f8273b02dce86f7ad61c7d27b20002306a7ddb80 | [
"Markdown",
"Python"
] | 4 | Python | marqsm/phonebook_py | 008a41195f0f9983850a389d1570a07123f3a4f0 | 332e2e854d0fbfe80478329d15f331ba7a9b9ee1 |
refs/heads/main | <file_sep>
class Calculator : public AdvancedArithmetic {
public:
int divisorSum(int n) {
int i, sum=0;
for(int i=1;i<=n;i++ ){
if(n%i == 0){
sum+=i;
}
}
return sum;
}
};
<file_sep>
Node* insert(Node *head,int data)
{
//Complete this method
Node** pp = &head; // pp is the pointer to the pointer head
while(*pp) // While head is not null (the content of pp is not null)
pp = &((*pp)->next); // pp receive the address of the pointer to the next node
*pp = new Node(data); // In this moment the content of pp is the address to the last node
return head;
}
<file_sep>
class Student : public Person{
private:
vector<int> testScores;
public:
/*
* Class Constructor
*
* Parameters:
* firstName - A string denoting the Person's first name.
* lastName - A string denoting the Person's last name.
* id - An integer denoting the Person's ID number.
* scores - An array of integers denoting the Person's test scores.
*/
// Write your constructor here
/*
* Function Name: calculate
* Return: A character denoting the grade.
*/
// Write your function here
Student(string firstName,string lastName,int id,vector<int> scores): Person(firstName, lastName, id) {
this->testScores = scores;
}
char calculate(){
double avg = 0.0;
for(int i=0;i<testScores.size();i++)
avg=avg + testScores[i];
avg=avg/testScores.size();
if(avg<40)
return 'T';
else if(avg<55)
return 'D';
else if (avg<70)
return 'P';
else if(avg<80)
return 'A';
else if(avg<90)
return 'E';
else
return 'O';
}
};
<file_sep># 30-days-of-coding-Hackerrank
Here is the solution of all of the 30 problems that comes on the 30-days-of-coding challenge by HackerRank.
# Languages used
I have used cpp and java both, 22 challenges are solved in cpp and 8 challenges are solved in java.
<file_sep>#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cassert>
#include <set>
using namespace std;
int minimum_index(vector<int> seq) {
if (seq.empty()) {
throw invalid_argument("Cannot get the minimum value index from an empty sequence");
}
int min_idx = 0;
for (int i = 1; i < seq.size(); ++i) {
if (seq[i] < seq[min_idx]) {
min_idx = i;
}
}
return min_idx;
}
class TestDataEmptyArray {
public:
static vector<int> get_array() {
// complete this function
vector<int> vect{};
return vect;
}
};
class TestDataUniqueValues {
public:
static vector<int> get_array() {
// complete this function
vector<int> vect{ 23,5,8,12,7 };
return vect;
}
static int get_expected_result() {
// complete this function
return 1;
}
};
class TestDataExactlyTwoDifferentMinimums {
public:
static vector<int> get_array() {
// complete this function
vector<int> vect{ 9,23,3,8,12,3,7 };
return vect;
}
static int get_expected_result() {
// complete this function
return 2;
}
};
<file_sep>#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
int main()
{
int N, i;
cin >> N;
regex exp(".+@gmail\\.com$");
vector<string> strarray;
for(i = 0; i < N; i++)
{
string Fname;
string Eid;
cin >> Fname >> Eid;
if(regex_match(Eid, exp))
{
strarray.push_back(Fname);
}
}
sort(strarray.begin(), strarray.end());
for(i = 0; i < strarray.size();i++)
{
cout << strarray[i] << endl;
}
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
<file_sep>
// Write your MyBook class here
// Class Constructor
//
// Parameters:
// title - The book's title.
// author - The book's author.
// price - The book's price.
//
// Write your constructor here
// Function Name: display
// Print the title, author, and price in the specified format.
//
// Write your method here
// Write your MyBook class here
class MyBook : Book{
int price;
public:
string title;
string author;
MyBook(string title_,string author_,int price_) : Book(title_,author_) ,price(price_){
}
virtual void display(){
cout<<"Title: "<<Book::title<<"\n"<<"Author: "<<Book::author<<"\n"<<"Price: "<<price;
}
};
// End class
| 8ab388a270f98139013bb72d81155fa189bc27e6 | [
"Markdown",
"C++"
] | 7 | C++ | SanjoyChatterjee/30-days-of-coding-Hackerrank | 6985fb47c067fb6d000269fe8ab84445185c9eb5 | 0de2dd1ea517216b006637c86daa7a5629d064e6 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WPFCalculator.ViewModels
{
class CalculatorViewModel : ObservableObject
{
private enum Operation
{
None,
Add,
Subtract,
Multiply,
Divide,
Percent,
Sin,
Cos,
Tan,
Square,
SquareRoot,
Equal
}
private Dictionary<string, Operation> BinaryOperations = new Dictionary<string, Operation>()
{
{ "+", Operation.Add },
{ "-", Operation.Subtract },
{ "*", Operation.Multiply },
{ "/", Operation.Divide },
{ "%", Operation.Percent },
{ "=", Operation.Equal }
};
private Dictionary<string, Operation> UnaryOperations = new Dictionary<string, Operation>()
{
{ "Sin", Operation.Sin },
{ "Cos", Operation.Cos },
{ "Tan", Operation.Tan },
{ "^2", Operation.Square },
{ "SqrRt", Operation.SquareRoot }
};
private static string _operandString;
private static double _operand1;
private static double _operand2;
private string _displayContent;
private string _displayPreviousContent;
private string _displayClearMessage;
public double PreviousAnswer;
private static Operation _binaryOperator;
public ICommand ButtonNumberCommand { get; set; }
public ICommand ButtonOperationCommand { get; set; }
private Operation CurrentOperation { get; set; }
public string DisplayContent
{
get { return _displayContent; }
set
{
_displayContent = value;
OnPropertyChanged("DisplayContent");
}
}
public string DisplayPreviousContent
{
get { return _displayPreviousContent; }
set
{
_displayPreviousContent = value;
OnPropertyChanged("DisplayPreviousContent");
}
}
public string DisplayClearMessage
{
get { return _displayClearMessage; }
set
{
_displayClearMessage = value;
OnPropertyChanged("DisplayClearMessage");
}
}
public CalculatorViewModel()
{
InitializeViewModel();
}
private void InitializeViewModel()
{
_displayContent = "Enter Number";
_displayPreviousContent = "Previous Calculation";
_displayClearMessage = "";
ButtonNumberCommand = new RelayCommand(new Action<object>(UpdateOperandString));
ButtonOperationCommand = new RelayCommand(new Action<object>(SetOperation));
}
private void UpdateOperandString(object obj)
{
//clears the calculation textbox after the user recieves this message and hits a number
if (DisplayContent == "Unknown Operation Occured")
{
_operandString = "";
}
if (obj.ToString() != "CE")
{
DisplayClearMessage = "";
_operandString += obj.ToString();
}
else
{
//variable displays when the last entry is cleared with CE
DisplayClearMessage = "Cleared last entry";
_operandString = "";
}
DisplayContent = _operandString;
}
private Operation CurrentOperator(string operationString)
{
if (BinaryOperations.ContainsKey(operationString))
{
return BinaryOperations[operationString];
}
else if (UnaryOperations.ContainsKey(operationString))
{
return UnaryOperations[operationString];
}
return Operation.None;
}
private void SetOperation(object obj)
{
string displayOperator = "";
Operation operation = CurrentOperator(obj.ToString());
if (double.TryParse(_operandString, out double result))
{
if (BinaryOperations.ContainsValue(operation))
{
if (operation == Operation.Equal)
{
_operand2 = result;
DisplayContent = ProcessBinaryOperation(_binaryOperator).ToString();
//set the displayOperator symbol == to the _binaryOperator word
switch (_binaryOperator)
{
case Operation.Add:
displayOperator = "+";
break;
case Operation.Subtract:
displayOperator = "-";
break;
case Operation.Multiply:
displayOperator = "*";
break;
case Operation.Divide:
displayOperator = "/";
break;
case Operation.Percent:
displayOperator = "%";
break;
default: DisplayContent = "Unknown Operation Occured";
break;
}
//Variable to display in the previous calculation textbox if the user triggers this error
if (DisplayContent == "Unknown Operation Occured")
{
DisplayPreviousContent = DisplayPreviousContent;
}
else
{
DisplayPreviousContent = $"{_operand1}" + $"{displayOperator}" + $"{_operand2}" + "=" + $"{DisplayContent}";
_binaryOperator = Operation.None;
////variable to allow for the if statement on line #233 to work
////Sets the PreviousAnswer = to DisplayContent while it is still the answer to the previous calculation
//PreviousAnswer = double.Parse(DisplayContent);
}
}
else if (operation == Operation.Percent)
{
_operand2 = result;
_binaryOperator = Operation.Percent;
DisplayContent = ProcessBinaryOperation(_binaryOperator).ToString();
}
else
{
_operand1 = result;
_binaryOperator = operation;
_operandString = "";
DisplayContent = "";
}
}
else if (UnaryOperations.ContainsValue(operation))
{
_operand1 = result;
DisplayContent = ProcessUnaryOperation(operation).ToString();
//allows the Previous Calculation box to display ^2
if (operation == Operation.Square)
{
DisplayPreviousContent = $"{_operand1}^2 = {DisplayContent}";
}
//allows the Previous Calculation box to disply SqRt
else if (operation == Operation.SquareRoot)
{
DisplayPreviousContent = $"√{_operand1} = {DisplayContent}";
}
//displays sin,cos,tan in Previous Calculation box
else
{
DisplayPreviousContent = $"{operation}(" + $"{_operandString}) = {DisplayContent}";
}
}
else
{
DisplayContent = "Unknown Operation Encountered";
}
}
else
{
DisplayContent = "Please enter a valid number.";
}
}
private double ProcessUnaryOperation(Operation operation)
{
switch (operation)
{
case Operation.Sin:
return Math.Sin(_operand1);
case Operation.Cos:
return Math.Cos(_operand1);
case Operation.Tan:
return Math.Tan(_operand1);
case Operation.Square:
return Math.Pow(_operand1, 2);
case Operation.SquareRoot:
return Math.Sqrt(_operand1);
default:
DisplayContent = "Unknown Operation Encountered";
return 0;
}
}
private double ProcessBinaryOperation(Operation operation)
{
////allows for user to do Answer *operation* _operand
//if (_displayPreviousContent != "Previous Calculation")
//{
// _operand1 = PreviousAnswer;
//}
switch (operation)
{
case Operation.Add:
return _operand1 + _operand2;
case Operation.Subtract:
return _operand1 - _operand2;
case Operation.Multiply:
return _operand1 * _operand2;
case Operation.Divide:
return _operand1 / _operand2;
case Operation.Percent:
return _operand1 * (_operand2 / 100);
default:
DisplayContent = "Unknown Operation Encountered";
return 0;
}
}
}
}
| a3804c7ccdd37e4ea22c94015beb4145bda54967 | [
"C#"
] | 1 | C# | TRabb/WPFCalculator | 4a75c86ab8b9586c69baa6be68a4325ccb9d2fdf | 8e80bcb134b0ee66c4c95ae416bace0204ae819f |
refs/heads/master | <repo_name>Galaco/gosigl<file_sep>/general.go
package gosigl
import (
opengl "github.com/go-gl/gl/v4.1-core/gl"
)
const Front = opengl.FRONT
const Back = opengl.BACK
const FrontAndBack = opengl.FRONT_AND_BACK
const DepthTestLEqual = opengl.LEQUAL
const WindingClockwise = opengl.CW
const WindingCounterClockwise = opengl.CCW
const MaskColourBufferBit = opengl.COLOR_BUFFER_BIT
const MaskDepthBufferBit = opengl.DEPTH_BUFFER_BIT
func ClearColour(red float32, green float32, blue float32, alpha float32) {
opengl.ClearColor(red, green, blue, alpha)
}
func Clear(bufferBits ...uint32) {
mask := uint32(0)
for _,buf := range bufferBits {
mask = mask | buf
}
opengl.Clear(mask)
}
func EnableBlend() {
opengl.Enable(opengl.BLEND)
opengl.BlendFunc(opengl.SRC_ALPHA, opengl.ONE_MINUS_SRC_ALPHA)
}
func DisableBlend(){
opengl.Disable(opengl.BLEND)
}
func EnableDepthTest() {
opengl.Enable(opengl.DEPTH_TEST)
opengl.DepthFunc(opengl.LEQUAL)
}
func DisableDepthTest() {
opengl.Disable(opengl.DEPTH_TEST)
}
func EnableCullFace(cullSide uint32, winding uint32) {
opengl.Enable(opengl.CULL_FACE)
opengl.CullFace(cullSide)
opengl.FrontFace(winding)
}<file_sep>/README.md
# Gosigl
Gosigl (Go SImple openGL) is an somewhat opinionated Go wrapper for OpenGL with emphasis on simple. It's purpose is to make creating simple OpenGL programs really goddamn
easy. It doesn't provide a whole lot of functionality, but it's really quick and simple to get a basic renderable
world up and running.
It provides simplified functions for creating textures, VAO and VBOs, and shader objects.
#### Texture
Provides functions for creating and binding Texture2D and Cube_Map_Textures.
Creating and binding a Texture2D can be done as follows:
```go
buf := gosigl.CreateTexture2D(
gosigl.TextureSlot(0), // Assign texture slot
width, // texture width
height, // texture height
pixelData, // []byte raw colour data
gosigl.RGB, // colour data format
false) // true = clamp to edge, false = repeat
gosigl.BindTexture2D(gosigl.TextureSlot(0), buf)
```
Cubemaps are very similar:
```go
buf := gosigl.CreateTextureCubemap(
gosigl.TextureSlot(0), // Assign texture slot
width, // texture width
height, // texture height
pixelData, // [6][]byte raw colour data
gosigl.RGB, // colour data format
true)
gosigl.BindTextureCubemap(gosigl.TextureSlot(0), buf)
```
#### Mesh
Simple methods are available for VBO and VAO generation, as follows:
```go
mesh := gosigl.NewMesh(vertices) // vertices = []float32
gosigl.CreateVertexAttribute(mesh, uvs, 2) // uvs = []float32, 2 = numPerVertex
gosigl.CreateVertexAttribute(mesh, normals, 3)
gosigl.FinishMesh()
```
To draw:
```go
gosigl.BindMesh(mesh) // bind vbo
gosigl.DrawArray(offset, length) // draw from bound
```
To delete:
```go
gosigl.DeleteMesh(mesh)
```
#### Shader
@Incomplete
<file_sep>/shader.go
package gosigl
import (
"fmt"
opengl "github.com/go-gl/gl/v4.1-core/gl"
"strings"
)
type ShaderType uint32
const VertexShader = ShaderType(opengl.VERTEX_SHADER)
const FragmentShader = ShaderType(opengl.FRAGMENT_SHADER)
type Context struct {
context uint32
}
func (ctx *Context) Id() uint32 {
return ctx.context
}
func (ctx *Context) AddShader(source string, shaderType ShaderType) error {
shader, err := ctx.compileShader(source, shaderType)
if err != nil {
return err
}
opengl.AttachShader(ctx.context, shader)
return nil
}
func (ctx *Context) Finalize() {
opengl.LinkProgram(ctx.context)
}
func (ctx *Context) UseProgram() {
opengl.UseProgram(ctx.context)
}
func (ctx *Context) GetUniform(name string) int32 {
return opengl.GetUniformLocation(ctx.context, opengl.Str(name+"\x00"))
}
func (ctx *Context) compileShader(source string, shaderType ShaderType) (uint32, error) {
shader := opengl.CreateShader(uint32(shaderType))
csources, free := opengl.Strs(source)
opengl.ShaderSource(shader, 1, csources, nil)
free()
opengl.CompileShader(shader)
var status int32
opengl.GetShaderiv(shader, opengl.COMPILE_STATUS, &status)
if status == opengl.FALSE {
var logLength int32
opengl.GetShaderiv(shader, opengl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
opengl.GetShaderInfoLog(shader, logLength, nil, opengl.Str(log))
return 0, fmt.Errorf("failed to compile %v: %v", source, log)
}
return shader, nil
}
func (ctx *Context) Destroy() {
opengl.DeleteShader(ctx.Id())
}
func NewShader() Context {
if err := opengl.Init(); err != nil {
panic(err)
}
context := Context{
context: opengl.CreateProgram(),
}
return context
}
<file_sep>/mesh.go
package gosigl
import (
opengl "github.com/go-gl/gl/v4.1-core/gl"
"math"
)
type VertexBufferObject uint32
type VertexArrayObject uint32
type ElementArrayObject uint32
type VertexObject struct {
Id VertexBufferObject
AttribId [32]VertexArrayObject
attribStride [32]int
numAttributes int
elementArrayBuffer ElementArrayObject
}
const Line = uint32(opengl.LINE)
const Triangles = uint32(opengl.TRIANGLES)
var vertexDrawMode = Triangles
func SetLineWidth(width float32) {
opengl.LineWidth(width)
}
func SetVertexDrawMode(drawMode uint32) {
vertexDrawMode = drawMode
}
func DrawArray(offset int, length int) {
opengl.DrawArrays(vertexDrawMode, int32(offset), int32(length))
}
func DrawElements(count int, offset int, indices []uint32) {
if offset > 0 {
opengl.DrawElements(opengl.TRIANGLES, int32(count), opengl.UNSIGNED_INT, opengl.Ptr(indices[offset]))
} else {
opengl.DrawElements(opengl.TRIANGLES, int32(count), opengl.UNSIGNED_INT, opengl.Ptr(nil))
}
}
func NewMesh(vertices []float32) (mesh *VertexObject) {
mesh = &VertexObject{
numAttributes: 0,
elementArrayBuffer: math.MaxUint32,
}
vbo := uint32(0)
opengl.GenBuffers(1, &vbo)
opengl.BindBuffer(opengl.ARRAY_BUFFER, vbo)
opengl.BufferData(opengl.ARRAY_BUFFER, 4*len(vertices), opengl.Ptr(vertices), opengl.STATIC_DRAW)
mesh.Id = VertexBufferObject(vbo)
// vao
vao := uint32(0)
opengl.GenVertexArrays(1, &vao)
opengl.BindVertexArray(vao)
opengl.EnableVertexAttribArray(0)
opengl.BindBuffer(opengl.ARRAY_BUFFER, vbo)
opengl.VertexAttribPointer(0, 3, opengl.FLOAT, false, 0, nil)
mesh.AttribId[mesh.numAttributes] = VertexArrayObject(vao)
mesh.attribStride[mesh.numAttributes] = 3
mesh.numAttributes++
return mesh
}
func BindMesh(mesh *VertexObject) {
BindVertexAttributes(mesh)
}
// CreateVertexAttribute creates a vertex array attribute
func CreateVertexAttribute(mesh *VertexObject, bufferData []float32, stride int) {
buffer := uint32(0)
opengl.GenBuffers(1, &buffer)
opengl.BindBuffer(opengl.ARRAY_BUFFER, buffer)
opengl.BufferData(opengl.ARRAY_BUFFER, len(bufferData)*4, opengl.Ptr(bufferData), opengl.STATIC_DRAW)
mesh.AttribId[mesh.numAttributes] = VertexArrayObject(buffer)
mesh.attribStride[mesh.numAttributes] = stride
mesh.numAttributes++
}
func CreateVertexAttributeArrayBuffer(mesh *VertexObject, bufferData []float32, stride int) {
CreateVertexAttribute(mesh, bufferData, stride)
}
func SetElementArrayAttribute(mesh *VertexObject, bufferData []uint32) {
buffer := uint32(0)
opengl.GenBuffers(1, &buffer)
opengl.BindBuffer(opengl.ELEMENT_ARRAY_BUFFER, buffer)
opengl.BufferData(opengl.ELEMENT_ARRAY_BUFFER, len(bufferData)*4, opengl.Ptr(bufferData), opengl.STATIC_DRAW)
mesh.elementArrayBuffer = ElementArrayObject(buffer)
}
func BindVertexAttributes(mesh *VertexObject) {
opengl.BindVertexArray(uint32(mesh.AttribId[0]))
opengl.EnableVertexAttribArray(0)
for i := 1; i < mesh.numAttributes; i++ {
opengl.EnableVertexAttribArray(uint32(i))
opengl.BindBuffer(opengl.ARRAY_BUFFER, uint32(mesh.AttribId[i]))
opengl.VertexAttribPointer(uint32(i), int32(mesh.attribStride[i]), opengl.FLOAT, false, 0, nil)
}
if mesh.elementArrayBuffer != math.MaxUint32 {
opengl.BindBuffer(opengl.ELEMENT_ARRAY_BUFFER, uint32(mesh.elementArrayBuffer))
}
}
func FinishMesh() {
opengl.BindVertexArray(0)
}
func DeleteMesh(mesh *VertexObject) {
vao := uint32(mesh.AttribId[0])
opengl.DeleteVertexArrays(1, &vao)
for i := 1; i < mesh.numAttributes; i++ {
buf := uint32(mesh.AttribId[1])
opengl.DeleteBuffers(1, &buf)
}
}<file_sep>/go.mod
module github.com/galaco/gosigl
go 1.13
require github.com/go-gl/gl v0.0.0-20211210172815-726fda9656d6
<file_sep>/texture.go
package gosigl
import (
opengl "github.com/go-gl/gl/v4.1-core/gl"
)
type TextureBindingId uint32
type TextureSlotId uint32
type PixelFormat uint32
const RGBA = PixelFormat(opengl.RGBA)
const RGB = PixelFormat(opengl.RGB)
const BGR = PixelFormat(opengl.BGR)
const BGRA = PixelFormat(opengl.BGRA)
const DXT1 = PixelFormat(opengl.COMPRESSED_RGB_S3TC_DXT1_EXT)
const DXT1A = PixelFormat(opengl.COMPRESSED_RGBA_S3TC_DXT1_EXT)
const DXT3 = PixelFormat(opengl.COMPRESSED_RGBA_S3TC_DXT3_EXT)
const DXT5 = PixelFormat(opengl.COMPRESSED_RGBA_S3TC_DXT5_EXT)
var textureSlots = [...]TextureSlotId{
opengl.TEXTURE0,
opengl.TEXTURE1,
opengl.TEXTURE2,
opengl.TEXTURE3,
opengl.TEXTURE4,
opengl.TEXTURE5,
opengl.TEXTURE6,
opengl.TEXTURE7,
opengl.TEXTURE8,
opengl.TEXTURE9,
opengl.TEXTURE10,
opengl.TEXTURE11,
opengl.TEXTURE12,
opengl.TEXTURE13,
opengl.TEXTURE14,
opengl.TEXTURE15,
opengl.TEXTURE16,
opengl.TEXTURE17,
opengl.TEXTURE18,
opengl.TEXTURE19,
opengl.TEXTURE20,
opengl.TEXTURE21,
opengl.TEXTURE22,
opengl.TEXTURE23,
opengl.TEXTURE24,
opengl.TEXTURE25,
opengl.TEXTURE26,
opengl.TEXTURE27,
opengl.TEXTURE28,
opengl.TEXTURE29,
opengl.TEXTURE30,
opengl.TEXTURE31,
}
var cubemapSlots = [...]TextureSlotId{
opengl.TEXTURE_CUBE_MAP_POSITIVE_X,
opengl.TEXTURE_CUBE_MAP_NEGATIVE_X,
opengl.TEXTURE_CUBE_MAP_POSITIVE_Y,
opengl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
opengl.TEXTURE_CUBE_MAP_POSITIVE_Z,
opengl.TEXTURE_CUBE_MAP_NEGATIVE_Z,
}
func TextureSlot(index int) TextureSlotId {
if index > 31 {
return textureSlots[0]
}
return textureSlots[index]
}
func BindTexture2D(slot TextureSlotId, id TextureBindingId) {
opengl.ActiveTexture(uint32(slot))
opengl.BindTexture(opengl.TEXTURE_2D, uint32(id))
}
func BindTextureCubemap(slot TextureSlotId, id TextureBindingId) {
opengl.ActiveTexture(uint32(slot))
opengl.BindTexture(opengl.TEXTURE_CUBE_MAP, uint32(id))
}
func CreateTexture2D(slot TextureSlotId, width int, height int, pixelData []byte, pixelFormat PixelFormat, clampToEdge bool) TextureBindingId {
textureBuffer := uint32(0)
opengl.GenTextures(1, &textureBuffer)
BindTexture2D(slot, TextureBindingId(textureBuffer))
createTexture(opengl.TEXTURE_2D, opengl.TEXTURE_2D, width, height, pixelData, pixelFormat, clampToEdge)
return TextureBindingId(textureBuffer)
}
func CreateTextureCubemap(slot TextureSlotId, width int, height int, pixelData [6][]byte, pixelFormat PixelFormat, clampToEdge bool) TextureBindingId {
textureBuffer := uint32(0)
opengl.GenTextures(1, &textureBuffer)
BindTextureCubemap(slot, TextureBindingId(textureBuffer))
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[0], width, height, pixelData[0], pixelFormat, clampToEdge)
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[1], width, height, pixelData[1], pixelFormat, clampToEdge)
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[2], width, height, pixelData[2], pixelFormat, clampToEdge)
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[3], width, height, pixelData[3], pixelFormat, clampToEdge)
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[4], width, height, pixelData[4], pixelFormat, clampToEdge)
createTexture(opengl.TEXTURE_CUBE_MAP, cubemapSlots[5], width, height, pixelData[5], pixelFormat, clampToEdge)
return TextureBindingId(textureBuffer)
}
func createTexture(textureType uint32, target TextureSlotId, width int, height int, pixelData []byte, pixelFormat PixelFormat, clampToEdge bool) {
opengl.TexParameteri(textureType, opengl.TEXTURE_MIN_FILTER, opengl.LINEAR)
opengl.TexParameteri(textureType, opengl.TEXTURE_MAG_FILTER, opengl.LINEAR)
if clampToEdge == true {
opengl.TexParameteri(textureType, opengl.TEXTURE_WRAP_S, opengl.CLAMP_TO_EDGE)
opengl.TexParameteri(textureType, opengl.TEXTURE_WRAP_T, opengl.CLAMP_TO_EDGE)
} else {
opengl.TexParameteri(textureType, opengl.TEXTURE_WRAP_S, opengl.REPEAT)
opengl.TexParameteri(textureType, opengl.TEXTURE_WRAP_T, opengl.REPEAT)
}
if isPixelFormatCompressed(pixelFormat) {
opengl.CompressedTexImage2D(
uint32(target),
0,
uint32(pixelFormat),
int32(width),
int32(height),
0,
int32(len(pixelData)),
opengl.Ptr(pixelData))
} else {
opengl.TexImage2D(
uint32(target),
0,
opengl.RGBA,
int32(width),
int32(height),
0,
uint32(pixelFormat),
opengl.UNSIGNED_BYTE,
opengl.Ptr(pixelData))
}
}
func DeleteTextures(ids ...TextureBindingId) {
rawIds := make([]uint32, len(ids))
for idx, id := range ids {
rawIds[idx] = uint32(id)
}
opengl.DeleteTextures(int32(len(rawIds)), &rawIds[0])
}
func isPixelFormatCompressed(format PixelFormat) bool {
switch format {
case DXT1, DXT1A, DXT3, DXT5:
return true
}
return false
} | 5f01ae832351fd38401295dad8d0d47c259c3d8b | [
"Markdown",
"Go Module",
"Go"
] | 6 | Go | Galaco/gosigl | 1302a0b2ab5c35f0924e1ac1d984dc754adb0a4a | 24ed1e5d48f79397fb00d759a4939547557519eb |
refs/heads/master | <file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/customers/customers_list.html'
})
export class CustomersListComponent {
public pageTitle: string = "Customers";
}
<file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/product_info/product_info.html',
})
export class ProductInfoComponent {
public pageTitle: string = "Product Info";
}
<file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/customers/customers_feedbacks.html'
})
export class CustomersFeedbacksComponent {
public pageTitle: string = "Customers Feedbacks";
}
<file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/product_info/video_presentations.html'
})
export class VideoPresentationsComponent {
public pageTitle: string = "Video Presentations";
}
<file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/contact_us/contact_us_cur_location.html'
})
export class ContactUsComponent {
public pageTitle: string = "Contact Us";
}
<file_sep>/**
* Created by AlexB on 2016-10-05.
*/
import { Component } from 'angular2/core';
@Component({
templateUrl: 'app/home/bs4u_home.html'
})
export class HomeComponent {
public pageTitle: string = "bs4u_home";
}
<file_sep>Project - BS4U
BS4U - Best Solution For You - Site
Technologies Used:
HTML5, CSS3, Bootstrap3 , JavaScript, Angular2
<file_sep>
import { Component } from 'angular2/core';
//import {Routes} from 'angular2/router';
import { HTTP_PROVIDERS } from 'angular2/http';
import 'rxjs/Rx';
import { ROUTER_PROVIDERS, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import { HomeComponent } from './home/home.component';
import { CustomersListComponent } from './customers/customersList.component';
import { CustomersFeedbacksComponent } from './customers/customersFeedbacks.component';
import { ContactUsComponent } from './contact_us/contactus.component';
import { ProductInfoComponent } from './product_info/productInfo.component';
import { VideoPresentationsComponent } from './product_info/video_presentations.component';
@Component({
selector:'bs4u-app',
templateUrl: 'app/main.html',
styleUrls: ['app/css/style.css'],
directives: [HomeComponent, ROUTER_DIRECTIVES],
providers: [
HomeComponent,
CustomersListComponent,
CustomersFeedbacksComponent,
ContactUsComponent,
ProductInfoComponent,
VideoPresentationsComponent,
HTTP_PROVIDERS,
ROUTER_PROVIDERS]
})
@RouteConfig([
{ path: '/home', name: 'Home', component: HomeComponent, useAsDefault: true },
{ path: '/customersList', name: 'CustomersList', component: CustomersListComponent },
{ path: '/customersFeedbacks', name: 'CustomersFeedbacks', component: CustomersFeedbacksComponent },
{ path: '/contuctUs', name: 'ContuctUs', component: ContactUsComponent },
{ path: '/productInfo', name: 'ProductInfo', component: ProductInfoComponent },
{ path: '/videoPresentations', name: 'VideoPresentations', component: VideoPresentationsComponent }
])
export class AppComponent {
pageTitle: string = 'Main Page Title';
} | cec8f7b3d94cd2c575c3973a935abedad77145f6 | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | AlexBrs/BS4U | bd01d2486681f70893ae231b41400ef03e90b3be | 8e6f8a154eb2f48403debed15682f738f1d23666 |
refs/heads/master | <file_sep>package com.ossjk.asset.car.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.car.entity.Car_receive;
import com.ossjk.asset.car.vo.Car_receiveVo;
/**
* <p>
* 车辆领用表 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface ICar_receiveService extends IService<Car_receive> {
public Page selectCar_receiveVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.device.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.device.entity.Device_scrap;
/**
* <p>
* 设备报废 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Device_scrapMapper extends BaseMapper<Device_scrap> {
List<Device_scrap> selectDevice_scrapVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.book.service;
import com.ossjk.asset.book.entity.Furniture_books_receive;
import com.ossjk.asset.book.vo.Furniture_books_receiveVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 家具图书领用表 服务类
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface IFurniture_books_receiveService extends IService<Furniture_books_receive> {
Page selectFurniture_books_receiveVo(Page page, @Param("ew") Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.system.vo;
import com.ossjk.asset.system.entity.Role_permission;
public class Role_permissionVo extends Role_permission {
private String rName;
private String pName;
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
<file_sep>package com.ossjk.asset.car.vo;
import com.ossjk.asset.car.entity.Car_receive;
public class Car_receiveVo extends Car_receive {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
private String recipientsNAME;
public String getRecipientsNAME() {
return recipientsNAME;
}
public void setRecipientsNAME(String recipientsNAME) {
this.recipientsNAME = recipientsNAME;
}
}
<file_sep>/*==============================================================*/
/* DBMS name: MySQL 5.0 */
/* Created on: 2020/1/13 19:18:30 */
/*==============================================================*/
drop table if exists car;
drop table if exists car_receive;
drop table if exists car_repair;
drop table if exists car_scrap;
drop table if exists car_type;
drop table if exists code_rule;
drop table if exists device;
drop table if exists device_receive;
drop table if exists device_repair;
drop table if exists device_scrap;
drop table if exists device_type;
drop table if exists dictionary;
drop table if exists furniture_book;
drop table if exists furniture_books_receive;
drop table if exists furniture_books_repair;
drop table if exists furniture_books_scrap;
drop table if exists furniture_books_type;
drop table if exists house;
drop table if exists house_receive;
drop table if exists land;
drop table if exists land_receive;
drop table if exists organization;
drop table if exists permission;
drop table if exists role;
drop table if exists role_permission;
drop table if exists user;
/*==============================================================*/
/* Table: car */
/*==============================================================*/
create table car
(
id varchar(32) not null,
ctid varchar(32) comment '车辆类型id',
code varchar(7) comment '车辆流水号',
residualrate numeric(3,3) comment '净残值率',
useyear numeric(2,0) comment '使用年限',
residual numeric(16,2) comment '净值',
original numeric(16,2) comment '原值',
status numeric(2,0) comment '状态 1-入库、2-出库中、3-出库、4-领用、5-报修',
proddate varchar(32) comment '生产日期',
creator varchar(32) comment '登记人',
createtime varchar(32) comment '登记时间',
buyer varchar(32) comment '购买人',
bugdate varchar(32) comment '购买日期',
sno varchar(32) comment '序列号',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table car comment '车辆明细';
/*==============================================================*/
/* Table: car_receive */
/*==============================================================*/
create table car_receive
(
id varchar(32) not null,
cid varchar(32) comment '车辆id',
receipt varchar(9) comment '单据号',
recipients varchar(32) comment '领用人',
receivedate varchar(32) comment '领取时间',
returndate varchar(32) comment '归还日期',
status numeric(1,0) comment '状态 1-领用、2-归还',
receiveremarks varchar(200) comment '领用备注',
returnremarks varchar(200) comment '归还备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table car_receive comment '车辆领用表';
/*==============================================================*/
/* Table: car_repair */
/*==============================================================*/
create table car_repair
(
id varchar(32) not null,
cid varchar(32) comment '车辆id',
damager varchar(32) comment '报修人',
damagedate varchar(32) comment '报修时间',
damageremarks varchar(200) comment '报修备注',
repairdate varchar(32) comment '维修时间',
repairer varchar(32) comment '维修人',
repairremarks varchar(200) comment '维修备注',
status numeric(1,0) comment '状态 1-报修、2-维修',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table car_repair comment '车辆维修表';
/*==============================================================*/
/* Table: car_scrap */
/*==============================================================*/
create table car_scrap
(
id varchar(32) not null,
cid varchar(32) comment '车辆id',
scraper varchar(32) comment '报废人',
scraperdate varchar(32) comment '报废日期',
scrapremarks varchar(200) comment '报废备注',
status numeric(1,0) comment '状态 1-申请、2-准许、3-拒绝',
approver varchar(32) comment '审批人',
approvalremarks varchar(200) comment '审批意见',
approvaldate varchar(32) comment '申请日期',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table car_scrap comment '车辆报废';
/*==============================================================*/
/* Table: car_type */
/*==============================================================*/
create table car_type
(
id varchar(32) not null,
name varchar(50) comment '名字',
brand varchar(100) comment '品牌',
intlcode varchar(100) comment '国际编号',
model varchar(100) comment '型号',
specifications varchar(100) comment '规格',
remarks varchar(200) comment '备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table car_type comment '车辆类型';
/*==============================================================*/
/* Table: code_rule */
/*==============================================================*/
create table code_rule
(
id varchar(32) not null,
name varchar(50) comment '名字',
rule varchar(50) comment '规则表达式',
current varchar(300) comment '当前流水号',
remarks varchar(200) comment '备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table code_rule comment '流水号规则表';
/*==============================================================*/
/* Table: device */
/*==============================================================*/
create table device
(
id varchar(32) not null,
dtid varchar(32) comment '设备类型id',
code varchar(7) comment '设备流水号',
residualrate numeric(3,3) comment '净残值率',
useyear numeric(2,0) comment '使用年限',
residual numeric(16,2) comment '净值',
original numeric(16,2) comment '原值',
status numeric(2,0) comment '状态 1-入库、2-出库中、3-出库、4-领用、5-报修',
proddate varchar(32) comment '生产日期',
creator varchar(32) comment '登记人',
createtime varchar(32) comment '登记时间',
buyer varchar(32) comment '购买人',
bugdate varchar(32) comment '购买日期',
sno varchar(32) comment '序列号',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table device comment '设备明细';
/*==============================================================*/
/* Table: device_receive */
/*==============================================================*/
create table device_receive
(
id varchar(32) not null,
did varchar(32) comment '设备id',
receipt varchar(9) comment '单据号',
recipients varchar(32) comment '领用人',
receivedate varchar(32) comment '领取时间',
returndate varchar(32) comment '归还日期',
status numeric(1,0) comment '状态 1-领用、2-归还',
receiveremarks varchar(200) comment '领用备注',
returnremarks varchar(200) comment '归还备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table device_receive comment '设备领用表';
/*==============================================================*/
/* Table: device_repair */
/*==============================================================*/
create table device_repair
(
id varchar(32) not null,
did varchar(32) comment '设备id',
damager varchar(32) comment '报修人',
damagedate varchar(32) comment '报修时间',
damageremarks varchar(200) comment '报修备注',
repairdate varchar(32) comment '维修时间',
repairer varchar(32) comment '维修人',
repairremarks varchar(200) comment '维修备注',
status numeric(1,0) comment '状态 1-报修、2-维修',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table device_repair comment '设备维修表';
/*==============================================================*/
/* Table: device_scrap */
/*==============================================================*/
create table device_scrap
(
id varchar(32) not null,
did varchar(32) comment '设备id',
scraper varchar(32) comment '报废人',
scraperdate varchar(32) comment '报废日期',
scrapremarks varchar(200) comment '报废备注',
status numeric(1,0) comment '状态 1-申请、2-准许、3-拒绝',
approver varchar(32) comment '审批人',
approvalremarks varchar(200) comment '审批意见',
approvaldate varchar(32) comment '申请日期',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table device_scrap comment '设备报废';
/*==============================================================*/
/* Table: device_type */
/*==============================================================*/
create table device_type
(
id varchar(32) not null,
name varchar(50) comment '名字',
brand varchar(100) comment '品牌',
intlcode varchar(100) comment '国际编号',
model varchar(100) comment '型号',
remarks varchar(200) comment '备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table device_type comment '设备类型';
/*==============================================================*/
/* Table: dictionary */
/*==============================================================*/
create table dictionary
(
id varchar(32) not null,
dkey varchar(50) comment '键',
dvalue varchar(500) comment '值',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table dictionary comment '数据字典';
/*==============================================================*/
/* Table: furniture_book */
/*==============================================================*/
create table furniture_book
(
id varchar(32) not null,
fbtid varchar(32) comment '家具图书类型id',
code varchar(7) comment '家具图书流水号',
name varchar(50) comment '名字',
residualrate numeric(3,3) comment '净残值率',
useyear numeric(2,0) comment '使用年限',
residual numeric(16,2) comment '净值',
original numeric(16,2) comment '原值',
status numeric(2,0) comment '状态 1-入库、2-出库中、3-出库、4-领用、5-报修',
proddate varchar(32) comment '生产日期',
creator varchar(32) comment '登记人',
createtime varchar(32) comment '登记时间',
buyer varchar(32) comment '购买人',
bugdate varchar(32) comment '购买日期',
sno varchar(32) comment '序列号',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table furniture_book comment '家具图书明细';
/*==============================================================*/
/* Table: furniture_books_receive */
/*==============================================================*/
create table furniture_books_receive
(
id varchar(32) not null,
fbid varchar(32) comment '家具图书id',
receipt varchar(9) comment '单据号',
recipients varchar(32) comment '领用人',
receivedate varchar(32) comment '领取时间',
returndate varchar(32) comment '归还日期',
status numeric(1,0) comment '状态 1-领用、2-归还',
receiveremarks varchar(200) comment '领用备注',
returnremarks varchar(200) comment '归还备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table furniture_books_receive comment '家具图书领用表';
/*==============================================================*/
/* Table: furniture_books_repair */
/*==============================================================*/
create table furniture_books_repair
(
id varchar(32) not null,
fbid varchar(32) comment '家具图书id',
damager varchar(32) comment '报修人',
damagedate varchar(32) comment '报修时间',
damageremarks varchar(200) comment '报修备注',
repairdate varchar(32) comment '维修时间',
repairer varchar(32) comment '维修人',
repairremarks varchar(200) comment '维修备注',
status numeric(1,0) comment '状态 1-报修、2-维修',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table furniture_books_repair comment '家具图书维修表';
/*==============================================================*/
/* Table: furniture_books_scrap */
/*==============================================================*/
create table furniture_books_scrap
(
id varchar(32) not null,
fbid varchar(32) comment '家具图书id',
scraper varchar(32) comment '报废人',
scraperdate varchar(32) comment '报废日期',
scrapremarks varchar(200) comment '报废备注',
status numeric(1,0) comment '状态 1-申请、2-准许、3-拒绝',
approver varchar(32) comment '审批人',
approvalremarks varchar(200) comment '审批意见',
approvaldate varchar(32) comment '申请日期',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table furniture_books_scrap comment '家具图书报废';
/*==============================================================*/
/* Table: furniture_books_type */
/*==============================================================*/
create table furniture_books_type
(
id varchar(32) not null,
type int(1) comment '类型:1、家具 2、图书',
name varchar(50) comment '名字',
brand varchar(100) comment '品牌/出版社',
intlcode varchar(100) comment '国际编号',
remarks varchar(200) comment '备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table furniture_books_type comment '家具图书类型';
/*==============================================================*/
/* Table: house */
/*==============================================================*/
create table house
(
id varchar(32) not null,
owner varchar(100) comment '屋主
',
property varchar(100) comment '房屋性质',
address varchar(100) comment '房屋位置
',
area double(10,4) comment '房屋面积
',
service_life varchar(20) comment '使用期限
',
remarks varchar(200) comment '备注信息',
status int comment '房屋状态:0、闲置 1、已分配 2、其他',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table house comment '房屋明细';
/*==============================================================*/
/* Table: house_receive */
/*==============================================================*/
create table house_receive
(
id varchar(32) not null,
hid varchar(32) comment '房屋id
',
oid varchar(32) comment '分配单位
',
creator varchar(32) comment '登记用户',
remarks varchar(200) comment '备注
',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table house_receive comment '房屋分配情况';
/*==============================================================*/
/* Table: land */
/*==============================================================*/
create table land
(
id varchar(32) not null,
property varchar(100) comment '土地性质',
address varchar(100) comment '土地位置
',
area double(10,4) comment '土地面积
',
service_life varchar(20) comment '使用期限
',
remarks varchar(200) comment '备注信息',
status int comment '土地状态:0、闲置 1、已分配 2、其他',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table land comment '土地明细';
/*==============================================================*/
/* Table: land_receive */
/*==============================================================*/
create table land_receive
(
id varchar(32) not null,
lid varchar(32) comment '土地编号
',
oid varchar(32) comment '分配单位
',
creator varchar(32) comment '登记用户',
remarks varchar(200) comment '备注
',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table land_receive comment '土地分配情况';
/*==============================================================*/
/* Table: organization */
/*==============================================================*/
create table organization
(
id varchar(32) not null,
pid varchar(32) comment '父级id',
name varchar(50) comment '名字',
remarks varchar(200) comment '备注',
sort numeric comment '排序',
level numeric comment '等级',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table organization comment '组织机构';
/*==============================================================*/
/* Table: permission */
/*==============================================================*/
create table permission
(
id varchar(32) not null,
pid varchar(32) comment '父级id',
name varchar(50) comment '名字',
url varchar(500) comment 'url',
sort numeric(8,0) comment '序号',
remarks varchar(200) comment '备注',
level numeric comment '等级',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table permission comment '权限';
/*==============================================================*/
/* Table: role */
/*==============================================================*/
create table role
(
id varchar(32) not null,
name varchar(50) comment '名字',
remarks varchar(200) comment '备注',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table role comment '角色';
/*==============================================================*/
/* Table: role_permission */
/*==============================================================*/
create table role_permission
(
id varchar(32) not null,
rid varchar(32) comment '角色id',
pid varchar(32) comment '权限id',
primary key (id)
);
alter table role_permission comment '角色权限中间表';
/*==============================================================*/
/* Table: user */
/*==============================================================*/
create table user
(
id varchar(32) not null,
rid varchar(32) comment '角色id',
ogid varchar(32) comment '组织机构id',
name varchar(50) comment '姓名',
pwd varchar(50) comment '密码',
sex numeric(8,0) comment '性别 1-男、2-女',
birth varchar(20) comment '生日',
phone varchar(11) comment '手机',
email varchar(500) comment '邮件',
logintime varchar(20) comment '登录时间',
loginip varchar(500) comment '登录ip',
crtm varchar(32) comment '创建时间',
mdtm varchar(32) comment '修改时间',
primary key (id)
);
alter table user comment '用户';
alter table car add constraint FK_Reference_10 foreign key (buyer)
references user (id) on delete restrict on update restrict;
alter table car add constraint FK_Reference_5 foreign key (ctid)
references car_type (id) on delete restrict on update restrict;
alter table car add constraint FK_Reference_9 foreign key (creator)
references user (id) on delete restrict on update restrict;
alter table car_receive add constraint FK_Reference_6 foreign key (cid)
references car (id) on delete restrict on update restrict;
alter table car_repair add constraint FK_Reference_7 foreign key (cid)
references car (id) on delete restrict on update restrict;
alter table car_scrap add constraint FK_Reference_8 foreign key (cid)
references car (id) on delete restrict on update restrict;
alter table device add constraint FK_Reference_11 foreign key (creator)
references user (id) on delete restrict on update restrict;
alter table device add constraint FK_Reference_12 foreign key (buyer)
references user (id) on delete restrict on update restrict;
alter table device add constraint FK_Reference_13 foreign key (dtid)
references device_type (id) on delete restrict on update restrict;
alter table device_receive add constraint FK_Reference_14 foreign key (did)
references device (id) on delete restrict on update restrict;
alter table device_repair add constraint FK_Reference_16 foreign key (did)
references device (id) on delete restrict on update restrict;
alter table device_scrap add constraint FK_Reference_15 foreign key (did)
references device (id) on delete restrict on update restrict;
alter table furniture_book add constraint FK_Reference_23 foreign key (fbtid)
references furniture_books_type (id) on delete restrict on update restrict;
alter table furniture_book add constraint FK_Reference_24 foreign key (creator)
references user (id) on delete restrict on update restrict;
alter table furniture_book add constraint FK_Reference_25 foreign key (buyer)
references user (id) on delete restrict on update restrict;
alter table furniture_books_receive add constraint FK_Reference_26 foreign key (fbid)
references furniture_book (id) on delete restrict on update restrict;
alter table furniture_books_repair add constraint FK_Reference_28 foreign key (fbid)
references furniture_book (id) on delete restrict on update restrict;
alter table furniture_books_scrap add constraint FK_Reference_27 foreign key (fbid)
references furniture_book (id) on delete restrict on update restrict;
alter table house_receive add constraint FK_Reference_17 foreign key (id)
references house (id) on delete restrict on update restrict;
alter table house_receive add constraint FK_Reference_19 foreign key (oid)
references organization (id) on delete restrict on update restrict;
alter table house_receive add constraint FK_Reference_20 foreign key (creator)
references user (id) on delete restrict on update restrict;
alter table land_receive add constraint FK_Reference_18 foreign key (id)
references land (id) on delete restrict on update restrict;
alter table land_receive add constraint FK_Reference_21 foreign key (oid)
references organization (id) on delete restrict on update restrict;
alter table land_receive add constraint FK_Reference_22 foreign key (creator)
references user (id) on delete restrict on update restrict;
alter table role_permission add constraint FK_Reference_3 foreign key (rid)
references role (id) on delete restrict on update restrict;
alter table role_permission add constraint FK_Reference_4 foreign key (pid)
references permission (id) on delete restrict on update restrict;
alter table user add constraint FK_Reference_1 foreign key (rid)
references role (id) on delete restrict on update restrict;
alter table user add constraint FK_Reference_2 foreign key (ogid)
references organization (id) on delete restrict on update restrict;
<file_sep>package com.ossjk.asset.house.vo;
import com.ossjk.asset.house.entity.House;
public class HouseVo extends House {
private String uName;
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
}
<file_sep>package com.ossjk.asset.system.service;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.system.entity.User;
/**
* <p>
* 用户 服务类
* </p>
*
* @author chair
* @since 2018-07-09
*/
public interface IUserService extends IService<User> {
public Page selectUserVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.system.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.base.controller.BaseController;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.common.vo.DwzPageBean;
import com.ossjk.asset.common.vo.ZtreeBean;
import com.ossjk.asset.system.entity.Permission;
import com.ossjk.asset.system.entity.Role;
import com.ossjk.asset.system.entity.Role_permission;
import com.ossjk.asset.system.service.IPermissionService;
import com.ossjk.asset.system.service.IRoleService;
import com.ossjk.asset.system.service.IRole_permissionService;
/**
* <p>
* 角色 前端控制器
* </p>
*
* @author lym
* @since 2020-01-09
*/
@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {
@Autowired
private IRoleService irs;
@Autowired
private IPermissionService ips;
@Autowired
private IRole_permissionService irps;
@RequestMapping("/list")
@RequiresPermissions("/system/role/list")
public String list(String name, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request,
HttpServletResponse response) {
map.put("name", name);
Wrapper wrapper = Condition.create().like("name", name).orderBy("crtm desc");
Page resultPage = irs.selectPage(dwzPageBean.toPage(), wrapper);
map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
return "system/role/list";
}
@RequestMapping("/toInsert")
@RequiresPermissions("/system/role/toInsert")
public String toInsert(HttpServletRequest request, HttpServletResponse response) {
return "system/role/edit";
}
@RequestMapping("/insert")
@RequiresPermissions("/system/role/toInsert")
@ResponseBody
public Object insert(Role ro, HttpServletRequest request, HttpServletResponse response) {
Wrapper<Role> wrapper = Condition.create().eq("name", ro.getName());
Role role = irs.selectOne(wrapper);
if (!CommonUtil.isBlank(role)) {
return ajaxError("职位名称已存在。");
} else if (irs.insert(ro)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toUpdate")
@RequiresPermissions("/system/role/toUpdate")
public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
map.put("record", irs.selectById(id));
return "system/role/edit";
}
@RequestMapping("/update")
@RequiresPermissions("/system/role/toUpdate")
@ResponseBody
public Object update(Role ro, HttpServletRequest request, HttpServletResponse response) {
// ro.setMdtm((new Date()).toString());
if (irs.updateById(ro)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toAuthorize")
@RequiresPermissions("/system/role/toAuthorize")
public String toShouquan(ModelMap map, String id) {
List<Permission> permissions = ips.selectList(null);
// 回显数据,查询已经授权的数据
Wrapper wrapper = Condition.create().isWhere(true).like("rid", id);
List<String> pid = irps.SelectRole_permissionCid(wrapper);
List list = new ArrayList();
for (Permission permission : permissions) {
ZtreeBean e = new ZtreeBean();
// 优化程序
e.setChecked(pid.contains(permission.getId()));
e.setId(permission.getId());
e.setPId(permission.getPid());
e.setName(permission.getName());
e.setOpen(true);
list.add(e);
}
map.put("zNodes", JSON.toJSONString(list));
map.put("rid", id);
return "system/role/authorize";
}
@RequestMapping("/authorize")
@RequiresPermissions("/system/role/toAuthorize")
@ResponseBody
public Object authorize(String[] pid, String rid, HttpServletRequest request, HttpServletResponse response) {
if (irps.insertBatchAuthorize(pid, rid)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/delete")
@RequiresPermissions("/system/role/delete")
@ResponseBody
public Object update(String[] id, HttpServletRequest request, HttpServletResponse response) {
if (irs.deleteBatchIds(Arrays.asList(id))) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
}
<file_sep>package com.ossjk.asset.system.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 流水号规则表
* </p>
*
* @author lym
* @since 2020-01-09
*/
@TableName("code_rule")
public class Code_rule extends BaseEntity<Code_rule> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 名字
*/
private String name;
/**
* 规则表达式
*/
private String rule;
/**
* 当前流水号
*/
private String current;
/**
* 备注
*/
private String remarks;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRule() {
return rule;
}
public void setRule(String rule) {
this.rule = rule;
}
public String getCurrent() {
return current;
}
public void setCurrent(String current) {
this.current = current;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Code_rule{" +
"id=" + id +
", name=" + name +
", rule=" + rule +
", current=" + current +
", remarks=" + remarks +
", crtm=" + crtm +
", mdtm=" + mdtm +
"}";
}
}
<file_sep>package com.ossjk.asset.house.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.house.entity.House;
import com.ossjk.asset.house.vo.HouseVo;
/**
* <p>
* 房屋明细 Mapper 接口
* </p>
*
* @author lym
* @since 2020-01-12
*/
public interface HouseMapper extends BaseMapper<House> {
List<HouseVo> selectHouseVo(Page page,@Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.car.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.car.entity.Car;
import com.ossjk.asset.car.vo.CarVo;
/**
* <p>
* 车辆明细 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface CarMapper extends BaseMapper<Car> {
List<CarVo> selectCarVo(Page page,@Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.car.service;
import com.ossjk.asset.car.entity.Car_scrap;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 车辆报废 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface ICar_scrapService extends IService<Car_scrap> {
public Page selectCar_scrapVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.system.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.system.entity.Permission;
import com.ossjk.asset.system.mapper.PermissionMapper;
import com.ossjk.asset.system.service.IPermissionService;
/**
* <p>
* 权限 服务实现类
* </p>
*
* @author lym
* @since 2020-01-09
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
@Override
public boolean insert(Permission entity) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
String format = sdf.format(new Date());
entity.setCrtm(format);
entity.setMdtm(format);
System.out.println(entity);
return super.insert(entity);
}
@Override
public Page selectPermissionVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
page.setRecords(baseMapper.selectPermissionVo(page, wrapper));
return page;
}
@Override
public List<String> selectUserPermission(Wrapper wrapper) {
return baseMapper.selectUserPermission(wrapper);
}
@Override
public List<Permission> selectMenuPermission(Wrapper wrapper) {
return baseMapper.selectMenuPermission(wrapper);
}
}
<file_sep>package com.ossjk.asset.book.service.impl;
import com.ossjk.asset.book.entity.Furniture_books_repair;
import com.ossjk.asset.book.mapper.Furniture_books_repairMapper;
import com.ossjk.asset.book.service.IFurniture_books_repairService;
import com.ossjk.asset.book.vo.Furniture_books_repairVo;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.stereotype.Service;
/**
* <p>
* 家具图书维修表 服务实现类
* </p>
*
* @author lxw
* @since 2020-01-09
*/
@Service
public class Furniture_books_repairServiceImpl extends ServiceImpl<Furniture_books_repairMapper, Furniture_books_repair> implements IFurniture_books_repairService {
@Override
public Page selectFurniture_books_repairVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
System.out.println(wrapper.getSqlSelect());
System.out.println(wrapper.getSqlSegment());
page.setRecords(baseMapper.selectFurniture_books_repairVo(page, wrapper));
return page;
}
}
<file_sep>package com.ossjk.asset.book.mapper;
import com.ossjk.asset.book.entity.Furniture_books_repair;
import com.ossjk.asset.book.vo.Furniture_books_repairVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 家具图书维修表 Mapper 接口
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface Furniture_books_repairMapper extends BaseMapper<Furniture_books_repair> {
List<Furniture_books_repairVo> selectFurniture_books_repairVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.common.util;
public class Constant {
public static final String SESSION_USER_KEY = "user";
public static final String DWZRESULT_STATUSCODE_SUCCESS = "200";
public static final String DWZRESULT_STATUSCODE_ERROR = "300";
public static final String DWZRESULT_STATUSCODE_TIMEOUT = "301";
public static final String DWZRESULT_MESSAGE_SUCCESS = "操作成功";
public static final String DWZRESULT_MESSAGE_ERROR = "操作失败";
public static final String DWZRESULT_MESSAGE_TIMEOUT = "超时";
public static final String DWZRESULT_CALLBACKTYPE_CLOSECURRENT = "closeCurrent";
public static final String DWZRESULT_CALLBACKTYPE_FORWARD = "forward";
}
<file_sep>package com.ossjk.asset.house.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 房屋分配情况
* </p>
*
* @author lym
* @since 2020-01-12
*/
@TableName("house_receive")
public class House_receive extends BaseEntity<House_receive> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 房屋id
*
*/
private String hid;
/**
* 分配单位
*
*/
private String oid;
/**
* 登记用户
*/
private String creator;
/**
* 备注
*
*/
private String remarks;
/**
* 单据号
*/
private String receipt;
public String getReceipt() {
return receipt;
}
public void setReceipt(String receipt) {
this.receipt = receipt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHid() {
return hid;
}
public void setHid(String hid) {
this.hid = hid;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "House_receive [id=" + id + ", hid=" + hid + ", oid=" + oid + ", creator=" + creator + ", remarks="
+ remarks + ", receipt=" + receipt + "]";
}
}
<file_sep>package com.ossjk.asset.device.service;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.device.entity.Device_repair;
/**
* <p>
* 设备维修表 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface IDevice_repairService extends IService<Device_repair> {
public Page selectDevice_repairVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.land.service.impl;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.land.entity.Land;
import com.ossjk.asset.land.entity.Land_receive;
import com.ossjk.asset.land.mapper.Land_receiveMapper;
import com.ossjk.asset.land.service.ILandService;
import com.ossjk.asset.land.service.ILand_receiveService;
import com.ossjk.asset.land.vo.Land_receiveVo;
import com.ossjk.asset.system.entity.Code_rule;
import com.ossjk.asset.system.service.ICode_ruleService;
/**
* <p>
* 土地分配情况 服务实现类
* </p>
*
* @author lym
* @since 2020-01-12
*/
@Service
public class Land_receiveServiceImpl extends ServiceImpl<Land_receiveMapper, Land_receive>
implements ILand_receiveService {
@Autowired
private ILandService ils;
@Autowired
private ILand_receiveService ilrs;
@Autowired
private ICode_ruleService icrs;
@Transactional
@Override
public boolean insert(Land_receive entity) {
Wrapper wrapper = Condition.create().eq("name", "土地单据");
Code_rule one = icrs.selectOne(wrapper);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
String year = sdf.format(new Date()).substring(2);
String cur = (Integer.parseInt(one.getCurrent()) + 1) + "";
for (int i = cur.length(); i < 4; i++) {
cur = "0" + cur;
}
entity.setReceipt(one.getRule() + year + cur);
one.setCurrent(cur);
icrs.updateById(one);
return super.insert(entity);
}
@Override
public Page selectLand_receiveVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
page.setRecords(baseMapper.selectLand_receiveVo(page, wrapper));
return page;
}
@Override
public Land_receiveVo selectVoById(String id) {
return baseMapper.selectVoById(id);
}
@Transactional
@Override
public boolean insertVo(Land_receiveVo lrv) {
try {
lrv.setId(UUID.randomUUID().toString().replaceAll("-", ""));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
String format = sdf.format(new Date());
lrv.setMdtm(format);
lrv.setCrtm(format);
if (!ilrs.insert(lrv)) {
new Exception();
}
Land l = new Land();
l.setId(lrv.getLid());
l.setStatus(1);
l.setService_life(lrv.getService_life());
if (!ils.updateById(l)) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
@Transactional
@Override
public boolean updateVoById(Land_receiveVo lrv, String olid) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
lrv.setMdtm(sdf.format(new Date()));
if (!ilrs.updateById(lrv)) {
new Exception();
}
Land l = new Land();
if (!olid.equals(lrv.getLid())) {
Land selectById = ils.selectById(olid);
selectById.setStatus(0);
if (!ils.updateById(selectById)) {
new Exception();
}
}
l.setStatus(1);
l.setId(lrv.getLid());
l.setService_life(lrv.getService_life());
if (!ils.updateById(l)) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean deleteBatchIdsAndReset(String[] id) {
try {
for (String string : id) {
Land selectById = ils.selectById(ilrs.selectById(string).getLid());
selectById.setStatus(0);
if (!ils.updateById(selectById)) {
new Exception();
}
}
if (!ilrs.deleteBatchIds(Arrays.asList(id))) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
}
<file_sep>package com.ossjk.asset.car.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 车辆报废
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@TableName("car_scrap")
public class Car_scrap extends BaseEntity<Car_scrap> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 车辆id
*/
private String cid;
/**
* 报废人
*/
private String scraper;
/**
* 报废日期
*/
private String scraperdate;
/**
* 报废备注
*/
private String scrapremarks;
/**
* 状态 1-申请、2-准许、3-拒绝
*/
private BigDecimal status;
/**
* 审批人
*/
private String approver;
/**
* 审批意见
*/
private String approvalremarks;
/**
* 申请日期
*/
private String approvaldate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getScraper() {
return scraper;
}
public void setScraper(String scraper) {
this.scraper = scraper;
}
public String getScraperdate() {
return scraperdate;
}
public void setScraperdate(String scraperdate) {
this.scraperdate = scraperdate;
}
public String getScrapremarks() {
return scrapremarks;
}
public void setScrapremarks(String scrapremarks) {
this.scrapremarks = scrapremarks;
}
public BigDecimal getStatus() {
return status;
}
public void setStatus(BigDecimal status) {
this.status = status;
}
public String getApprover() {
return approver;
}
public void setApprover(String approver) {
this.approver = approver;
}
public String getApprovalremarks() {
return approvalremarks;
}
public void setApprovalremarks(String approvalremarks) {
this.approvalremarks = approvalremarks;
}
public String getApprovaldate() {
return approvaldate;
}
public void setApprovaldate(String approvaldate) {
this.approvaldate = approvaldate;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Car_scrap{" +
"id=" + id +
", cid=" + cid +
", scraper=" + scraper +
", scraperdate=" + scraperdate +
", scrapremarks=" + scrapremarks +
", status=" + status +
", approver=" + approver +
", approvalremarks=" + approvalremarks +
", approvaldate=" + approvaldate +
", crtm=" + crtm +
", mdtm=" + mdtm +
"}";
}
}
<file_sep>package com.ossjk.asset.land.service.impl;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.land.entity.Land;
import com.ossjk.asset.land.mapper.LandMapper;
import com.ossjk.asset.land.service.ILandService;
import com.ossjk.asset.system.entity.Code_rule;
import com.ossjk.asset.system.service.ICode_ruleService;
/**
* <p>
* 土地明细 服务实现类
* </p>
*
* @author lym
* @since 2020-01-12
*/
@Service
public class LandServiceImpl extends ServiceImpl<LandMapper, Land> implements ILandService {
@Autowired
private ICode_ruleService icrs;
@Transactional
@Override
public boolean insert(Land entity) {
Wrapper wrapper = Condition.create().eq("name", "土地流水");
Code_rule one = icrs.selectOne(wrapper);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
String year = sdf.format(new Date()).substring(2);
String cur = (Integer.parseInt(one.getCurrent()) + 1) + "";
for (int i = cur.length(); i < 4; i++) {
cur = "0" + cur;
}
entity.setCode(one.getRule() + year + cur);
one.setCurrent(cur);
icrs.updateById(one);
return super.insert(entity);
}
}
<file_sep>spring.datasource.url = jdbc:mysql://localhost:3306/assets?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = <PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.validationQuery=select 1 <file_sep>package com.ossjk.asset.car.mapper;
import com.ossjk.asset.car.entity.Car_repair;
import com.ossjk.asset.car.vo.CarVo;
import com.ossjk.asset.car.vo.Car_repairVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 车辆维修表 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Car_repairMapper extends BaseMapper<Car_repair> {
List<Car_repairVo> selectCar_repairVo(Page page,@Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.device.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ResponseBody;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.base.controller.BaseController;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.common.vo.DwzPageBean;
import com.ossjk.asset.device.entity.Device;
import com.ossjk.asset.device.entity.Device_receive;
import com.ossjk.asset.device.service.IDeviceService;
import com.ossjk.asset.device.service.IDevice_receiveService;
import com.ossjk.asset.device.vo.Device_receiveVo;
import com.ossjk.asset.system.entity.User;
import com.ossjk.asset.system.service.IUserService;
/**
* <p>
* 设备领用表 前端控制器
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Controller
@RequestMapping("/device/device_receive")
public class Device_receiveController extends BaseController {
@Autowired
private IDevice_receiveService iDevice_receiveService;
@Autowired
private IUserService iUserService;
@Autowired
private IDeviceService iDeviceService;
@RequestMapping("/list")
public String list(String receipt, String recipients, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request,
HttpServletResponse response) {
dwzPageBean.getCountResultMap().put("receipt", receipt);
dwzPageBean.getCountResultMap().put("recipients", recipients);
Wrapper wrapper = Condition.create().like("receipt", receipt).like("recipients", recipients);
Page resultPage = iDevice_receiveService.selectDevice_receiveVo(dwzPageBean.toPage(), wrapper);
map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
return "device/device_receive/list";
}
@RequestMapping("/toInsert")
public String toInsert(HttpServletRequest request, HttpServletResponse response,ModelMap map) {
List<User> userlist=iUserService.selectList(null);
List<Device> deviceServicelist=iDeviceService.selectList(null);
map.put("deviceServicelist",deviceServicelist);
map.put("userlist", userlist);
return "device/device_receive/edit";
}
@RequestMapping("/insert")
@ResponseBody
public Object insert(Device_receive device_receive, HttpServletRequest request, HttpServletResponse response) {
Wrapper<Device_receive> wrapper = Condition.create().eq("receipt", device_receive.getReceipt()).or()
.eq("recipients", device_receive.getRecipients());
Device_receive device_receive2 = iDevice_receiveService.selectOne(wrapper);
if (!CommonUtil.isBlank(device_receive2)) {
return ajaxError("单据号或领用人");
}
if (iDevice_receiveService.insert(device_receive)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toUpdate")
public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
List<User> userlist=iUserService.selectList(null);
List<Device> deviceServicelist=iDeviceService.selectList(null);
map.put("deviceServicelist",deviceServicelist);
map.put("userlist", userlist);
map.put("record", iDevice_receiveService.selectById(id));
return "device/device_receive/edit";
}
@RequestMapping("/update")
@ResponseBody
public Object update(Device_receiveVo device_receive, HttpServletRequest request, HttpServletResponse response) {
if (iDevice_receiveService.updateById(device_receive)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/delete")
@ResponseBody
public Object update(String[] id, HttpServletRequest request, HttpServletResponse response) {
if (iDevice_receiveService.deleteBatchIds(Arrays.asList(id))) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
}
<file_sep>package com.ossjk.asset.house.vo;
import com.ossjk.asset.house.entity.House_receive;
public class House_receiveVo extends House_receive {
private String address;
private String oName;
private String uName;
private String service_life;
private Integer status;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getoName() {
return oName;
}
public void setoName(String oName) {
this.oName = oName;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getService_life() {
return service_life;
}
public void setService_life(String service_life) {
this.service_life = service_life;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
<file_sep>package com.ossjk.asset.device.vo;
import com.ossjk.asset.device.entity.Device_repair;
public class Device_repairVo extends Device_repair {
private String dname;
private String rname;
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
}
<file_sep>package com.ossjk.asset.book.vo;
import com.ossjk.asset.book.entity.Furniture_books_repair;
public class Furniture_books_repairVo extends Furniture_books_repair{
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
<file_sep>package com.ossjk.asset.car.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.car.entity.Car_receive;
import com.ossjk.asset.car.vo.Car_receiveVo;
/**
* <p>
* 车辆领用表 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Car_receiveMapper extends BaseMapper<Car_receive> {
List<Car_receiveVo> selectCar_receiveVo(Page page,@Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.land.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 土地分配情况
* </p>
*
* @author lym
* @since 2020-01-13
*/
@TableName("land_receive")
public class Land_receive extends BaseEntity<Land_receive> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 土地编号
*
*/
private String lid;
/**
* 分配单位
*
*/
private String oid;
/**
* 登记用户
*/
private String creator;
/**
* 备注
*
*/
private String remarks;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
protected String crtm;
/**
* 修改时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
protected String mdtm;
/**
* 土地单据号
*/
private String receipt;
public String getReceipt() {
return receipt;
}
public void setReceipt(String receipt) {
this.receipt = receipt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLid() {
return lid;
}
public void setLid(String lid) {
this.lid = lid;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Land_receive [id=" + id + ", lid=" + lid + ", oid=" + oid + ", creator=" + creator + ", remarks="
+ remarks + ", crtm=" + crtm + ", mdtm=" + mdtm + ", receipt=" + receipt + "]";
}
}
<file_sep>package com.ossjk.asset.device.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.device.entity.Device_repair;
import com.ossjk.asset.device.mapper.Device_repairMapper;
import com.ossjk.asset.device.service.IDevice_repairService;
/**
* <p>
* 设备维修表 服务实现类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Service
public class Device_repairServiceImpl extends ServiceImpl<Device_repairMapper, Device_repair>
implements IDevice_repairService {
@Override
public Page selectDevice_repairVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
wrapper.getSqlSegment();
page.setRecords(baseMapper.selectDevice_repairVo(page, wrapper));
return page;
}
}
<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.ossjk</groupId>
<artifactId>assets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId>
</dependency> -->
<!-- spring boot tomcat jsp 支持开启 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet支持开启 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- jstl 支持开启 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<!-- 添加MySQL数据库驱动依赖包. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<!-- druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.18</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.5</version>
</dependency>
<!-- jwt start -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<!-- jwt end -->
<!-- mybatis plus start -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>2.1.2</version>
</dependency>
<!-- mybatis plus end -->
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional><!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖myboot项目的项目如果想要使用devtools,需要重新引入 -->
</dependency>
<!-- shiro spring. -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 打成war包 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>boot</warName>
</configuration>
</plugin>
<!-- 打包可执行jar包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project><file_sep>package com.ossjk.asset.house.service;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.house.entity.House;
/**
* <p>
* 房屋明细 服务类
* </p>
*
* @author lym
* @since 2020-01-12
*/
public interface IHouseService extends IService<House> {
public Page selectHouseVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.car.service.impl;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.car.entity.Car;
import com.ossjk.asset.car.mapper.CarMapper;
import com.ossjk.asset.car.service.ICarService;
import com.ossjk.asset.land.entity.Land;
import com.ossjk.asset.system.entity.Code_rule;
import com.ossjk.asset.system.service.ICode_ruleService;
/**
* <p>
* 车辆明细 服务实现类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {
@Autowired
private ICode_ruleService iCode_ruleService;
@Transactional
@Override
public boolean insert(Car entity) {
Wrapper wrapper = Condition.create().eq("name", "车辆流水");
Code_rule one = iCode_ruleService.selectOne(wrapper);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
String time = sdf.format(new Date());
String year = time.substring(2, 4);
String cur = (Integer.parseInt(one.getCurrent()) + 1) + "";
for (int i = cur.length(); i < 4; i++) {
cur = "0" + cur;
}
entity.setCode(one.getRule() + year + cur);
one.setCurrent(cur);
iCode_ruleService.updateById(one);
entity.setCreatetime(time);
return super.insert(entity);
}
public Page selectCarVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
page.setRecords(baseMapper.selectCarVo(page, wrapper));
return page;
}
}
<file_sep>package com.ossjk.asset.book.mapper;
import com.ossjk.asset.book.entity.Furniture_book;
import com.ossjk.asset.book.vo.Furniture_bookVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 家具图书明细 Mapper 接口
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface Furniture_bookMapper extends BaseMapper<Furniture_book> {
List<Furniture_bookVo> selectFurniture_bookVo(Page page, @Param("ew") Wrapper wrapper);
List<Furniture_book> selectAll();
}<file_sep>package com.ossjk.asset.device.service;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.device.entity.Device;
/**
* <p>
* 设备明细 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface IDeviceService extends IService<Device> {
public Page selectDeviceVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.car.service;
import com.ossjk.asset.car.entity.Car_repair;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 车辆维修表 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface ICar_repairService extends IService<Car_repair> {
public Page selectCar_repairVo(Page page, Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.car.controller;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ResponseBody;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.base.controller.BaseController;
import com.ossjk.asset.car.entity.Car_type;
import com.ossjk.asset.car.service.ICar_typeService;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.common.vo.DwzPageBean;
/**
* <p>
* 车辆类型 前端控制器
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Controller
@RequestMapping("/car/car_type")
public class Car_typeController extends BaseController {
@Autowired
private ICar_typeService iCar_typeService;
@RequestMapping("/list")
public String list(String name, String damager, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request,
HttpServletResponse response) {
dwzPageBean.getCountResultMap().put("name", name);
Wrapper wrapper = Condition.create().like("name", name);
Page resultPage = iCar_typeService.selectPage(dwzPageBean.toPage(), wrapper);
map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
return "car/car_type/list";
}
@RequestMapping("/toInsert")
public String toInsert(HttpServletRequest request, HttpServletResponse response) {
return "car/car_type/edit";
}
@RequestMapping("/insert")
@ResponseBody
public Object insert(Car_type car_type, HttpServletRequest request, HttpServletResponse response) {
Wrapper<Car_type> wrapper = Condition.create().eq("name", car_type.getName());
Car_type car_type2 = iCar_typeService.selectOne(wrapper);
if (!CommonUtil.isBlank(car_type2)) {
return ajaxError("重复");
}
if (iCar_typeService.insert(car_type)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toUpdate")
public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
map.put("record", iCar_typeService.selectById(id));
return "car/car_type/edit";
}
@RequestMapping("/update")
@ResponseBody
public Object update(Car_type car_type, HttpServletRequest request, HttpServletResponse response) {
if (iCar_typeService.updateById(car_type)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/delete")
@ResponseBody
public Object update(String[] id, HttpServletRequest request, HttpServletResponse response) {
if (iCar_typeService.deleteBatchIds(Arrays.asList(id))) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
}
<file_sep>package com.ossjk.asset.car.mapper;
import com.ossjk.asset.car.entity.Car_type;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 车辆类型 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Car_typeMapper extends BaseMapper<Car_type> {
}<file_sep>package com.ossjk.asset.device.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.device.entity.Device_repair;
import com.ossjk.asset.device.vo.Device_repairVo;
/**
* <p>
* 设备维修表 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Device_repairMapper extends BaseMapper<Device_repair> {
List<Device_repairVo> selectDevice_repairVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.book.vo;
import com.ossjk.asset.book.entity.Furniture_book;
public class Furniture_bookVo extends Furniture_book{
String brand;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
<file_sep>package com.ossjk.asset.book.mapper;
import com.ossjk.asset.book.entity.Furniture_books_receive;
import com.ossjk.asset.book.vo.Furniture_books_receiveVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 家具图书领用表 Mapper 接口
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface Furniture_books_receiveMapper extends BaseMapper<Furniture_books_receive> {
List<Furniture_books_receiveVo> selectFurniture_books_receiveVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.book.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 家具图书类型
* </p>
*
* @author lxw
* @since 2020-01-09
*/
@TableName("furniture_books_type")
public class Furniture_books_type extends BaseEntity<Furniture_books_type> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 类型:1、家具 2、图书
*/
private Integer type;
/**
* 名字
*/
private String name;
/**
* 品牌/出版社
*/
private String brand;
/**
* 国际编号
*/
private String intlcode;
/**
* 备注
*/
private String remarks;
/**
* 创建时间
*/
private String crtm;
/**
* 修改时间
*/
private String mdtm;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getIntlcode() {
return intlcode;
}
public void setIntlcode(String intlcode) {
this.intlcode = intlcode;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Furniture_books_type{" +
"id=" + id +
", type=" + type +
", name=" + name +
", brand=" + brand +
", intlcode=" + intlcode +
", remarks=" + remarks +
", crtm=" + crtm +
", mdtm=" + mdtm +
"}";
}
}
<file_sep>package com.ossjk.asset.system.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.system.entity.Role_permission;
import com.ossjk.asset.system.mapper.Role_permissionMapper;
import com.ossjk.asset.system.service.IRoleService;
import com.ossjk.asset.system.service.IRole_permissionService;
/**
* <p>
* 角色权限中间表 服务实现类
* </p>
*
* @author lym
* @since 2020-01-09
*/
@Service
public class Role_permissionServiceImpl extends ServiceImpl<Role_permissionMapper, Role_permission>
implements IRole_permissionService {
@Autowired
private IRole_permissionService irps;
@Autowired
private IRoleService irs;
@Override
public List<String> SelectRole_permissionCid(Wrapper wrapper) {
return baseMapper.SelectRole_permissionCid(wrapper);
}
@Override
public boolean insertBatchAuthorize(String[] pid, String rid) {
// 接收到所有的参数就要保存数据
// 先删除掉rid中的所有的权限数据
Wrapper wrapper = Condition.create().like("rid", rid);
irps.delete(wrapper);
// 再保存新的数据
List entityList = new ArrayList();
for (String string : pid) {
Role_permission permission = new Role_permission();
permission.setPid(string);
permission.setRid(rid);
entityList.add(permission);
}
return irs.insertBatch(entityList);
}
}
<file_sep>package com.ossjk.asset.book.vo;
import com.ossjk.asset.book.entity.Furniture_books_receive;
public class Furniture_books_receiveVo extends Furniture_books_receive{
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
<file_sep>package com.ossjk.asset.land.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 土地明细
* </p>
*
* @author lym
* @since 2020-01-12
*/
@TableName("land")
public class Land extends BaseEntity<Land> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 土地性质
*/
private String property;
/**
* 土地位置
*
*/
private String address;
/**
* 土地面积
*
*/
private Double area;
/**
* 使用期限
*
*/
private String service_life;
/**
* 备注信息
*/
private String remarks;
/**
* 土地状态:0、闲置 1、已分配 2、其他
*/
private Integer status;
/**
* 土地流水号
*/
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Double getArea() {
return area;
}
public void setArea(Double area) {
this.area = area;
}
public String getService_life() {
return service_life;
}
public void setService_life(String service_life) {
this.service_life = service_life;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Land [id=" + id + ", property=" + property + ", address=" + address + ", area=" + area
+ ", service_life=" + service_life + ", remarks=" + remarks + ", status=" + status + ", code=" + code
+ "]";
}
}
<file_sep>package com.ossjk.asset.device.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.device.entity.Device;
import com.ossjk.asset.device.vo.DeviceVo;
/**
* <p>
* 设备明细 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface DeviceMapper extends BaseMapper<Device> {
List<DeviceVo> selectDeviceVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.book.service;
import com.ossjk.asset.book.entity.Furniture_books_repair;
import com.ossjk.asset.book.vo.Furniture_books_repairVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 家具图书维修表 服务类
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface IFurniture_books_repairService extends IService<Furniture_books_repair> {
Page selectFurniture_books_repairVo(Page page,Wrapper wrapper);
}
<file_sep>package com.ossjk.asset.car.controller;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ResponseBody;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.base.controller.BaseController;
import com.ossjk.asset.car.entity.Car_repair;
import com.ossjk.asset.car.service.ICarService;
import com.ossjk.asset.car.service.ICar_repairService;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.common.vo.DwzPageBean;
import com.ossjk.asset.system.service.IUserService;
/**
* <p>
* 车辆维修表 前端控制器
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Controller
@RequestMapping("/car/car_repair")
public class Car_repairController extends BaseController {
@Autowired
private ICar_repairService iCar_repairService;
@Autowired
private IUserService iUserService;
@Autowired
private ICarService iCarService;
@RequestMapping("/list")
public String list(String cid, String damager, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request,
HttpServletResponse response) {
dwzPageBean.getCountResultMap().put("cid", cid);
Wrapper wrapper = Condition.create().isWhere(true).like("r.cid", cid);
Page resultPage = iCar_repairService.selectCar_repairVo(dwzPageBean.toPage(), wrapper);
map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
return "car/car_repair/list";
}
@RequestMapping("/toInsert")
public String toInsert(HttpServletRequest request, HttpServletResponse response,ModelMap map) {
map.put("user", iUserService.selectList(null));
map.put("car", iCarService.selectList(null));
return "car/car_repair/edit";
}
@RequestMapping("/insert")
@ResponseBody
public Object insert(Car_repair car_repair, HttpServletRequest request, HttpServletResponse response) {
Wrapper<Car_repair> wrapper = Condition.create().eq("cid", car_repair.getCid());
Car_repair car_repair2 = iCar_repairService.selectOne(wrapper);
if (!CommonUtil.isBlank(car_repair2)) {
return ajaxError("重复");
}
if (iCar_repairService.insert(car_repair)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toUpdate")
public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
map.put("record", iCar_repairService.selectById(id));
map.put("user", iUserService.selectList(null));
map.put("car", iCarService.selectList(null));
return "car/car_repair/edit";
}
@RequestMapping("/update")
@ResponseBody
public Object update(Car_repair car_repair, HttpServletRequest request, HttpServletResponse response) {
if (iCar_repairService.updateById(car_repair)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/delete")
@ResponseBody
public Object update(String[] id, HttpServletRequest request, HttpServletResponse response) {
if (iCar_repairService.deleteBatchIds(Arrays.asList(id))) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
}
<file_sep>package com.ossjk.asset.book.mapper;
import com.ossjk.asset.book.entity.Furniture_books_scrap;
import com.ossjk.asset.book.vo.Furniture_books_scrapVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
/**
* <p>
* 家具图书报废 Mapper 接口
* </p>
*
* @author lxw
* @since 2020-01-09
*/
public interface Furniture_books_scrapMapper extends BaseMapper<Furniture_books_scrap> {
List<Furniture_books_scrapVo> selectFurniture_books_scrapVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.car.service.impl;
import com.ossjk.asset.car.entity.Car_scrap;
import com.ossjk.asset.car.mapper.Car_scrapMapper;
import com.ossjk.asset.car.service.ICar_scrapService;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 车辆报废 服务实现类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Service
public class Car_scrapServiceImpl extends ServiceImpl<Car_scrapMapper, Car_scrap> implements ICar_scrapService {
public Page selectCar_scrapVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
page.setRecords(baseMapper.selectCar_scrapVo(page, wrapper));
return page;
}
}
<file_sep>package com.ossjk.asset.device.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.device.entity.Device_receive;
import com.ossjk.asset.device.vo.Device_receiveVo;
/**
* <p>
* 设备领用表 Mapper 接口
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface Device_receiveMapper extends BaseMapper<Device_receive> {
List<Device_receiveVo> selectDevice_receiveVo(Page page, @Param("ew") Wrapper wrapper);
}<file_sep>package com.ossjk.asset.system.vo;
import com.ossjk.asset.system.entity.User;
public class UserVo extends User {
private String rName;
private String oName;
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getoName() {
return oName;
}
public void setoName(String oName) {
this.oName = oName;
}
}
<file_sep>package com.ossjk.asset.system.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 角色权限中间表
* </p>
*
* @author lym
* @since 2020-01-09
*/
@TableName("role_permission")
public class Role_permission extends BaseEntity<Role_permission>{
private static final long serialVersionUID = 1L;
private String id;
/**
* 角色id
*/
private String rid;
/**
* 权限id
*/
private String pid;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Role_permission{" +
"id=" + id +
", rid=" + rid +
", pid=" + pid +
"}";
}
}
<file_sep>spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
spring.datasource.druid.maxWait=60000
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=select 1
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.filters=stat,wall,log4j
spring.datasource.druid.logSlowSql=true<file_sep>package com.ossjk.asset.system.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotations.TableName;
import com.ossjk.asset.base.entity.BaseEntity;
/**
* <p>
* 权限
* </p>
*
* @author lym
* @since 2020-01-09
*/
@TableName("permission")
public class Permission extends BaseEntity<Permission> {
private static final long serialVersionUID = 1L;
private String id;
/**
* 父级id
*/
private String pid;
/**
* 名字
*/
private String name;
/**
* url
*/
private String url;
/**
* 序号
*/
private BigDecimal sort;
/**
* 备注
*/
private String remarks;
/**
* 等级
*/
private BigDecimal level;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public BigDecimal getSort() {
return sort;
}
public void setSort(BigDecimal sort) {
this.sort = sort;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public BigDecimal getLevel() {
return level;
}
public void setLevel(BigDecimal level) {
this.level = level;
}
public String getCrtm() {
return crtm;
}
public void setCrtm(String crtm) {
this.crtm = crtm;
}
public String getMdtm() {
return mdtm;
}
public void setMdtm(String mdtm) {
this.mdtm = mdtm;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Permission{" +
"id=" + id +
", pid=" + pid +
", name=" + name +
", url=" + url +
", sort=" + sort +
", remarks=" + remarks +
", level=" + level +
", crtm=" + crtm +
", mdtm=" + mdtm +
"}";
}
}
<file_sep>package com.ossjk.asset.device.service.impl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.device.entity.Device_type;
import com.ossjk.asset.device.mapper.Device_typeMapper;
import com.ossjk.asset.device.service.IDevice_typeService;
/**
* <p>
* 设备类型 服务实现类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Service
public class Device_typeServiceImpl extends ServiceImpl<Device_typeMapper, Device_type> implements IDevice_typeService {
}
<file_sep>package com.ossjk.asset.book.service.impl;
import com.ossjk.asset.book.entity.Furniture_books_type;
import com.ossjk.asset.book.mapper.Furniture_bookMapper;
import com.ossjk.asset.book.mapper.Furniture_books_scrapMapper;
import com.ossjk.asset.book.mapper.Furniture_books_typeMapper;
import com.ossjk.asset.book.service.IFurniture_books_typeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* 家具图书类型 服务实现类
* </p>
*
* @author lxw
* @since 2020-01-09
*/
@Service
public class Furniture_books_typeServiceImpl extends ServiceImpl<Furniture_books_typeMapper, Furniture_books_type> implements IFurniture_books_typeService {
@Autowired
private Furniture_books_typeMapper books_typeMapper;
@Override
public List<Furniture_books_type> selectAll() {
return books_typeMapper.selectAll();
}
}
<file_sep>package com.ossjk.asset.device.service;
import com.baomidou.mybatisplus.service.IService;
import com.ossjk.asset.device.entity.Device_type;
/**
* <p>
* 设备类型 服务类
* </p>
*
* @author Mht
* @since 2020-01-09
*/
public interface IDevice_typeService extends IService<Device_type> {
}
<file_sep>package com.ossjk.asset.car.controller;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ResponseBody;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.base.controller.BaseController;
import com.ossjk.asset.car.entity.Car_receive;
import com.ossjk.asset.car.service.ICarService;
import com.ossjk.asset.car.service.ICar_receiveService;
import com.ossjk.asset.common.util.CommonUtil;
import com.ossjk.asset.common.vo.DwzPageBean;
import com.ossjk.asset.system.service.IUserService;
/**
* <p>
* 车辆领用表 前端控制器
* </p>
*
* @author Mht
* @since 2020-01-09
*/
@Controller
@RequestMapping("/car/car_receive")
public class Car_receiveController extends BaseController {
@Autowired
private ICarService iCarService;
@Autowired
private ICar_receiveService iCar_receiveService;
@Autowired
private IUserService iUserService;
@RequestMapping("/list")
public String list(String cid, String receipt, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request,
HttpServletResponse response) {
dwzPageBean.getCountResultMap().put("r.cid", cid);
dwzPageBean.getCountResultMap().put("receipt", receipt);
Wrapper wrapper = Condition.create().isWhere(true).like("r.cid", cid).like("receipt", receipt);
Page resultPage = iCar_receiveService.selectCar_receiveVo(dwzPageBean.toPage(), wrapper);
map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
return "car/car_receive/list";
}
@RequestMapping("/toInsert")
public String toInsert(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
map.put("user", iUserService.selectList(null));
map.put("car", iCarService.selectList(null));
return "car/car_receive/edit";
}
@RequestMapping("/insert")
@ResponseBody
public Object insert(Car_receive car_receive, HttpServletRequest request, HttpServletResponse response) {
Wrapper<Car_receive> wrapper = Condition.create().eq("receipt", car_receive.getReceipt());
Car_receive car_receive2 = iCar_receiveService.selectOne(wrapper);
if (!CommonUtil.isBlank(car_receive2)) {
return ajaxError("单据号");
}
if (iCar_receiveService.insert(car_receive)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/toUpdate")
public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
map.put("record", iCar_receiveService.selectById(id));
map.put("user", iUserService.selectList(null));
map.put("car", iCarService.selectList(null));
return "car/car_receive/edit";
}
@RequestMapping("/update")
@ResponseBody
public Object update(Car_receive car_receive, HttpServletRequest request, HttpServletResponse response) {
if (iCar_receiveService.updateById(car_receive)) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
@RequestMapping("/delete")
@ResponseBody
public Object update(String[] id, HttpServletRequest request, HttpServletResponse response) {
if (iCar_receiveService.deleteBatchIds(Arrays.asList(id))) {
return ajaxSuccess();
} else {
return ajaxError();
}
}
}
<file_sep>package com.ossjk.asset.book.service;
import com.ossjk.asset.book.entity.Furniture_book;
import com.ossjk.asset.book.vo.Furniture_bookVo;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 家具图书明细 服务类
* </p>
*
* @author lxw
* @since 2020-01-09
*/
@Service
public interface IFurniture_bookService extends IService<Furniture_book> {
Page selectFurniture_bookVo(Page page,Wrapper wrapper);
List<Furniture_book> selectAll();
}
<file_sep>package com.ossjk.asset.house.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ossjk.asset.house.entity.House_receive;
import com.ossjk.asset.house.vo.House_receiveVo;
/**
* <p>
* 房屋分配情况 Mapper 接口
* </p>
*
* @author lym
* @since 2020-01-12
*/
public interface House_receiveMapper extends BaseMapper<House_receive> {
List<House_receiveVo> selectHouse_receiveVo(Page page, @Param("ew") Wrapper wrapper);
House_receiveVo selectHouse_receiveVoById(String id);
}<file_sep>package com.ossjk.asset.land.mapper;
import com.ossjk.asset.land.entity.Land;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 土地明细 Mapper 接口
* </p>
*
* @author lym
* @since 2020-01-12
*/
public interface LandMapper extends BaseMapper<Land> {
}<file_sep>package com.ossjk.asset.house.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ossjk.asset.house.entity.House;
import com.ossjk.asset.house.entity.House_receive;
import com.ossjk.asset.house.mapper.House_receiveMapper;
import com.ossjk.asset.house.service.IHouseService;
import com.ossjk.asset.house.service.IHouse_receiveService;
import com.ossjk.asset.house.vo.House_receiveVo;
import com.ossjk.asset.land.entity.Land_receive;
import com.ossjk.asset.system.entity.Code_rule;
import com.ossjk.asset.system.service.ICode_ruleService;
/**
* <p>
* 房屋分配情况 服务实现类
* </p>
*
* @author lym
* @since 2020-01-12
*/
@Service
public class House_receiveServiceImpl extends ServiceImpl<House_receiveMapper, House_receive>
implements IHouse_receiveService {
@Autowired
private IHouse_receiveService ihrs;
@Autowired
private IHouseService ihs;
@Autowired
private ICode_ruleService icrs;
@Transactional
@Override
public boolean insert(House_receive entity) {
Wrapper wrapper = Condition.create().eq("name", "房屋单据");
Code_rule one = icrs.selectOne(wrapper);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
String year = sdf.format(new Date()).substring(2);
String cur = (Integer.parseInt(one.getCurrent()) + 1) + "";
for (int i = cur.length(); i < 4; i++) {
cur = "0" + cur;
}
entity.setReceipt(one.getRule() + year + cur);
one.setCurrent(cur);
icrs.updateById(one);
return super.insert(entity);
}
@Override
public Page selectHouse_receiveVo(Page page, Wrapper wrapper) {
SqlHelper.fillWrapper(page, wrapper);
page.setRecords(baseMapper.selectHouse_receiveVo(page, wrapper));
return page;
}
@Override
public House_receiveVo selectVoById(String id) {
return baseMapper.selectHouse_receiveVoById(id);
}
@Override
public boolean insertVo(House_receiveVo hrv) {
try {
hrv.setId(UUID.randomUUID().toString().replaceAll("-", ""));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
String format = dateFormat.format(new Date());
hrv.setCrtm(format);
hrv.setMdtm(format);
if(!ihrs.insert(hrv)) {
new Exception();
}
House h = new House();
h.setId(hrv.getHid());
h.setStatus(1);
h.setService_life(hrv.getService_life());
if(!ihs.updateById(h)) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean updateVoById(House_receiveVo hrv ,String ohid) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
hrv.setMdtm(dateFormat.format(new Date()));
if(!ihrs.updateById(hrv)) {
new Exception();
}
if(!ohid.equals(hrv.getHid())) {
House selectById = ihs.selectById(ohid);
selectById.setStatus(0);
if(!ihs.updateById(selectById)) {
new Exception();
}
}
House h = new House();
h.setStatus(1);
h.setId(hrv.getHid());
h.setService_life(hrv.getService_life());
if(!ihs.updateById(h)) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
@Override
public boolean deleteBatchIdsAndReset(String[] id) {
try {
List<House_receive> selectBatchIds = ihrs.selectBatchIds(Arrays.asList(id));
List<String> hid=new ArrayList();
for (House_receive house_receive : selectBatchIds) {
hid.add(house_receive.getHid());
}
List<House> selectBatchIds2 = ihs.selectBatchIds(hid);
for (House house : selectBatchIds2) {
house.setStatus(0);
}
if(!ihs.updateBatchById(selectBatchIds2))
{
new Exception();
}
// for (String string : id) {
// House selectById = ihs.selectById(ihrs.selectById(string).getHid());
// selectById.setStatus(0);
// if (!ihs.updateById(selectById)) {
// new Exception();
// }
// }
if (!ihrs.deleteBatchIds(Arrays.asList(id))) {
new Exception();
}
} catch (Exception e) {
return false;
}
return true;
}
}
<file_sep># assets
资产系统项目
| 4e0e0cf7b123d49c659eafe8277335a16302f72e | [
"SQL",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 65 | Java | YaingLin/assets | c5df8bd51b4a1001ac1209a0039b4de64db1b520 | 6b6d9126c75bface295ce020459b03cbf4912f70 |
refs/heads/master | <repo_name>iorixq01/iorixq01.GitHub.io<file_sep>/Resume/resume.js
document.getElementById("btn").onclick = function(){
document.getElementById("test").innerHTML = "Call me:13669949698";
} | e6dadd51decd16df4518e7a1c7f7ccf49fb42a42 | [
"JavaScript"
] | 1 | JavaScript | iorixq01/iorixq01.GitHub.io | aa7679927683fd318367b0208122f59b95603557 | 479beaa7286f0365a2e7ce0afab440bf2ecdebdd |
refs/heads/master | <file_sep>class TextsController < ApplicationController
def new
@party_id = params[:party_id]
end
def create
friend_name = params[:friend_name]
party_id = Party.find(params[:party_id]).id
twilio = TwilioFacade.new(friend_name, current_user.name, params[:phone_number], party_id)
twilio.text
flash[:alert] = "Your text message to #{friend_name} was sent!"
redirect_to '/dashboard'
end
end
<file_sep>require "rails_helper"
describe TwilioFacade do
subject { TwilioFacade.new("friend", "User", "720-730-7827", 5) }
it 'exists' do
expect(subject).to be_a(TwilioFacade)
end
context 'instance methods' do
context '#number' do
it 'should format phone number for Twilio' do
expected = '+17207307827'
expect(subject.number).to eq(expected)
end
end
context '#text_link' do
it 'should format a link for the given party' do
expected = "https://star-party.herokuapp.com/parties/5"
expect(subject.text_link).to eq(expected)
end
end
context '#text_body' do
it 'should format a set body for text' do
expected = "Hi Friend! User is attending a Star Party and wants you to join! You can see more info at https://star-party.herokuapp.com/parties/5."
expect(subject.text_body).to eq(expected)
end
end
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Party.destroy_all
User.destroy_all
host = User.create(name: "Test Host", email: "<EMAIL>", password: '<PASSWORD>')
user_1 = User.create(name: "Test User", email: "<EMAIL>", password: '<PASSWORD>')
user_2 = User.create(name: "Test User2", email: "<EMAIL>", password: '<PASSWORD>')
Party.create(title: "Comet Party",
date: "01-01-2019",
description: "View Halley's Comet",
street_address: "9357 W 26th Ave",
city: "Wheat Ridge",
state: "CO",
zip_code: 80033,
latitude: 39.754721,
longitude: -105.1089577,
host_id: host.id)
Party.create(title: "Nebula Party",
date: "11-11-2018",
description: "View Turing Nebula",
street_address: "1700 N Sheridan Blvd",
city: "Denver",
state: "CO",
zip_code: 80212,
latitude: 39.744609,
longitude: -105.0550696,
host_id: host.id)
Party.create(title: "Meteor Party",
date: "07-07-2020",
description: "View Lovelace Meteor Shower",
street_address: "15600 W Morrison Rd",
city: "Lakewood",
state: "CO",
zip_code: 80228,
latitude: 39.6497555,
longitude: -105.1629224,
host_id: host.id)
Party.create(title: "Meteor Party",
date: "07-08-2019",
description: "View Lovelace Meteor Shower",
street_address: "980 Grant Street",
city: "Denver",
state: "CO",
zip_code: 80203,
latitude: 39.731650,
longitude: -104.983180,
host_id: host.id)
<file_sep>require 'rails_helper'
describe 'visitor searches for parties' do
context 'with a valid zip code' do
it 'returns all parties' do
VCR.use_cassette("create 5 parties3") do
create_list(:party, 5)
end
VCR.use_cassette("visit root") do
visit '/'
end
fill_in :q_find, with: 80203
VCR.use_cassette("click find to find") do
find(".find", visible: false).click
end
expect(current_path).to eq("/party_search")
expect(page).to have_css(".party-card", count: 5)
within(first(".party-card")) do
expect(page).to have_css(".party-title")
expect(page).to have_css(".date")
expect(page).to have_css(".description")
expect(page).to have_css(".location")
end
end
it 'does not return past parties' do
host = create(:user)
VCR.use_cassette("create past, present, future party") do
@today_party = create(:party, title: "Today Party", date: Date.today)
@future_party = create(:party, title: "Future Party", date: "11-11-2018")
@past_party = create(:party, title: "Past Party", date: "07-07-2017")
end
VCR.use_cassette("visit root") do
visit '/'
end
fill_in :q_find, with: 80203
VCR.use_cassette("find to not show past parties") do
find(".find", visible: false).click
end
expect(page).to have_css(".party-card", count: 2)
expect(page).to have_content(@today_party.title)
expect(page).to have_content(@future_party.title)
expect(page).to_not have_content(@past_party.title)
end
it 'does not return parties outside 15mi radius' do
host = create(:user)
VCR.use_cassette("create near and far parties2") do
@near_party = create(:party, title: "Near Party")
@far_party = create(:party,
title: "Far Party",
zip_code: 70119,
street_address: "980 Grant Street",
city: "New Orleans",
state: "LA"
)
end
VCR.use_cassette("visit root") do
visit '/'
end
fill_in :q_find, with: 80203
VCR.use_cassette("find to not show far parties") do
find(".find", visible: false).click
end
expect(page).to have_css(".party-card", count: 1)
expect(page).to have_content(@near_party.title)
expect(page).to_not have_content(@far_party.title)
end
end
context 'with zip code corresponding to zero parties' do
it 'returns a message on index page' do
VCR.use_cassette("create standard party") do
create(:party)
end
VCR.use_cassette("visit root") do
visit '/'
end
fill_in :q_find, with: 14624
VCR.use_cassette("click another other find") do
find(".find", visible: false).click
end
expect(current_path).to eq("/")
expect(page).to_not have_css(".party")
expect(page).to have_content("No parties found near 14624. Try another search!")
end
end
end
<file_sep>class ForecastController < ApplicationController
def index
@zip_code = params[:zip_code]
if valid_zip?
@forecast_results = ForecastFacade.new(@zip_code)
else
flash[:alert] = "Sorry, no data for #{@zip_code}. Please try again."
redirect_to '/'
end
end
private
def valid_zip?
@zip_code.to_lat && @zip_code.to_lon
end
end
<file_sep>require 'rails_helper'
describe DarkskyService do
subject { DarkskyService.new("80203") }
context '#dark_sky_data' do
it 'returns dark sky json data' do
results = VCR.use_cassette("pull dark sky data") do
subject.dark_sky_data[:data]
end
expect(results.first).to have_key(:time)
expect(results.first).to have_key(:moonPhase)
expect(results.first).to have_key(:precipProbability)
expect(results.first).to have_key(:cloudCover)
end
context "#location" do
it 'returns string of lat and long' do
expect(subject.location).to eq("39.731286,-104.98306")
end
end
end
end
<file_sep>require "rails_helper"
feature "As an authenticated user" do
context "when on my user dashboard" do
scenario "I can see my parties" do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("create_6_parties") do
@party_1 = create(:party, host_id: user.id)
@party_2 = create(:party)
@party_3 = create(:party)
@party_4 = create(:party)
@party_5 = create(:party, host_id: user.id)
@party_6 = create(:party)
@party_2.users << user
@party_6.users << user
end
VCR.use_cassette('new-dashboard') do
visit '/dashboard'
end
within('.hosted') do
expect(page).to have_content(@party_1.title)
expect(page).to have_content(@party_1.view_date)
expect(page).to have_content(@party_5.title)
expect(page).to have_content(@party_5.view_date)
end
within('.attending') do
expect(page).to have_content(@party_2.title)
expect(page).to have_content(@party_2.view_date)
expect(page).to have_content(@party_6.title)
expect(page).to have_content(@party_6.view_date)
expect(page).to_not have_content(@party_1.title)
expect(page).to_not have_content(@party_5.title)
end
expect(page).to_not have_content(@party_3.title)
expect(page).to_not have_content(@party_4.title)
end
end
end
<file_sep>class PartySearchController < ApplicationController
def index
@party_search_result = PartySearchResult.new(params[:q_find])
if @party_search_result.parties == []
flash[:notice] = "No parties found near #{params[:q_find]}. Try another search!"
redirect_to "/"
end
end
end
<file_sep>class UserPartyFacade
def initialize(user_id)
@user_id = user_id
end
def hosting
Party.where(host_id: @user_id)
end
def attending
Party.select('parties.*')
.joins(:user_parties)
.where("user_parties.user_id = ?", @user_id)
end
end
<file_sep>require "rails_helper"
feature "As an authenticated user" do
scenario "I can view ten day forecast with valid zip code" do
VCR.use_cassette("visit forecast path as user") do
visit forecast_path(zip_code: "80203")
end
expect(page).to have_css('.time')
expect(page).to have_css('.weather-card', count: 8)
within(first('.weather-card')) do
expect(page).to have_css('.cloud-cover')
expect(page).to have_css('.moon-phase')
expect(page).to have_css('.rain-chance')
expect(page).to have_css('.moon-name')
end
expect(page).to have_css('.select')
end
scenario "invalid zip prompts me to try again" do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("home page") do
visit '/'
end
invalid_zip = 87822
fill_in :zip_code, with: invalid_zip
VCR.use_cassette("click plan") do
find(".plan-party", visible: false).click
expect(current_path).to eq('/')
expect(page).to have_content("Sorry, no data for #{invalid_zip}. Please try again.")
end
end
end
<file_sep>Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'welcome#index'
namespace :api do
namespace :v1 do
namespace :parties do
get '/find_all', to: 'search#index' #by zip
end
scope module: 'parties' do
resources :parties, only: [:index, :show]
end
end
end
get '/forecast', to: 'forecast#index'
get "/party_search", to: 'party_search#index'
resources :parties, only: [:new, :create, :show, :destroy]
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
get '/auth/:provider/callback', to: 'sessions#create'
get '/logout', to: 'sessions#destroy'
get '/dashboard', to: 'dashboard#show'
get '/text', to: 'texts#new'
post '/text', to: 'texts#create'
resources :users, only: [:new, :create]
end
<file_sep>class DarkskyService
def initialize(zip_code)
@zip_code = zip_code
end
def location
@zip_code.to_lat + "," + @zip_code.to_lon
end
def dark_sky_data
JSON.parse(response.body, symbolize_names: true)[:daily]
end
def response
@response ||= Faraday.get("https://api.darksky.net/forecast/#{ENV["darksky_api_key"]}/#{location}")
end
end
<file_sep>require 'rails_helper'
describe "Parties API" do
it "sends a list of parties" do
VCR.use_cassette("create 5 parties") do
create_list(:party, 5)
end
VCR.use_cassette("get all parties api") do
get '/api/v1/parties'
end
expect(response).to be_successful
parties = JSON.parse(response.body)
expect(parties.count).to eq(5)
end
it "can get one party by its id" do
VCR.use_cassette("create standard party") do
@id = create(:party).id
end
VCR.use_cassette("visit party show api") do
get "/api/v1/parties/#{@id}"
end
party = JSON.parse(response.body)
expect(response).to be_successful
expect(party["id"]).to eq(@id)
end
it "returns all parties by zip code" do
VCR.use_cassette("create parties by zip") do
@party1, @party2 = create_list(:party, 2, zip_code: 80000)
@party3 = create(:party, zip_code: 70000)
end
VCR.use_cassette("return parties in certain zip code api") do
get "/api/v1/parties/find_all?zip_code=#{@party1.zip_code}"
end
expect(response).to be_successful
parties = JSON.parse(response.body)
expect(response.body).to include("#{@party1.id}")
expect(response.body).to include("#{@party2.id}")
expect(response.body).to_not include("#{@party3.zip_code}")
end
end
<file_sep>require "rails_helper"
describe "As a visitor" do
describe "I can create and account" do
it "should let me register and redirect me to the dashboard" do
user_info = { name: "<NAME>",
email: "<EMAIL>",
phone_number: "123-456-7890",
zip_code: 80202
}
VCR.use_cassette("visit root") do
visit "/"
end
VCR.use_cassette("click login") do
click_on("Log In / Sign Up")
end
expect(current_path).to eq("/login")
VCR.use_cassette("click register here") do
click_on("Register Here")
end
expect(current_path).to eq("/users/new")
fill_in "Name", with: user_info[:name]
fill_in "Email", with: user_info[:email]
fill_in "Phone Number", with: user_info[:phone_number]
fill_in "Zip Code", with: user_info[:zip_code]
fill_in "Password", with: "<PASSWORD>"
fill_in "Confirm Password", with: "<PASSWORD>"
VCR.use_cassette("click create user") do
click_on("Create User")
end
expect(current_path).to eq("/dashboard")
expect(page).to have_content("Welcome, #{user_info[:name]}")
expect(page).to have_link("My Account")
expect(page).to_not have_link("Log In / Sign Up")
end
end
end
<file_sep>class PartiesController < ApplicationController
def new
if current_user
@party = Party.new(new_party_params)
else
flash[:notice] = 'Must be logged in to create party.'
redirect_to "/"
end
end
def create
if current_user
party = Party.new(party_params)
party.host_id = current_user.id
time = { hour: time_params["date(4i)"], min: time_params["date(5i)"] }
party.update(date: party.date.change(time))
if Geocoder.coordinates(party.address)
coordinates = Geocoder.coordinates(party.address)
party.latitude = coordinates[0]
party.longitude = coordinates[1]
if party.save
redirect_to party_path(party)
else
flash[:notice] = "Something went wrong. \n
Please fill in all fields"
redirect_to new_party_path(party_params)
end
else
flash[:notice] = 'Must put in valid address.'
redirect_to new_party_path(party_params)
end
else
flash[:notice] = 'Must be logged in to create party.'
render :new
end
end
def show
@party = Party.find(params[:id])
@party.attendance(current_user, params[:attendance]) if params[:attendance]
end
def destroy
party = Party.find(params[:id])
if party.destroy
flash[:notice] = "Your party was successfully cancelled."
redirect_to '/dashboard'
else
flash[:alert] = "Something went wrong, your party wasn't cancelled."
render :show
end
end
private
def party_params
params.require(:party).permit(:title, :description, :date, :street_address, :city, :zip_code, :state)
end
def new_party_params
params.permit(:zip_code, :date)
end
def time_params
params.require(:time).permit(:date)
end
end
<file_sep>class User < ApplicationRecord
validates :email, uniqueness: true, presence: true
validates_presence_of :password, require: true
validates_presence_of :name,
:email
has_many :parties, dependent: :destroy
has_many :user_parties, dependent: :destroy
has_many :parties, through: :user_parties, dependent: :destroy
has_secure_password
enum role: %w(user admin)
def self.create_with_omniauth(auth)
create! do |user|
user.name = auth[:info][:name]
user.email = auth[:info][:email]
user.password = auth[:uid]
end
end
end
<file_sep>require "rails_helper"
feature "As an authenticated user" do
context "when I mark to attend a party" do
it 'can send a text to a friend to invite them' do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("create standard party") do
@party = create(:party)
end
VCR.use_cassette("party_show") do
visit "/parties/#{@party.id}"
click_on("Attend")
end
VCR.use_cassette("text") do
click_on("Text a friend")
expect(current_path).to eq('/text')
friend = "Bob"
fill_in :friend_name, with: friend
fill_in :phone_number, with: "+17203620696"
end
VCR.use_cassette("dashboard") do
click_on("Submit")
friend = "Bob"
expect(current_path).to eq('/dashboard')
expect(page).to have_content("Your text message to #{friend} was sent!")
end
end
end
end
<file_sep>class ForecastFacade
attr_reader :zip_code
def initialize(zip_code)
@zip_code = zip_code
end
def day_forecast_objects
service.dark_sky_data[:data].map do |day_forecast_data|
DayForecast.new(day_forecast_data)
end
end
private
def service
@service ||= DarkskyService.new(zip_code)
end
end
<file_sep>require 'rails_helper'
describe DayForecast do
attributes = {"time": 1540360800,
"summary": "Rain until evening.",
"moonPhase": 0.51,
"precipProbability": 0.87,
"cloudCover": 0.99}
subject { DayForecast.new(attributes) }
it 'exists' do
expect(subject).to be_a DayForecast
end
it 'has attributes' do
expect(subject.time).to eq '2018-10-24 00:00:00 -0600'
end
context 'instance methods' do
context '#star_party_rating' do
it 'uses attributes to calculate a star_party_rating' do
expect(subject.star_party_rating).to eq(4.1)
end
end
end
end
<file_sep>require 'rails_helper'
describe 'user visits the landing page' do
scenario 'as a visitor' do
VCR.use_cassette("visit root") do
visit '/'
end
expect(page).to have_link "Log In / Sign Up"
expect(page).to have_button "Find a Star Party"
expect(page).to have_button "Plan a Star Party"
expect(page).to have_link "About this photo. NASA"
end
end
<file_sep>$(document).ready(function(){
$('.bottom-weather-card').hide();
$('.select').click(function(button) {
button.stopPropagation();
});
$(".top-weather-card").click(function(){
if ($('.bottom-weather-card').height() > 0) {
$(this).parents().siblings().children('.bottom-weather-card').slideUp();
}
$(this).siblings('.bottom-weather-card').slideToggle();
});
});
<file_sep>require "rails_helper"
describe UserPartyFacade do
before(:each) do
@user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@user)
@facade = UserPartyFacade.new(1)
VCR.use_cassette("create_6_parties") do
@party_1 = create(:party, host_id: @user.id)
@party_2 = create(:party)
@party_3 = create(:party)
@party_4 = create(:party)
@party_5 = create(:party, host_id: @user.id)
@party_6 = create(:party)
@party_2.users << @user
@party_6.users << @user
end
end
it 'exists' do
expect(@facade).to be_a(UserPartyFacade)
end
context '#instance methods' do
context '#hosting' do
it 'should return array of parties that user is hosting' do
expected = [@party_1, @party_5]
expect(@facade.hosting).to eq(expected)
end
end
context '#attending' do
it 'should return array of parties that user is attending' do
expected = [@party_2, @party_6]
expect(@facade.attending).to eq(expected)
end
end
end
end
<file_sep>require 'rails_helper'
describe "As a guest user" do
describe "When I go to log in" do
it "should take me to my dashboard" do
user = create(:user)
VCR.use_cassette("visit login page") do
visit("/login")
end
fill_in "Email", with: user.email
fill_in "Password", with: <PASSWORD>
VCR.use_cassette("click login") do
click_on("Login")
end
expect(current_path).to eq("/dashboard")
end
end
describe "When I log in with google" do
before(:each) do
def stub_omniauth
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:default] = OmniAuth::AuthHash.new({
info: { email: "<EMAIL>", name: "Ben"},
:uid => "11"
})
end
stub_omniauth
end
it "should take me to my dashboard" do
VCR.use_cassette("visit google login page") do
visit("/login")
end
VCR.use_cassette("click login with google") do
click_on("Login with Google")
end
expect(current_path).to eq("/dashboard")
end
end
end
<file_sep>require "rails_helper"
feature 'As an authenticated user' do
context 'I can visit a party show' do
scenario 'and click to attend the party' do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("create standard party") do
@fun_party = create(:party)
end
VCR.use_cassette("visit ANOTHER party") do
visit "/parties/#{@fun_party.id}"
end
expect(page).to have_content(@fun_party.title)
expect(page).to have_content("Date: #{@fun_party.view_date}")
expect(page).to have_content("Time: #{@fun_party.view_time}")
expect(page).to have_content(@fun_party.description)
expect(page).to have_content("Hosted By: #{@fun_party.host.name}")
VCR.use_cassette("click attend") do
click_on("Attend")
end
expect(current_path).to eq("/parties/#{@fun_party.id}")
expect(page).to have_content("You are attending this party.")
expect(page).to have_content("Cancel Attendance")
end
end
context 'as the host of a party' do
it 'should give me different options on party show' do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("create standard party") do
@fun_party = create(:party, host_id: user.id)
end
VCR.use_cassette("visit ANOTHER party") do
visit "/parties/#{@fun_party.id}"
end
expect(page).to_not have_css(".attend")
expect(page).to_not have_content("Cancel Attendance")
VCR.use_cassette("cancelled_dash") do
click_on "Cancel Party"
expect(current_path).to eq('/dashboard')
expect(page).to have_content("Your party was successfully cancelled.")
expect(page).to_not have_content(@fun_party.title)
end
end
end
end
<file_sep>class DayForecast
attr_reader :moon_phase,
:rain_chance,
:cloud_cover,
:summary
def initialize(data)
@time = data[:time]
@moon_phase = data[:moonPhase]
@rain_chance = data[:precipProbability]
@cloud_cover = data[:cloudCover]
@summary = data[:summary]
end
def time
Time.at(@time)
end
def star_party_rating
raw_score = moonscore + rain_chance + cloud_cover
(10 - ((raw_score) * 2.5)).round(2)
end
def image_tag
moon = (moon_phase * 10).round()
cloud = (cloud_cover * 10).round()
cloud = 9 if cloud == 10
moon = 0 if moon == 10
moon = 0 if cloud == 9
"#{cloud}#{moon}"
end
def moon_name
moon_phase_namer.each do |range, name|
if range === moon_phase
return name
end
end
end
private
def moon_phase_namer
{
0..0.2 => "New Moon",
0.3..0.24 => "Waxing Crescent",
0.25 => "First Quarter Moon",
0.26...0.49 => "Waxing Gibbous",
0.5 => "Full Moon",
0.51..0.74 => "Waning Gibbous",
0.75 => "Last Quarter Moon",
0.76..0.97 => "Waning Crescent",
0.98..1 => "New Moon"
}
end
def moon_phase_converter
{
0..0.25 => 0,
0.26...0.5 => 0.5,
0.5 => 1,
0.51..0.75 => 0.5,
0.76..1 => 0
}
end
def moonscore
moon_phase_converter.each do |range, score|
if range === moon_phase
return score
end
end
end
end
<file_sep>$(document).ready(function(){
$(document).click(function(){
$('.hidden-form').slideUp();
});
$('.zip-search').click(function(button) {
button.stopPropagation();
});
$('.hidden-form').click(function(button) {
button.stopPropagation();
});
$('.hidden-form').hide();
$('.hidden-button').hide();
$(".zip-search").click(function(){
if ($('.hidden-form').height() > 0) {
$(this).parents().parents().siblings().find('.hidden-form').slideUp();
}
$(this).parent().children('.hidden-form').slideToggle(function(){
$(this).children(".hidden-drop").focus();
});
});
});
<file_sep># README
[](https://codeclimate.com/github/BeccaHyland/star_party/maintainability)
This project was developed out of a need and desire to create more interest and community around the astronomy community. One of the most exciting events in astronomy is the Star Party. Typically, this is when people gather, and with the help of an expert and a telescope, they learn and admire the sights in the night sky. Sounds exciting, but the problem is finding these parties! Sometimes you can find a stray post on meetup or a local astronomical society website, but you have to spend too much time searching just to find an event near you. Enter the StarParty app, where anyone can create a Star Party or search for a Star Party all from one easy to use app!
Built by:
- <NAME>: github.com/BeccaHyland
- <NAME>: github.com/bghalmi
- <NAME>: github.com/wehttamclan
- <NAME>: github.com/KathleenYruegas
## NASA Astronomy Picture of the Day
The background image is sourced from NASA's astronomy picture of the day. Each day a different image or photograph of our fascinating universe is featured.
<em><img src="https://github.com/BeccaHyland/star_party/blob/readme_apod/app/assets/images/landing1.png" alt="Image of Landing Page" width="280" height="496"/></em>
<em><img src="https://github.com/BeccaHyland/star_party/blob/readme_apod/app/assets/images/landing2.png" alt="Image of Landing Page" width="280" height="496"/></em>
<em><img src="https://github.com/BeccaHyland/star_party/blob/readme_apod/app/assets/images/landing3.png" alt="Image of Landing Page" width="280" height="496"/></em>
## Usage
To use the app, simply visit https://star-party.herokuapp.com/ and start browsing around!
You can sign in with Google (using OAuth) or you can create an account on the app.
Feel free to clone down this repo and play with the code!
* Technologies used:
- Ruby 2.4.2
- Rails 5.1.6
* System dependencies
- `gem 'area'` https://github.com/jgv/area
- allows us to easily convert zip codes to latituges and longitudes
- `gem 'faraday'` https://github.com/lostisland/faraday
- for making our API calls
- `gem 'geocoder'`
- allows us to search a 15 mile radius of given zip code to find nearby parties
To user our app on your local, you will need these API Keys:
- https://api.nasa.gov/index.html#apply-for-an-api-key (can be requested for free)
- NASA API used to pull the background image, the NASA Astronomy Picture of the Day stored as `NASA_API_KEY`
Y
- https://darksky.net/dev/docs (can be resquested for free)
- Dark Sky API used for all weather and moon related information stored as `darksky_api_key`
- https://www.twilio.com/docs/sms/quickstart/ruby
- Twilio used for sending text messages stored as `twilio_account_sid`, `twilio_auth_token`, and `twilio_phone_number`
- https://developers.google.com/identity/protocols/OAuth2
- Google OAuth used to sign in users. You'll need to add a `GOOGLE_CLIENT_ID` and a `GOOGLE_CLIENT_SECRET`
* Configuration
To clone down and configure this project on your local, follow these steps in your terminal:
```
1. git clone <EMAIL>:BeccaHyland/star_party.git
2. bundle install
3. bundle update
4. rake db:{create,migrate,seed}
(Running seed is optional. If run, it will load a few fake parties for display
and development purposes.)
```
* How to run the test suite
This project uses RSpec for its test suite. To run the test, cd into the root of the project and run ```rspec```.
* Services (job queues, cache servers, search engines, etc.)
# Api endpoints
## RESTful API routes
#### `/api/v1/parties/:id`
* Return data from an individual Star Party.
#### `/api/v1/parties`
* Return data from all Star Party.
## Search API routes
Use search parameters to find specific Star Parties.
#### `/api/v1/parties/find`
* Find data for an individual Star Party matching search parameters.
#### `/api/v1/parties/find_all`
* Find data for all Star Parties matching search parameters.
<file_sep>class TwilioFacade
def initialize(friend_name, user_name, number, party_id)
@client = Twilio::REST::Client.new(ENV["twilio_account_sid"], ENV["twilio_auth_token"])
@friend_name = friend_name
@user_name = user_name
@number = number
@party_id = party_id
end
def text
@client.messages.create(
from: ENV["twilio_phone_number"],
to: number,
body: text_body)
end
def friend_name
@friend_name.capitalize
end
def number
@number.delete('^0-9').prepend("+1")
end
def text_link
link = "https://star-party.herokuapp.com/parties/#{@party_id}"
end
def text_body
"Hi #{friend_name}! #{@user_name} is attending a Star Party and wants you to join! You can see more info at #{text_link}."
end
end
<file_sep>require 'rails_helper'
describe Party, type: :model do
describe 'validations' do
it {should validate_presence_of(:title)}
it {should validate_presence_of(:date)}
it {should validate_presence_of(:zip_code)}
end
describe 'relationships' do
it { should belong_to(:host) }
it { should have_many(:user_parties) }
it { should have_many(:users) }
end
describe 'instance methods' do
it '#location' do
VCR.use_cassette("create standard party") do
@p = create(:party)
end
expect(@p.location).to eq(
"#{@p.street_address}, #{@p.city}, #{@p.state} #{@p.zip_code}")
end
context '#attendance' do
it 'should set or delete user relationship to party' do
VCR.use_cassette("create standard party") do
@party = create(:party)
end
user = create(:user)
expect(@party.users.first).to be(nil)
@party.attendance(user, "attend")
expect(@party.users.first).to eq(user)
@party.attendance(user, "cancel")
expect(@party.users.first).to be(nil)
end
end
end
end
<file_sep>require "rails_helper"
describe ForecastFacade do
subject { ForecastFacade.new("80203") }
it 'exists' do
expect(subject).to be_a(ForecastFacade)
end
it 'has zip code attribute' do
expect(subject.zip_code).to eq("80203")
end
context 'instance methods' do
context '#day_forecast_objects' do
it 'returns dark sky json data' do
results = VCR.use_cassette("day_forecast_objects from facade2") do
subject.day_forecast_objects
end
expect(results.length).to eq(8)
expect(results.first).to be_a DayForecast
end
end
context '#zip_code' do
it 'returns the zip code passed in' do
zip_code = subject.zip_code
expect(zip_code).to eq('80203')
end
end
end
end
<file_sep>FactoryBot.define do
factory :party do
title { Faker::Book.title }
date { "07-08-2099 10:54:00" }
description { "Viewing the Sample Celestial Event" }
street_address { "980 Grant Street" }
city { "Denver" }
state { "CO"}
zip_code { 80203 }
association :host, factory: :user
end
end
<file_sep>require 'spec_helper'
describe ApodFacade do
it 'exists' do
af = ApodFacade.new
expect(af).to be_a(ApodFacade)
end
end
<file_sep>require 'rails_helper'
describe 'nasa api endpoints' do
it 'should return apod data' do
apod_json = VCR.use_cassette("new apod service") do
ApodService.new.get_json
end
expect(apod_json[:title]).to be_a String
if apod_json[:copyright]
expect(apod_json[:copyright]).to be_a String
end
if apod_json[:hdurl]
expect(apod_json[:hdurl]).to be_a String
end
end
end
<file_sep>class ApodService
def conn
Faraday.new(url: "https://api.nasa.gov")
end
def response
conn.get("/planetary/apod?api_key=#{ENV["NASA_API_KEY"]}")
end
def get_json
JSON.parse(response.body, symbolize_names: true)
end
end
<file_sep>require 'rails_helper'
describe PartySearchResult do
it 'exists' do
psr = PartySearchResult.new(80203)
expect(psr).to be_a(PartySearchResult)
end
end
<file_sep>class ApodFacade
def source
apod_background || default_background
end
def apod_background
return_json[:hdurl]
end
def default_background
"https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/Hubble_ultra_deep_field_high_rez_edit1.jpg/768px-Hubble_ultra_deep_field_high_rez_edit1.jpg"
end
def title
return_json[:title]
end
# def copyright
# if return_json[:copyright]
# return_json[:copyright]
# else
# "Public Domain"
# end
# end
private
def return_json
service.get_json
end
def service
@service ||= ApodService.new
end
end
<file_sep>require 'rails_helper'
describe ApodService do
it 'exists' do
as = ApodService.new
expect(as).to be_a(ApodService)
end
end
<file_sep>class Api::V1::Parties::SearchController < ApplicationController
def index
render json: Party.where(search_params)
end
private
def search_params
params.permit(:zip_code)
end
end
<file_sep>require "rails_helper"
feature 'As an guest user' do
context 'I can visit a party show' do
scenario 'and view party details' do
VCR.use_cassette("create standard party") do
@fun_party = create(:party)
end
VCR.use_cassette("visit party not logged in") do
visit "/parties/#{@fun_party.id}"
end
expect(page).to have_content(@fun_party.title)
expect(page).to have_content("Date: Aug. 7, 2099")
expect(page).to have_content("Time: 10:54 AM")
expect(page).to have_content(@fun_party.description)
expect(page).to have_content("Please log in to view party details and to rsvp.")
expect(page).to_not have_content("Hosted By: #{@fun_party.host.name}")
within(".party-show-card") do
expect(page).to_not have_content("Attend")
end
end
end
end
<file_sep>class PartySearchResult
def initialize(zip_code)
@zip_code = zip_code
end
def parties
@parties ||= (Party.where('date >= ?', Date.today).near(@zip_code, 15)).to_a
exact_zip = (Party.where('zip_code = ? AND date >= ?', @zip_code, Date.today)).to_a
exact_zip.each do |party|
@parties << party
end
@parties.uniq
end
end
<file_sep># This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'vcr'
VCR.configure do |config|
config.allow_http_connections_when_no_cassette = true
config.cassette_library_dir = "fixtures/vcr_cassettes"
config.hook_into :webmock
end
DatabaseCleaner.strategy = :truncation
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
config.include Capybara::DSL
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.before :each do
DatabaseCleaner.clean
end
config.after :each do
DatabaseCleaner.clean
end
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
<file_sep>require 'rails_helper'
feature 'As a user' do
scenario 'fills out new party form' do
user = create(:user)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
VCR.use_cassette("visit forecast path as user to create") do
visit forecast_path(zip_code: '80033')
end
within(first('.weather-card')) do
VCR.use_cassette("click select this day") do
click_on 'Select this Day'
end
end
expect(current_path).to eq '/parties/new'
expect(find_field('party_zip_code').value).to eq('80033')
# expect(page).to have_content(date)
fill_in :party_title, with: 'This is my party.'
fill_in :party_description, with: 'Party under the stars.'
fill_in :party_street_address, with: '9357 W 26th Ave'
fill_in :party_city, with: 'Wheat Ridge'
select 11, from: :time_date_4i
select 15, from: :time_date_5i
select 'Colorado', from: 'party[state]'
VCR.use_cassette("click create a star party", :allow_unused_http_interactions => false) do
click_on 'Create a Star Party'
end
expect(current_path).to eq '/parties/1'
expect(page).to have_content "11:15 AM"
expect(Party.last.latitude).to_not be(nil)
expect(Party.last.longitude).to_not be(nil)
end
end
<file_sep>$(document).ready(function () {
$('#party_title').on("blur", function () {
if (!this.value) {
$(this).css("border", '2px solid red');
$(this).attr("placeholder", "Title (required field)");
}
else {
$('#party_title').css("border", '2px solid black');
}
});
$('#party_zip_code').ready(function () {
if (!this.value) {
$('#party_zip_code').css("border", '2px solid red');
$('#party_zip_code').attr("placeholder", "Zip code (required field)");
}
})
});<file_sep>class Party < ApplicationRecord
validates_presence_of :title,
:date,
:zip_code
belongs_to :host, class_name: 'User'
has_many :user_parties, dependent: :destroy
has_many :users, through: :user_parties, dependent: :destroy
geocoded_by :address
after_validation :geocode
attr_reader :address
def address
[street_address, city, zip_code, state].compact.join(", ")
end
def address_changed
street_address_changed? || city_changed? || zip_code_changed? || state_changed?
end
def view_date
self.date.strftime('%b. %-d, %Y')
end
def view_time
self.date.strftime('%I:%M %p')
end
def location
"#{self.street_address}, #{self.city}, #{self.state} #{self.zip_code}"
end
def attendance(user, rsvp)
if rsvp == 'attend'
self.users << user
elsif rsvp == 'cancel'
user_party = UserParty.where(user_id: user, party_id: self)
user_party.first.delete
end
end
end
<file_sep>require "rails_helper"
describe User do
context 'relationships' do
it { should have_many(:user_parties) }
it { should have_many(:parties) }
end
end
<file_sep>class DashboardController < ApplicationController
def show
if current_user
@user = current_user
@user_parties = UserPartyFacade.new(@user)
else
render status: 404
end
end
end
| 76694e44e8ab6e3fffa1a1e0f4db693c2925d795 | [
"JavaScript",
"Ruby",
"Markdown"
] | 46 | Ruby | wehttamclan/star_party | 94e2f17db0161d5100e7f16de2bb39ca6eeedd96 | f712c3639022c814ba761a40db626d2babf85fc0 |
refs/heads/master | <repo_name>lvazquez81/MinakoNoTango<file_sep>/MinakoNoTango/Controllers/HomeController.cs
using MinakoNoTangoLib.Entities;
using MinakoNoTangoLib.Library;
using MinakoNoTangoLib.Library.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MinakoNoTango.Controllers
{
public class HomeController : Controller
{
private TeacherModel _teacher;
private SecurityToken _token;
private IRepository _repository;
public HomeController()
{
_token = new SecurityToken()
{
Username = "Luis",
ExpirationDate = DateTime.Now.AddDays(1),
Token = "abc123"
};
_repository = new MemoryRepository();
if (_repository.GetAll().Count == 0)
{
_repository.Add(_token.Username, "hitori bochi yoru", LanguageType.English, "Probado el sistema.");
_repository.Add(_token.Username, "I am hungry", LanguageType.English, "Probado el sistema.");
}
_teacher = new TeacherModel(_repository, _token);
}
#region Index
/// <summary>
/// Home
/// </summary>
[HttpGet]
public ActionResult Index()
{
return View(_teacher);
}
#endregion
#region View
/// <summary>
/// Home
/// </summary>
[HttpGet]
public ActionResult View(int Id)
{
_teacher.LoadViewedExpression(Id);
return View(viewName: "Detail", model: _teacher.ViewedExpression);
}
#endregion
#region Add
[HttpGet]
public ActionResult Add()
{
return View("Add", new StudentModel(_repository, _token));
}
[HttpPost]
public ActionResult Add(StudentModel student)
{
student.Setup(_repository, _token);
if (student.SaveExpression())
{
return View("Index", new TeacherModel(_repository, _token));
}
else
{
return View("Add", student);
}
}
#endregion
}
}
<file_sep>/MinakoNoTango/Controllers/PhraseController.cs
using MinakoNoTango.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MinakoNoTango.Controllers
{
public class PhraseController : Controller
{
public ActionResult Index()
{
return View(new PhraseView());
}
public ActionResult Add()
{
return View(new PhraseView());
}
public ActionResult Detail()
{
return View(new PhraseView());
}
}
}
<file_sep>/MinakoNoTango.Tests/LibraryTests/StudentTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MinakoNoTangoLib.Entities;
using MinakoNoTangoLib.Library;
using MinakoNoTangoLib.Library.Models;
using Moq;
using System;
using System.Collections.Generic;
namespace MinakoNoTango.Tests.LibraryTests
{
[TestClass]
public class StudentTests
{
private IMinakoNoTangoLibrary _lib;
private SecurityToken _testSecurityToken;
[TestInitialize]
public void TestSetup()
{
IRepository testRepository = initiateFakeDatabase();
_lib = new MinakoNoTangoLibrary(testRepository);
_testSecurityToken = getTestSecurityToken();
}
private SecurityToken getTestSecurityToken()
{
string testUsername = "Dulce";
string token = "<PASSWORD>";
DateTime expiration = DateTime.Now.AddHours(1);
return new SecurityToken()
{
Username = testUsername,
Token = token,
ExpirationDate = expiration
};
}
private IRepository initiateFakeDatabase()
{
var mockDataAccess = new Mock<IRepository>();
// Mock GetAll
mockDataAccess.Setup(x => x.GetAll()).Returns(new List<PhraseEntity>()
{
new PhraseEntity(){ Id = 1, Expression = "Good morning!", AuthorName = "Minako" },
new PhraseEntity(){ Id = 2, Expression = "Konnichi wa!", AuthorName = "Chibi" },
new PhraseEntity(){ Id = 3, Expression = "Dokka e onsen e ikimashouka", AuthorName = "Chibi" },
new PhraseEntity(){ Id = 4, Expression = "I love to take photos", AuthorName = "Minako" }
});
// Mock GetSingle
mockDataAccess.Setup(x => x.GetSingle(It.IsAny<int>())).Returns(
new PhraseEntity()
{
Id = It.IsAny<int>(),
Expression = It.IsAny<string>()
});
// Mock Add
mockDataAccess
.Setup(x => x.Add(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<LanguageType>(),
It.IsAny<string>()))
.Returns(
It.IsAny<int>());
return mockDataAccess.Object;
}
}
}
<file_sep>/MinakoNoTango.Tests/LibraryTests/DulceTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MinakoNoTangoLib.Entities;
using MinakoNoTangoLib.Library;
using MinakoNoTangoLib.Library.Models;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTango.Tests.LibraryTests
{
[TestClass]
public class DulceTests
{
private StudentModel _lib;
private SecurityToken _testSecurityToken;
private IRepository _repository;
#region Test setup
[TestInitialize]
public void TestSetup()
{
_repository = initiateFakeDatabase();
_testSecurityToken = getTestSecurityToken();
}
private SecurityToken getTestSecurityToken()
{
string testUsername = "Dulce";
string token = "<PASSWORD>";
DateTime expiration = DateTime.Now.AddHours(1);
return new SecurityToken()
{
Username = testUsername,
Token = token,
ExpirationDate = expiration
};
}
private IRepository initiateFakeDatabase()
{
var mockDataAccess = new Mock<IRepository>();
// Mock GetAll
mockDataAccess.Setup(x => x.GetAll()).Returns(new List<PhraseEntity>()
{
new PhraseEntity(){ Id = 1, Expression = "Good morning!", AuthorName = "Minako" },
new PhraseEntity(){ Id = 2, Expression = "Konnichi wa!", AuthorName = "Chibi" },
new PhraseEntity(){ Id = 3, Expression = "Dokka e onsen e ikimashouka", AuthorName = "Chibi" },
new PhraseEntity(){ Id = 4, Expression = "I love to take photos", AuthorName = "Minako" }
});
// Mock GetSingle
mockDataAccess.Setup(x => x.GetSingle(It.IsAny<int>())).Returns(
new PhraseEntity()
{
Id = 1,
Expression = Faker.TextFaker.Sentence()
});
// Mock Add
mockDataAccess
.Setup(x => x.Add(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<LanguageType>(),
It.IsAny<string>()))
.Returns(1);
return mockDataAccess.Object;
}
#endregion
[TestMethod]
public void Dulce_QuieroHacerLogin_MeDejaEntrar()
{
LoginModel login = new LoginModel();
login.Username = "minako";
login.Password = "<PASSWORD>";
SecurityToken token = login.GetAuthenticationToken();
Assert.IsNotNull(token);
Assert.IsFalse(string.IsNullOrWhiteSpace(token.Token));
Assert.AreEqual(login.Username, token.Username);
Assert.IsTrue(token.ExpirationDate > DateTime.Now);
}
[TestMethod]
public void Dulce_QuieroAgregarMiFrase_CapturaDeFraseNueva()
{
StudentModel student = new StudentModel(_repository, _testSecurityToken);
student.Expression = "Machigai ga aru mono";
student.Author = _testSecurityToken.Username;
student.Language = LanguageType.Japanese;
bool result = student.SaveExpression();
Assert.IsTrue(result);
Assert.IsTrue(student.NewId > 0);
}
[TestMethod]
public void Dulce_QuieroVerLasFrases_MuestraListaDeFrases()
{
StudentModel student = new StudentModel(_repository, _testSecurityToken);
List<PhraseEntity> phrases = student.GetAllPhrases().ToList();
Assert.IsNotNull(phrases);
CollectionAssert.AllItemsAreNotNull(phrases);
}
[TestMethod]
public void Dulce_QuieroVerUnaFraseDeLuis_MuestraDetalleDeFrase()
{
string author = "Luis";
// Repository contains an expression
var repository = new Mock<IRepository>();
repository.Setup(x => x.GetSingle(It.IsAny<int>())).Returns(new PhraseEntity()
{
Id = Faker.NumberFaker.Number(),
Expression = Faker.TextFaker.Sentence(),
AuthorName = author
});
TeacherModel student = new TeacherModel(repository.Object, _testSecurityToken);
PhraseEntity phrase = student.GetExpression(1);
Assert.IsNotNull(phrase);
Assert.AreEqual(author, phrase.AuthorName);
}
[TestMethod]
public void Dulce_QuieroCorregirUnaFraseDeLuis_CapturaDeCorreccion()
{
string author = "Luis";
string sampleExpression = "Machigai aru toko";
string originalComment = "Como se usa el toko";
// Repository contains an expression
var memRepository = new MemoryRepository(1);
int id = memRepository.Add(author, sampleExpression, LanguageType.English, originalComment);
TeacherModel teacher = new TeacherModel(memRepository, _testSecurityToken);
PhraseEntity expression = teacher.GetExpression(id);
teacher.ViewedExpression = expression;
teacher.Comment = "Se usa con particulas.";
teacher.Correction = "Machigai nai toko";
bool result = teacher.AddCorrection();
Assert.IsTrue(result);
PhraseEntity corretedPhrase = teacher.GetExpression(id);
Assert.IsNotNull(corretedPhrase);
Assert.AreEqual(id, corretedPhrase.Id);
Assert.AreEqual(sampleExpression, corretedPhrase.Expression);
Assert.IsTrue(corretedPhrase.Corrections.Count == 1);
Assert.AreEqual(teacher.Correction, corretedPhrase.Corrections[0].Expression);
}
[TestMethod]
public void Dulce_QuieroComentarSobreUnaFrase_CapturaDeComentario()
{
string author = "Luis";
string sampleExpression = "Machigai aru toko";
string originalComment = "Como se usa el toko";
// Repository contains an expression
var memRepository = new MemoryRepository(1);
int id = memRepository.Add(author, sampleExpression, LanguageType.English, originalComment);
TeacherModel teacher = new TeacherModel(memRepository, _testSecurityToken);
PhraseEntity expression = teacher.GetExpression(id);
teacher.ViewedExpression = expression;
teacher.Comment = "Se usa con particulas.";
teacher.Correction = "Machigai nai toko";
bool result = teacher.AddCorrection();
Assert.IsTrue(result);
PhraseEntity corretedPhrase = teacher.GetExpression(id);
Assert.IsNotNull(corretedPhrase);
Assert.AreEqual(id, corretedPhrase.Id);
Assert.IsTrue(corretedPhrase.Comments.Count == 1);
Assert.AreEqual(teacher.Comment, corretedPhrase.Comments[0].Comment);
}
}
}
<file_sep>/MinakoNoTangoLib/Entities/LanguageType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Entities
{
public enum LanguageType
{
English,
Japanese,
Spanish
}
}
<file_sep>/MinakoNoTangoLib/Library/Repository/MemoryRepository.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library
{
public class MemoryRepository : IRepository
{
private int _newId;
private IList<PhraseEntity> _data;
public MemoryRepository() : this(1) { }
public MemoryRepository(int newIdSeed)
{
_newId = newIdSeed;
if(_data == null) _data = new List<PhraseEntity>();
}
public bool Initialize()
{
_newId = 1;
_data = new List<PhraseEntity>();
return true;
}
public IList<PhraseEntity> GetAll()
{
return _data;
}
public PhraseEntity GetSingle(int phraseId)
{
return _data.Where(x => x.Id == phraseId).FirstOrDefault();
}
#region Add
public int Add(string authorName, string expression, LanguageType language)
{
return this.Add(authorName, expression, language, null);
}
public int Add(string authorName, string expression, LanguageType language, string comment)
{
PhraseEntity entry = new PhraseEntity()
{
Id = _newId++,
AuthorName = authorName,
Language = language,
Comment = comment,
Expression = expression
};
_data.Add(entry);
return entry.Id;
}
#endregion
public bool Remove(int phraseId)
{
if (phraseId == 0) throw new ArgumentException();
PhraseEntity phrase = this.GetSingle(phraseId);
if (phrase == null) throw new InvalidOperationException();
return _data.Remove(phrase);
}
public bool Update(PhraseEntity phrase)
{
if (phrase == null) throw new ArgumentNullException();
if (phrase.Id == 0) throw new ArgumentException();
PhraseEntity originalPhrase = this.GetSingle(phrase.Id);
if (originalPhrase == null) throw new InvalidOperationException();
bool removed = _data.Remove(phrase);
if (removed)
{
_data.Add(phrase);
}
bool added = _data.Contains(phrase);
return removed && added;
}
}
}
<file_sep>/MinakoNoTango/Controllers/LoginController.cs
using MinakoNoTango.Models;
using MinakoNoTangoLib.Library.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MinakoNoTango.Controllers
{
public class LoginController : Controller
{
private LoginModel _login;
public LoginController()
{
_login = new LoginModel();
}
[HttpGet]
public ActionResult Index()
{
return View(new LoginView());
}
[HttpPost]
public ActionResult Index(LoginView form)
{
return View();
}
public ActionResult Logout()
{
return View("Index", new LoginView());
}
}
}
<file_sep>/MinakoNoTangoLib/Library/Repository/IRepository.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library
{
public interface IRepository
{
bool Initialize();
IList<PhraseEntity> GetAll();
PhraseEntity GetSingle(int phraseId);
// Adding
int Add(string authorName, string expression, LanguageType language);
int Add(string authorName, string expression, LanguageType language, string comment);
bool Remove(int phraseId);
bool Update(PhraseEntity phrase);
}
}
<file_sep>/MinakoNoTangoLib/Library/IMinakoNoTangoAuthentication.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library
{
public interface IMinakoNoTangoAuthentication
{
SecurityToken GetAuthenticationToken(string userName, string password);
bool IsValidToken(string userName, string token);
}
}
<file_sep>/MinakoNoTangoLib/Library/MinakoNoTangoLib.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library
{
public interface IMinakoNoTangoLibrary
{
IList<PhraseEntity> GetAllPhrases(SecurityToken token);
PhraseEntity GetPhraseDetail(SecurityToken token, int phraseId);
bool AddEnglishCorrection(SecurityToken token, int phraseId, string correction, string comment);
bool AddJapaneseCorrection(SecurityToken token, int phraseId, string correction, string comment);
// Add english phrase
PhraseEntity AddEnglishPhrase(SecurityToken token, string phrase);
PhraseEntity AddEnglishPhrase(SecurityToken token, string phrase, string comment);
}
public class MinakoNoTangoLibrary : IMinakoNoTangoLibrary
{
private readonly IRepository _repository;
public MinakoNoTangoLibrary(IRepository dataAccess)
{
if (dataAccess != null)
{
_repository = dataAccess;
}
else
{
throw new ArgumentException();
}
}
public IList<PhraseEntity> GetAllPhrases(SecurityToken token)
{
return _repository.GetAll();
}
public PhraseEntity GetPhraseDetail(SecurityToken token, int phraseId)
{
return _repository.GetSingle(phraseId);
}
public bool AddEnglishCorrection(SecurityToken token, int phraseId, string correction, string comment)
{
return true;
}
public bool AddJapaneseCorrection(SecurityToken token, int phraseId, string correction)
{
PhraseEntity storedPhrase = _repository.GetSingle(phraseId);
storedPhrase.Expression = correction;
return true;
}
#region Add english phrase
public PhraseEntity AddEnglishPhrase(SecurityToken token, string englishPhrase)
{
//return this.AddEnglishPhrase(token, englishPhrase, null);
throw new NotImplementedException();
}
public PhraseEntity AddEnglishPhrase(SecurityToken token, string englishPhrase, string comment)
{
//return _repository.Add(token.Username, englishPhrase, comment);
throw new NotImplementedException();
}
#endregion
public bool AddJapaneseCorrection(SecurityToken token, int phraseId, string correction, string comment)
{
throw new NotImplementedException();
}
}
}
<file_sep>/MinakoNoTangoLib/Library/MinakoNoTangoAuthentication.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library
{
public class MinakoNoTangoAuthentication : IMinakoNoTangoAuthentication
{
public bool IsValidToken(string userName, string token)
{
return true;
}
SecurityToken IMinakoNoTangoAuthentication.GetAuthenticationToken(string userName, string password)
{
return new SecurityToken()
{
Username = userName,
Token = "<PASSWORD>",
ExpirationDate = DateTime.Now.AddHours(1)
};
}
}
}
<file_sep>/MinakoNoTangoLib/Library/Repository/XmlRepository.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace MinakoNoTangoLib.Library.Repository
{
public class XmlRepository : IRepository
{
private XDocument _xml;
private int _newId = 1;
private string _filePath;
private List<PhraseEntity> _data;
public XmlRepository(string filePath)
{
_filePath = filePath;
if (!File.Exists(_filePath))
{
FileStream stream = File.Create(_filePath);
stream.Close();
}
loadFromXmlFile();
}
private void loadFromXmlFile()
{
FileStream file = File.Open(_filePath, FileMode.Open);
_xml = XDocument.Load(file);
IEnumerable<XElement> phraseNodes = _xml.Elements("Phrase");
if (_data == null) _data = new List<PhraseEntity>();
_data.Clear();
foreach (XElement node in phraseNodes)
{
var phrase = new PhraseEntity()
{
Id = Convert.ToInt32(node.Attribute("Id").Value),
AuthorName = node.Attribute("AuthorName").Value,
Expression = node.Value,
};
_data.Add(phrase);
}
}
public bool Initialize()
{
_data.Clear();
return true;
}
public IList<PhraseEntity> GetAll()
{
throw new NotImplementedException();
}
public PhraseEntity GetSingle(int phraseId)
{
throw new NotImplementedException();
}
public int Add(string authorName, string expression, LanguageType language)
{
var phrase = new PhraseEntity()
{
Id = _newId,
AuthorName = authorName,
Expression = expression,
Language = language
};
_data.Add(phrase);
_xml.Add(new XElement("Phrase"));
saveToXmlFile();
return _newId++;
}
private bool saveToXmlFile()
{
try
{
_xml.Save(_filePath);
return true;
}
catch
{
return false;
}
}
public int Add(string authorName, string expression, LanguageType language, string comment)
{
throw new NotImplementedException();
}
public bool Remove(int phraseId)
{
throw new NotImplementedException();
}
public bool Update(PhraseEntity phrase)
{
throw new NotImplementedException();
}
}
}
<file_sep>/MinakoNoTangoLib/Library/Models/StudentModel.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
namespace MinakoNoTangoLib.Library.Models
{
public class StudentModel
{
public int NewId { get; set; }
public string Author { get; set; }
public string Expression { get; set; }
public string Comment { get; set; }
public DateTime CapturedOn { get; set; }
public LanguageType Language { get; set; }
private SecurityToken _token;
private IRepository _repository;
public StudentModel() { }
public StudentModel(IRepository dataAccess, SecurityToken token)
{
validateRepositoryAndSecurityToken(dataAccess, token);
}
public void Setup(IRepository dataAccess, SecurityToken token)
{
validateRepositoryAndSecurityToken(dataAccess, token);
}
private void validateRepositoryAndSecurityToken(IRepository dataAccess, SecurityToken token)
{
if (token != null)
{
_token = token;
}
else
{
throw new ArgumentNullException();
}
if (dataAccess != null)
{
_repository = dataAccess;
}
else
{
throw new ArgumentNullException();
}
}
public bool SaveExpression()
{
this.NewId = _repository.Add(_token.Username, this.Expression, this.Language, this.Comment);
return this.NewId > 0;
}
public IList<PhraseEntity> GetAllPhrases()
{
return _repository.GetAll();
}
public PhraseEntity GetExpression(int phraseId)
{
return _repository.GetSingle(phraseId);
}
}
}
<file_sep>/MinakoNoTango/Controllers/TangoController.cs
using MinakoNoTango.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MinakoNoTango.Controllers
{
public class TangoController : Controller
{
public ActionResult Index()
{
return View(new TangoView());
}
public ActionResult Add()
{
return View(new TangoView());
}
}
}
<file_sep>/MinakoNoTango.Tests/LibraryTests/RepositoryTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MinakoNoTangoLib.Entities;
using MinakoNoTangoLib.Library;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTango.Tests.LibraryTests
{
[TestClass]
public class RepositoryTests
{
#region Test helpers
private PhraseEntity addPhraseToRepository()
{
string authorName = Faker.NameFaker.Name();
string englishPhrase = Faker.TextFaker.Sentence();
string comment = Faker.TextFaker.Sentences(3);
IRepository repo = new MemoryRepository();
int phraseId = repo.Add(authorName, englishPhrase, LanguageType.English, comment);
PhraseEntity phrase = new PhraseEntity()
{
Id = phraseId,
AuthorName = authorName,
Expression = englishPhrase,
Comment = comment
};
return phrase;
}
#endregion
[TestMethod]
public void MemRepository_AddPhrase()
{
string authorName = Faker.NameFaker.Name();
string expression = Faker.TextFaker.Sentence();
LanguageType language = LanguageType.English;
IRepository repo = new MemoryRepository();
//PhraseEntity phrase = repo.Add(authorName, englishPhrase);
int phraseId = repo.Add(authorName, expression, language);
Assert.IsTrue(phraseId > 0);
//Assert.IsNotNull(phrase);
//Assert.IsTrue(phrase.Id > 0);
//Assert.AreEqual(authorName, phrase.AuthorName);
//Assert.AreEqual(englishPhrase, phrase.Expression);
}
[TestMethod]
public void MemRepository_AddPhraseWithComment()
{
string authorName = Faker.NameFaker.Name();
string expression = Faker.TextFaker.Sentence();
string comment = Faker.TextFaker.Sentences(3);
LanguageType language = LanguageType.English;
IRepository repo = new MemoryRepository();
//PhraseEntity phrase = repo.Add(authorName, englishPhrase, comment);
int phraseId = repo.Add(authorName, expression, language, comment);
Assert.IsTrue(phraseId > 0);
//Assert.IsNotNull(phrase);
//Assert.IsTrue(phrase.Id > 0);
//Assert.AreEqual(authorName, phrase.AuthorName);
//Assert.AreEqual(englishPhrase, phrase.Expression);
//Assert.AreEqual(comment, phrase.Comment);
}
[TestMethod]
public void MemRepository_RemovePhrase()
{
string authorName = Faker.NameFaker.Name();
string expression = Faker.TextFaker.Sentence();
string comment = Faker.TextFaker.Sentences(3);
LanguageType language = LanguageType.English;
IRepository repo = new MemoryRepository();
//PhraseEntity phrase = repo.Add(authorName, englishPhrase, comment);
int phraseId = repo.Add(authorName, expression, language, comment);
Assert.IsTrue(phraseId > 0);
//Assert.IsNotNull(phrase);
bool hasBeenDeleted = repo.Remove(phraseId);
PhraseEntity deletedPhrase = repo.GetSingle(phraseId);
Assert.IsTrue(hasBeenDeleted);
Assert.IsNull(deletedPhrase);
}
[TestMethod]
public void MemRepository_ModifyPhrase()
{
IRepository repo = new MemoryRepository();
string authorName = Faker.NameFaker.Name();
string englishPhrase = Faker.TextFaker.Sentence();
string comment = Faker.TextFaker.Sentences(3);
int phraseId = repo.Add(authorName, englishPhrase, LanguageType.English, comment);
string modification = Faker.TextFaker.Sentence();
PhraseEntity updatedPhrase = new PhraseEntity()
{
Id = phraseId,
AuthorName = authorName,
Expression = modification,
Language = LanguageType.English,
Comment = comment
};
bool updated = repo.Update(updatedPhrase);
Assert.IsTrue(updated);
PhraseEntity storedPhrase = repo.GetSingle(updatedPhrase.Id);
Assert.IsNotNull(storedPhrase);
Assert.AreEqual(phraseId, storedPhrase.Id);
Assert.AreEqual(modification, storedPhrase.Expression);
}
}
}
<file_sep>/MinakoNoTangoLib/Entities/PhraseEntity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Entities
{
public class PhraseEntity
{
public int Id { get; set; }
public string Expression { get; set; }
public LanguageType Language { get; set; }
// Author
public int AuthorId { get; set; }
public string AuthorName { get; set; }
// Comments
public string Comment { get; set; }
public IList<CommentEntity> Comments { get; set; }
public IList<CorrectionEntity> Corrections { get; set; }
public override bool Equals(object obj)
{
PhraseEntity x = obj as PhraseEntity;
if (x != null)
{
return x.Id == this.Id;
}
else
{
return false;
}
}
}
public class CorrectionEntity
{
public string Expression { get; set; }
public DateTime CorrecctedOn { get; set; }
}
}
<file_sep>/MinakoNoTangoLib/Entities/CommentEntity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Entities
{
public class CommentEntity
{
public string AuthorName { get; set; }
public string Comment { get; set; }
public DateTime EditedOn { get; set; }
public bool ShowComment { get; set; }
}
}
<file_sep>/MinakoNoTangoLib/Library/Models/TeacherModel.cs
using MinakoNoTangoLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MinakoNoTangoLib.Library.Models
{
public class TeacherModel
{
private readonly SecurityToken _token;
private readonly IRepository _repository;
public IList<PhraseEntity> Expressions { get; set; }
public PhraseEntity ViewedExpression { get; set; }
public string Comment { get; set; }
public string Correction { get; set; }
public TeacherModel(IRepository dataAccess, SecurityToken token)
{
if (token != null)
{
_token = token;
}
else
{
throw new ArgumentException();
}
if (dataAccess != null)
{
_repository = dataAccess;
}
else
{
throw new ArgumentException();
}
this.Expressions = _repository.GetAll();
}
public PhraseEntity GetExpression(int phraseId)
{
return _repository.GetSingle(phraseId);
}
public bool AddCorrection()
{
PhraseEntity originalPhrase = this.ViewedExpression;
// Corretions
if (originalPhrase.Corrections == null)
originalPhrase.Corrections = new List<CorrectionEntity>();
originalPhrase.Corrections.Add(new CorrectionEntity()
{
Expression = this.Correction,
CorrecctedOn = DateTime.Now
});
// Comments
if (originalPhrase.Comments == null)
originalPhrase.Comments = new List<CommentEntity>();
originalPhrase.Comments.Add(new CommentEntity()
{
AuthorName = _token.Username,
Comment = this.Comment
});
return _repository.Update(originalPhrase);
}
public void LoadViewedExpression(int Id)
{
if (Id > 0)
{
this.ViewedExpression = _repository.GetSingle(Id);
}
else
{
throw new ArgumentException();
}
}
}
}
<file_sep>/MinakoNoTango/Models/TangoView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MinakoNoTango.Models
{
public class TangoView
{
public string NewVocabulary { get; set; }
public List<string> Vocabulary { get; set; }
public TangoView()
{
this.Vocabulary = new List<string>();
}
}
}<file_sep>/README.md
# MinakoNoTango
Un proyecto para ayudar a generar vocabulario entre dos personas que quieren aprender un nuevo idioma :)
<file_sep>/MinakoNoTango/Models/PhraseView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MinakoNoTango.Models
{
public class PhraseView
{
public string NewPhrase { get; set; }
public List<string> Phrases { get; set; }
public string Expression { get; set; }
public string Comment { get; set; }
public string Language { get; set; }
public string Author { get; set; }
public PhraseView()
{
this.Phrases = new List<string>();
}
}
} | ddd6111740c4ad6d57e6921aeb167efe8fa4e47d | [
"Markdown",
"C#"
] | 21 | C# | lvazquez81/MinakoNoTango | 2398873a45b000e0f9a1adfde28936ed6111d0c4 | 66e8e7d611ba6ed193923df5dd3e8b22ae8c4c9a |
refs/heads/master | <repo_name>han-yan-ds/CSharp-Stopwatch<file_sep>/Stopwatch.cs
using System;
namespace Stopwatch
{
public class Stopwatch
{
private TimeSpan Ticker { get; set; }
private DateTime StartTime { get; set; }
private bool _isRunning = false;
public Stopwatch()
{
Ticker = TimeSpan.Zero;
}
public void Start()
{
if (!_isRunning)
{
_isRunning = true;
StartTime = DateTime.Now;
}
}
public TimeSpan Stop()
{
if (_isRunning)
{
_isRunning = false;
Ticker += (DateTime.Now - StartTime);
}
return Ticker;
}
public TimeSpan Reset()
{
TimeSpan totalSpan = Stop();
Ticker = TimeSpan.Zero;
return totalSpan;
}
}
}<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Stopwatch
{
class Program
{
static void Main(string[] args)
{
Stopwatch myStopwatch = new Stopwatch();
TimeSpan mySpan;
for (int i = 0; i < 10; i++)
{
myStopwatch.Start();
System.Threading.Thread.Sleep(1000);
mySpan = myStopwatch.Stop();
Console.WriteLine(mySpan);
}
Console.Write("Finished! Press ENTER to exit... ");
Console.Read();
}
}
}
| e8ae8a0cd2327309cd3be55d1598e2e794f2b05a | [
"C#"
] | 2 | C# | han-yan-ds/CSharp-Stopwatch | cc923bba4f319fe598bfadbd70137b8c51595ff8 | 5c72ebfd4bc71c7417bf4fed173cae90fa9fa710 |
refs/heads/master | <file_sep>#!/bin/sh
sbcl --load load.lisp --eval '(planetwit:main)' | 7728bb966e8ee23dbf6126e1213a412a622dbdf2 | [
"Shell"
] | 1 | Shell | jsmpereira/planetwit | 0763f7ae78f7243d60a297248659ed442e9216c1 | 1e4e86964e5d7641d10eab10ccfa626d13e85985 |
refs/heads/master | <repo_name>DanDanTseng/AlarmManager_Repeat<file_sep>/app/src/main/java/com/wj/alarmmanager/app/AlarmReceiver.java
package com.wj.alarmmanager.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
/**
* Created by WJ on 5/12/2014.
*/
public class AlarmReceiver extends BroadcastReceiver {
//Toast toast;
@Override
public void onReceive(Context context,Intent intent){
Bundle bundle =intent.getExtras();
//NotifyM nm=new NotifyM();
if(bundle.get("msg").equals("partyOn")){
Log.d("WJ","doReceiver");
Toast toast=Toast.makeText(context, "Hello World", Toast.LENGTH_SHORT);
toast.show();
// nm.SetNotify(context);
}
}
}
<file_sep>/app/src/main/java/com/wj/alarmmanager/app/MainActivity.java
package com.wj.alarmmanager.app;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends Activity {
Button btn;
Button close;
PendingIntent pi;
TextView textView;
Calendar mcalendar;
ReminderManager RemindM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(Active_Alarm);
textView=(TextView)findViewById(R.id.textView);
close=(Button)findViewById(R.id.close);
close.setOnClickListener(closeAlarm);
RemindM=new ReminderManager(MainActivity.this);
}
Button.OnClickListener Active_Alarm=new Button.OnClickListener(){
@Override
public void onClick(View view) {
mcalendar=Calendar.getInstance();
mcalendar.set(Calendar.SECOND,5);
RemindM.setAlarm();
}
};
Button.OnClickListener closeAlarm=new Button.OnClickListener(){
@Override
public void onClick(View v) {
RemindM.cancelAlarm();
}
};
@Override
protected void onDestroy() {
super.onDestroy();
}
}
| 89bf9863a5f72548d369d58791f5fa59d0eea01b | [
"Java"
] | 2 | Java | DanDanTseng/AlarmManager_Repeat | 5f02b5557041dd13c9e0c8d3bfd4ef643711546f | f00edca8fc25dee07765959b97047d9fb98e8f2e |
refs/heads/master | <repo_name>Andrewryanhyde/ruby-music-library-cli-cb-000<file_sep>/lib/song.rb
class Song
attr_accessor :name, :artist, :genre
@@all = []
def initialize(name, artist = nil, genre = nil)
@name = name
self.artist = artist if artist
self.genre = genre if genre
end
def self.create(name)
new_song = Song.new(name)
new_song.save
new_song
end
def save
@@all << self
end
def artist=(artist)
@artist = artist
artist.add_song(self)
end
def genre=(genre)
@genre = genre
genre.add_song(self)
end
def self.all
@@all
end
def self.destroy_all
self.all.clear
end
def self.find_by_name(song)
@@all.find { |x| x.name == song}
end
def self.find_or_create_by_name(song)
self.find_by_name(song) || self.create(song)
end
def self.new_from_filename(path)
file = path.chomp(".mp3").split(" - ")
new_song = Song.new(file[1])
new_song.artist = Artist.find_or_create_by_name(file[0])
new_song.genre = Genre.find_or_create_by_name(file[2])
new_song.save
new_song
end
def self.create_from_filename(path)
self.new_from_filename(path)
end
end
<file_sep>/lib/concerns/findable.rb
module Concerns::Findable
def find_by_name(name)
self.all.find { |x| x.name == name}
end
def create(name)
new_entry = self.new(name)
new_entry.save
new_entry
end
def find_or_create_by_name(name)
self.find_by_name(name) || self.create(name)
end
end
| 3d5757e114a6f9d90369059288b65c1cd0ceaf7e | [
"Ruby"
] | 2 | Ruby | Andrewryanhyde/ruby-music-library-cli-cb-000 | 2d910efc64a0c46eea8a3a42067162966c4ead88 | 2d1aabf3a9a5c257fa2c24e5b96a84940f2c1e0d |
refs/heads/main | <repo_name>pohaha/distribution_Optimization<file_sep>/Distribution/cell.h
#pragma once
#include <string>
class cell
{
private:
float m_transferCost = 0;
unsigned int m_consumerId = 0;
unsigned int m_providerId = 0;
int m_transfer_amount = 0;
bool m_inSolution = false;
friend class distribution;
friend class redistribution;
public:
cell();
cell(unsigned int n_ProviderId, unsigned int n_consumerId);
~cell();
void show(bool inLine = false);
void changeAmount(int n_amount);
};
<file_sep>/Distribution/cell.cpp
#include "cell.h"
#include <iostream>
cell::cell(unsigned int n_ProviderId,
unsigned int n_consumerId) : m_consumerId(n_consumerId),
m_providerId(n_ProviderId)
{
std::cout << "cell id: ["
<< m_providerId
<< "]["
<< m_consumerId
<< "]"
<< std::endl;
std::cout << "input the transfer_cost: ";
std::cin >> m_transferCost;
std::cout << "this cell is in current solution?[0/1]: ";
std::cin >> m_inSolution;
if (m_inSolution)
{
std::cout << "input the amount of transferred items: ";
std::cin >> m_transfer_amount;
}
}
cell::~cell()
{
}
cell::cell()
{
}
void cell::changeAmount(int volume)
{
m_transfer_amount += volume;
if (m_transfer_amount == 0)
m_inSolution = false;
else if (m_transfer_amount < 0)
std::cout << "ERROR!" << std::endl;
else
m_inSolution = true;
}
void cell::show(bool inLine)
{
std::cout << "cell"
<< "[" << m_providerId << "]"
<< "[" << m_consumerId << "]: "
<< m_transferCost
<< "(" << m_transfer_amount << ")";
if (not inLine)
std::cout << std::endl;
}<file_sep>/Distribution/distribution.cpp
#include "distribution.h"
#include <iostream>
#include <vector>
#include "redistribution.h"
distribution::distribution(const bool &construct)
{
if (construct)
{
std::cout << "input the amount of providers: ";
std::cin >> m_amountOfProviders;
m_providers = new int[m_amountOfProviders];
for (unsigned int i = 0; i < m_amountOfProviders; i++)
{
std::cout << "Input the amount provided by #" << i << ": ";
std::cin >> m_providers[i];
}
std::cout << "input the amount of consumers: ";
std::cin >> m_amountOfConsumers;
m_consumers = new int[m_amountOfConsumers];
for (unsigned int i = 0; i < m_amountOfConsumers; i++)
{
std::cout << "Input the amount consumed by #" << i << ": ";
std::cin >> m_consumers[i];
}
m_grid = new cell *[m_amountOfProviders];
for (unsigned int i = 0; i < m_amountOfProviders; i++)
{
m_grid[i] = new cell[m_amountOfConsumers];
for (unsigned int j = 0; j < m_amountOfConsumers; j++)
m_grid[i][j] = cell(i, j);
}
}
std::cout << "empty distribution" << std::endl;
}
distribution::~distribution()
{
delete[] m_consumers;
for (unsigned int i = 0; i < m_amountOfProviders; i++)
delete[] m_grid[i];
delete[] m_grid;
delete[] m_providers;
}
float distribution::cost()
{
float rt_cost = 0;
for (unsigned int i = 0; i < m_amountOfProviders; i++)
{
for (unsigned int j = 0; j < m_amountOfConsumers; j++)
{
if (m_grid[i][j].m_inSolution)
rt_cost += (m_grid[i][j].m_transferCost) * (m_grid[i][j].m_transfer_amount);
}
}
std::cout << "total cost of that solution is: " << rt_cost << std::endl;
return rt_cost;
}
void distribution::show()
{
std::cout << "\t";
for (unsigned int i = 0; i < m_amountOfConsumers; i++)
std::cout << i << "\t";
std::cout << "\n";
for (unsigned int i = 0; i < m_amountOfProviders; i++)
{
for (unsigned int j = 0; j < (m_amountOfConsumers + 2); j++)
{
if (j == 0)
std::cout << i << "\t";
else if (j <= m_amountOfConsumers)
{
if (m_grid[i][j - 1].m_inSolution)
{
std::cout << m_grid[i][j - 1].m_transferCost
<< "("
<< m_grid[i][j - 1].m_transfer_amount
<< ")\t";
}
else
std::cout << m_grid[i][j - 1].m_transferCost << "(0)\t";
}
else
std::cout << "| " << m_providers[i] << "\n";
}
}
for (unsigned int i = 0; i < ((m_amountOfConsumers + 1) * 8); i++)
std::cout << "-";
std::cout << std::endl;
std::cout << "\t";
for (unsigned int i = 0; i < m_amountOfConsumers; i++)
std::cout << m_consumers[i] << "\t";
std::cout << std::endl;
}
void distribution::redistribute(redistribution n_redistribution)
{
int inLineVolume = n_redistribution.m_cellInLine.m_transfer_amount;
int inColumnVolume = n_redistribution.m_cellInColumn.m_transfer_amount;
int redistributedVolume = (inLineVolume < inColumnVolume) ? (inLineVolume) : (inColumnVolume);
unsigned int mainRow = n_redistribution.m_mainCell.m_providerId;
unsigned int mainColumn = n_redistribution.m_mainCell.m_consumerId;
unsigned int subRow = n_redistribution.m_submissiveCell.m_providerId;
unsigned int subColumn = n_redistribution.m_submissiveCell.m_consumerId;
m_grid[mainRow][mainColumn].changeAmount(redistributedVolume);
m_grid[subRow][mainColumn].changeAmount((redistributedVolume * (-1)));
m_grid[mainRow][subColumn].changeAmount((redistributedVolume * (-1)));
m_grid[subRow][subColumn].changeAmount(redistributedVolume);
}
void distribution::optimize()
{
std::vector<redistribution> eligible_redistributions;
for (unsigned int i = 0; i < m_amountOfProviders; i++)
{
for (unsigned int j = 0; j < m_amountOfConsumers; j++)
{
if (not m_grid[i][j].m_inSolution)
{
for (unsigned int rowCounter = 0; rowCounter < m_amountOfProviders; rowCounter++)
{
if ((rowCounter != i) and (m_grid[rowCounter][j].m_inSolution))
{
for (unsigned int columnCounter = 0; columnCounter < m_amountOfConsumers; columnCounter++)
{
if ((columnCounter != j) and (m_grid[i][columnCounter].m_inSolution))
{
eligible_redistributions.push_back(redistribution(m_grid[i][j],
m_grid[rowCounter][columnCounter],
m_grid[rowCounter][j],
m_grid[i][columnCounter]));
}
}
}
}
}
}
}
redistribution bestRedistribution;
bool exists = false;
for (auto element : eligible_redistributions)
if (not exists)
{
if (element.m_influence <= 0)
{
bestRedistribution = element;
exists = true;
}
}
else
{
if (element.m_influence < bestRedistribution.m_influence)
bestRedistribution = element;
}
if (not exists)
{
std::cout << "there are no negative or zero redistributions. nothing to redistribute!" << std::endl;
return;
}
std::cout << "best singular redistribotion is: " << std::endl;
bestRedistribution.show();
redistribute(bestRedistribution);
show();
}<file_sep>/Distribution/CMakeLists.txt
add_library(distribution cell.cpp distribution.cpp redistribution.cpp)<file_sep>/Distribution/distribution.h
#pragma once
#include <string>
#include "cell.h"
#include "redistribution.h"
class distribution
{
private:
unsigned int m_amountOfConsumers = 0;
unsigned int m_amountOfProviders = 0;
int *m_consumers = nullptr;
int *m_providers = nullptr;
cell **m_grid = nullptr;
void redistribute(redistribution n_redistribution);
public:
distribution(const bool &construct = false);
~distribution();
float cost();
void show();
void optimize();
};
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.19.7)
project(Try_Cmake)
add_executable(${PROJECT_NAME} main.cpp)
add_subdirectory(Distribution)
target_link_directories(${PROJECT_NAME} PRIVATE Distribution/)
target_link_libraries(${PROJECT_NAME} distribution)<file_sep>/Distribution/redistribution.cpp
#include "redistribution.h"
#include <iostream>
void redistribution::show()
{
//line 1
m_mainCell.show(true);
std::cout << "\t<-------\t";
m_cellInLine.show(true);
std::cout << std::endl;
//line 2
m_cellInColumn.show(true);
std::cout << "\t------->\t";
m_submissiveCell.show();
std::cout << "singular redistribution resolves in: " << m_influence << std::endl;
}
redistribution::redistribution() {}
redistribution::redistribution(cell n_mainCell,
cell n_submissiceCell,
cell n_cellInLine,
cell n_cellInColumn) : m_mainCell(n_mainCell),
m_submissiveCell(n_submissiceCell),
m_cellInLine(n_cellInLine),
m_cellInColumn(n_cellInColumn)
{
m_influence = (m_mainCell.m_transferCost + m_submissiveCell.m_transferCost) -
(m_cellInColumn.m_transferCost + m_cellInLine.m_transferCost);
}<file_sep>/Distribution/redistribution.h
#pragma once
#include "cell.h"
struct redistribution
{
cell m_mainCell;
cell m_submissiveCell;
cell m_cellInLine;
cell m_cellInColumn;
float m_influence = 0;
void show();
redistribution(cell n_mainCell,
cell n_submissiceCell,
cell n_cellInLine,
cell n_cellInColumn);
redistribution();
};
<file_sep>/main.cpp
#include <iostream>
#include "Distribution/distribution.h"
int main()
{
distribution test_distribution(true);
test_distribution.show();
float n_cost = test_distribution.cost();
char answer = 'y';
while (answer == 'y')
{
test_distribution.optimize();
std::cin.clear();
std::cout << "would you like to optimize again?[y/n]: ";
std::cin >> answer;
}
} | d238e00d3899643c3528c1bea6a63f3ba5c2815c | [
"C",
"CMake",
"C++"
] | 9 | C++ | pohaha/distribution_Optimization | 70aad74bdf95f6f5a639bc642a80d91589c14ba7 | 2ddc3dfccedb1029412faba0856e4cf9dc83f0bb |
refs/heads/master | <file_sep>/**
Write a function that accepts two arguments and returns the remainder after dividing the larger number by the smaller number. Division by zero should return NaN. Arguments will both be integers.
**/
function remainder(a, b){
// Divide the larger argument by the smaller argument and return the remainder
// if a or b == 0 return Not a Number
if (a == 0 || b == 0){
return NaN;
}
// if a < b return the modulo of b%a
else if(a < b){
return b%a;
// else return modulo a%b
}else{
return a%b;
}
}<file_sep>
//First try 1hour
// Had real difficulties to know if I could use splice (only for arrays) or split/SubString for String
/*
function disemvowel(str) {
var arrayOfVowels = ["a", "e", "i", "o", "u"];
for(var i = 0, y = str.length; i < y; i++){
console.log(str[i]);
arrayOfVowels.forEach(function(y) {
if(str[i] == y){
console.log("vowel");
var x = str.indexOf(y);
var replace = str[x];
console.log(replace);
var newstr = str.replace(replace, " ");
console.log(newstr);
}
});
}
}
disemvowel("heyae");
*/
//Second try
function disemvowel(str){
var newstr = str.replace(/[aeiou]/ig, "");
return newstr;
}<file_sep>CodeWars
========
My solutions for codewars katas
<file_sep>/**
ISAN
Description:
isNaN doesn't work very well. We want us to tell us whether the value or object we're dealing with is a number or not. Instead, it tells us if the value is equal to the NaN value it has on-record.
So let's make a proper function, called isAN, for is A Number. If you pass it a value, it will return true if a value is a valid primitive number or Number object, and false if not.
**/
function isAN(value) {
if(typeof value == "object"){
if(Array.isArray(value)){
return false;
}else{
var savedValue = parseInt(value);
if(isNaN(savedValue)){
return false;
}
if(typeof savedValue == "number"){
return true;
}
}
}
if(typeof value !== "number"){
return false;
}
return !isNaN(value);
}<file_sep>/* Description:
Let's build a calculator that can calculate the average for an arbitrary number of arguments.
The test expects you to provide a Calculator object with an average method:
Calculator.average();
The test also expects that when you pass no arguments, it returns 0. The arguments are expected to be integers.
It expects Calculator.average(3,4,5) to return 4. */
var Calculator = {
average: function() {
var args = Array.prototype.slice.call(arguments);
var total = 0;
var average = 0;
var argsLength = args.length;
if(argsLength == 0){
return 0;
}else {
for(var i = 0, y = args.length; i < y; i++){
args[i] = parseInt(args[i]);
total += args[i];
}
average = total/argsLength;
return average;
}
}
};
Calculator.average(3, 4, 5);<file_sep>var i, y;
function getNiceNames(people){
var nicePeople = [];
for(i = 0, y = people.length; i < y; i++ ){
if(people[i].wasNice === true){
nicePeople.push(people[i].name);
}
}
return nicePeople;
}
function getNaughtyNames(people){
var nicePeople = [];
for(i = 0, y = people.length; i < y; i++ ){
if(people[i].wasNice === false){
naughtyPeople.push(people[i].name);
}
}
return naughtyPeople;
}
alert(getNiceNames([
{name:'Jonathan', wasNice:true},
{name: 'Bayan', wasNice:false},
{name: 'Barak', wasNice:true},
{name: 'Mdr', wasNice:true},
{name:'Arvin', wasNice:false}
]));
alert(getNaughtyNames([
{name:'Jonathan', wasNice:true},
{name: 'Bayan', wasNice:false},
{name: 'Barak', wasNice:true},
{name: 'Mdr', wasNice:true},
{name:'Arvin', wasNice:false}
]));
alert(getNiceNames([]));
<file_sep>/**
Happy Holidays fellow Code Warriors!
Santa's senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code.
Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out?
Sort the Gift Code
Write a function called sortGiftCode (sort_gift_code in Ruby) that accepts a string containing up to 26 unique alphabetical characters, and returns a string containing the same characters in alphabetical order.
Examples:
Javascript/CoffeeScript:
sortGiftCode( 'abcdef' );//=> returns 'abcdef'
sortGiftCode( 'pqksuvy' );//=> returns 'kpqsuvy'
sortGiftCode( 'zyxwvutsrqponmlkjihgfedcba' );//=> returns 'abcdefghijklmnopqrstuvwxyz'
**/
// First try without uniqueness
function sortGiftCode(code) {
var letters = /^[A-Za-z]+$/ , output = [], i, y;
if (letters.test(code)) {
for (i = 0, y = code.length; i < y; i++) {
output.push(code[i]);
}
}else {
alert("Only letters !")
}
output.sort();
code = output.join("");
return code;
}
// Now achieved with uniqueness
function sortGiftCode(code) {
var i, len=code.length, output=[], obj={};
for (i=0;i<len;i++) {
obj[code[i]]=0;
}
for (i in obj) {
output.push(i);
}
code = output.sort();
code = output.join("");
return code;
}
<file_sep>/*
Description:
Your task, is to create NxN multiplication table, of size provided in parameter.
*/
multiplicationTable = function (size) {
var array = [];
//for loop over size of rows
for(var i = 1; i <= size; i++){
// make new innerArray every row
var innerArray = [];
//for loop over size of columns
for(var y = 1; y <= size; y++){
var result = i*y;
//push every result to innerArray
innerArray.push(result);
}
//push innerArray to globalArray when column for loop has quit
array.push(innerArray);
}
return array;
};
multiplicationTable(5);
<file_sep>/**
Let's implement the range function:
range([start], stop, [step])
range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(1, 4, 0); // /!\ note that the step is 0
=> [1, 1, 1]
range(0);
=> []
range(10, 0); // /!\ note that the end is before the start
=> []
range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
start, if omitted, defaults to 0; step defaults to 1.
Returns a list of integers from start to stop, incremented (or decremented) by step, exclusive.
Note that ranges that stop before they start are considered to be zero-length instead of negative.
**/
function range(start, end, range){
var array = [];
if(arguments.length == 0){
console.log("No parameters");
return array;
}
else if(arguments.length == 1){
console.log("There is 1 parameters");
for(var i = 0, y = arguments[0]; i < y; i++){
array.push(i);
}
return array;
}
else if(arguments.length == 2){
console.log("There are 2 parameters");
var argument1 = arguments[0];
var argument2 = arguments[1];
//check if start is larger than end
if(argument1 > argument2){
console.log("Argument1 is larger than argument2");
return array;
}else{
for(var i = arguments[0], y = arguments[1]; i < y; i++){
console.log(i);
array.push(i);
}
}
}
else if(arguments.length == 3){
console.log("There are 3 parameters");
if(argument1 > argument2){
console.log("Argument1 is larger than argument2");
return array;
}else{
for(var i = arguments[0], y = arguments[1]; i < y; i+=arguments[2]){
if(i > y){
}else{
array.push(i);
}
}
return array;
}
}
}<file_sep>/**
For the sake of argument
Write a function named numbers that returns true if all the parameters it is passed are of the Number type. Otherwise, the function should return false. The function should accept any number of parameters.
Example usage:
numbers(1, 4, 3, 2, 5); // true
numbers(1, "a", 3); // false
numbers(1, 3, NaN); // true
**/
function numbers(){
var args = Array.prototype.slice.call(arguments, 0);
var allNumbers = true;
for(var i = 0, y = args.length; i < y; i++){
if(typeof args[i] !== "number"){
console.log(args[i]);
console.log("It isn't' a number!");
allNumbers = false;
}
}
return allNumbers;
} | 5cbe5c38f9aca651232b9a1bb9f16394091f96e9 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | ludovicbonivert/CodeWars | ae5aa0f42599692b00635047089174c6d499d52a | 6c55415ab47d525710716d3b5d910a2a99fe6c58 |
refs/heads/master | <file_sep>volume-adjuster
===============
Simple script that auto-adjusts pulseaudio volume so you don't have to keep fiddling with the volume.
#### Installing
```
git clone https://github.com/the7erm/volume-adjuster.git
cd volume-adjuster/
git submodule init
git submodule update
```
#### Running
Open up your command line and run `./new-volume-adjuster.py` play some sound.
To ensure the program is working open up `pavucontrol` and check the `Playback` tab.
- The peak bar fluctuate.
- The db volume should change automatically.

#### Trouble shooting.
If the sound is distorted you'll need to run `paman` and on the `Devices` tab open each item in `Sources` and `Reset` their volume so the volume is `100%`.

This needs to be done for the `alsa_input.*` and `alsa_output.*` `Sources`.

#### Graph

The graph shows the last 10 seconds of activity. If you don't like it just close it. It won't show up until you restart the program.
The dotted line is a reference point for "100%" in pulse audio. The solid black line is the volume (you can open `pavucontrol` and watch it in action via the playback tab.)
The program samples the audio level 10 times a second. Out of those 10 times the light blue peak represents the "highest" level. The medium blue represents the "average" level, and the dark blue represents the "lowest" level.
If the volume is too soft ... it raises the volume. To loud lowers. Simple as that. No more constantly moving your mouse to adjust the volume via the speaker icon.
<file_sep>#!/usr/bin/env python2
# A good portion of this script was taken from
# http://freshfoo.com/blog/pulseaudio_monitoring
import sys
from Queue import Queue, Empty
from ctypes import POINTER, c_ubyte, c_void_p, c_ulong, cast
import subprocess
import re
import pprint
import math
import os
# From https://github.com/Valodim/python-pulseaudio
sys.path.append(os.path.join(sys.path[0], "python_pulseaudio", "pulseaudio"))
from lib_pulseaudio import *
# edit to match your sink
# alsa_output.pci-0000_00_14.2.analog-stereo
SINK_NAME = 'alsa_output.pci-0000_00_14.2.analog-stereo'
# METER_RATE = 344
METER_RATE = 20
MAX_SAMPLE_VALUE = 127
DISPLAY_SCALE = 2
MAX_SPACES = MAX_SAMPLE_VALUE >> DISPLAY_SCALE
class PeakMonitor(object):
def __init__(self, sink_name, rate):
self.sink_name = sink_name
self.rate = rate
# Wrap callback methods in appropriate ctypefunc instances so
# that the Pulseaudio C API can call them
self._context_notify_cb = pa_context_notify_cb_t(self.context_notify_cb)
self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
self._stream_read_cb = pa_stream_request_cb_t(self.stream_read_cb)
self._stream_input_read_cb = pa_stream_request_cb_t(self.stream_input_read_cb)
self._subscribe = pa_context_subscribe_cb_t(self.subscribe)
# pa_context_subscribe_cb_t = CFUNCTYPE(None, POINTER(pa_context), pa_subscription_event_type_t, uint32_t, c_void_p)
self._subscribe_success = pa_context_success_cb_t(self.subscribe_success)
# stream_read_cb() puts peak samples into this Queue instance
self._samples = Queue()
self._ques = {}
# Create the mainloop thread and set our context_notify_cb
# method to be called when there's updates relating to the
# connection to Pulseaudio
_mainloop = pa_threaded_mainloop_new()
_mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
context = pa_context_new(_mainloop_api, 'volume-adjuster')
pa_context_set_state_callback(context, self._context_notify_cb, None)
pa_context_connect(context, None, 0, None)
pa_threaded_mainloop_start(_mainloop)
def subscribe(self, context, event_type, idx, *args, **kwargs):
if event_type in (5, 18,37):
return
# print "event_type:", event_type, "idx:",idx
if (event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SINK_INPUT:
mask = event_type & PA_SUBSCRIPTION_EVENT_TYPE_MASK
if mask == PA_SUBSCRIPTION_EVENT_NEW:
print "NEW SINK",idx
self._ques["%s" % idx] = Queue()
o = pa_context_get_sink_input_info(context, idx, self._sink_input_info_cb, None)
pa_operation_unref(o)
if mask == PA_SUBSCRIPTION_EVENT_REMOVE:
print "REMOVE SINK", idx
print "event_type:", event_type.__repr__()
print "idx:", idx
del self._ques["%s" % idx]
def subscribe_success(self, *args, **kwargs):
print "subscribe_success", args
def __iter__(self):
while True:
yield self._samples.get()
def get_sink_input_samples(self):
samples = {}
for idx, q in self._ques.items():
try:
samples[idx] = q.get(False)
except Empty:
print "Empty"
samples[idx] = 0
return samples
def context_notify_cb(self, context, _):
state = pa_context_get_state(context)
if state == PA_CONTEXT_READY:
print "Pulseaudio connection ready..."
# Connected to Pulseaudio. Now request that sink_info_cb
# be called with information about the available sinks.
o = pa_context_get_sink_info_list(context, self._sink_info_cb, None)
pa_operation_unref(o)
self._sink_input_info_cb = pa_sink_input_info_cb_t(self.sink_input_info_cb)
elif state == PA_CONTEXT_FAILED :
print "Connection failed"
elif state == PA_CONTEXT_TERMINATED:
print "Connection terminated"
def sink_info_cb(self, context, sink_info_p, _, __):
print "sink_info_p:",sink_info_p
if not sink_info_p:
return
sink_info = sink_info_p.contents
print '-'* 60
print 'index:', sink_info.index
print 'name:', sink_info.name
print 'description:', sink_info.description
print "sink_info.name:", sink_info.name
print "self.sink_name:", self.sink_name
if sink_info.name == self.sink_name:
# Found the sink we want to monitor for peak levels.
# Tell PA to call stream_read_cb with peak samples.
print
print 'setting up peak recording using', sink_info.monitor_source_name
print
samplespec = pa_sample_spec()
samplespec.channels = 1
samplespec.format = PA_SAMPLE_U8
samplespec.rate = self.rate
self.monitor_source_name = sink_info.monitor_source_name
pa_stream = pa_stream_new(context, "main-output", samplespec, None)
pa_stream_set_read_callback(pa_stream,
self._stream_read_cb,
sink_info.index)
pa_stream_connect_record(pa_stream,
sink_info.monitor_source_name,
None,
PA_STREAM_PEAK_DETECT)
"""
pa_operation* pa_context_subscribe (
pa_context * c,
pa_subscription_mask_t m,
pa_context_success_cb_t cb,
void * userdata
) """
# PA_SUBSCRIPTION_EVENT_CHANGE
# PA_SUBSCRIPTION_MASK_SINK_INPUT
# PA_SUBSCRIPTION_EVENT_SINK_INPUT
# PA_SUBSCRIPTION_MASK_SINK
# PA_STREAM_READY
# PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT
# PA_SUBSCRIPTION_EVENT_SINK_INPUT
pa_context_subscribe(
context,
PA_SUBSCRIPTION_MASK_ALL,
self._subscribe_success, None)
pa_context_set_subscribe_callback(context, self._subscribe, None)
o = pa_context_get_sink_input_info_list(context, self._sink_input_info_cb, None)
pa_operation_unref(o)
def sink_input_info_cb(self, context, sink_input_info_p, _, __):
print "*"*60
if not sink_input_info_p:
print "none", sink_input_info_p
print "/"*60
return
print "="*60
print "sink_input_info_p.contents.name:", sink_input_info_p.contents.name
print "sink_input_info_p.contents.index:", sink_input_info_p.contents.index
sink_input_info = sink_input_info_p.contents
samplespec = pa_sample_spec()
samplespec.channels = 1
samplespec.format = PA_SAMPLE_U8
samplespec.rate = self.rate
self._ques["%s" % sink_input_info.index] = Queue()
pa_stream = pa_stream_new(context, "input-sink %s" % sink_input_info.name, samplespec, None)
pa_stream_set_monitor_stream(pa_stream, sink_input_info.index);
pa_stream_set_read_callback(pa_stream,
self._stream_input_read_cb,
sink_input_info.index,
None)
pa_stream_connect_record(pa_stream,
self.monitor_source_name,
None,
PA_STREAM_PEAK_DETECT)
print "/"*60
def stream_read_cb(self, stream, length, index_incr):
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
self._samples.put(data[i] - 128)
# print "stream_read_cb:",data[i] - 128
pa_stream_drop(stream)
def stream_input_read_cb(self, stream, length, index_incr):
# print "stream:",stream
# print "index_incr:", index_incr
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
# self._samples.put(data[i] - 128)
# print "stream_input_read_cb:",data[i] - 128
self._ques["%s" % index_incr].put(data[i] - 128)
pa_stream_drop(stream)
class LevelMonitorSink:
def __init__(self, context, rate, sink_input_info_p, monitor_source_name):
self.context = context
self.rate = rate
self.monitor_source_name = monitor_source_name
self.sink_input_info_p = sink_input_info_p
self.average = 0
self.total = 0
self.vol = 0
self.count = 0
self.min = 127
self.max = 0
self.history = []
self.max_history = 2
self.reset_history_samples = 10
self._stream_input_read_cb = pa_stream_request_cb_t(self.stream_input_read_cb)
self.setup_monitor()
def hard_reset(self):
self.total = 0
self.count = 0
self.average = 0
self.min = 127
self.max = 0
def stream_input_read_cb(self, stream, length, index_incr):
# print "stream:",stream
# print "index_incr:", index_incr
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
# self._samples.put(data[i] - 128)
# print "stream_input_read_cb:",data[i] - 128
level = data[i] - 128
if level < self.min:
self.min = level
if level > self.max:
self.max = level
self.count += 1
self.total += level
if self.count > self.reset_history_samples:
self.append_history()
pa_stream_drop(stream)
def append_history(self):
self.average = sum(self.history) / len(self.history)
self.history.append({
"min": self.min,
"max": self.max,
"avg": self.avg
})
if len(self.history) > self.max_history:
self.history[1:] = self.history
self.hard_reset()
self.process_history()
def process_history(self):
min_cnt = 0
max_cnt = 0
silent_cnt = 0
too_loud_cnt = 0
too_soft_cnt = 0
extreamely_loud_count = 0
min_too_loud_cnt
for h in self.history:
if h['max'] >= 120:
too_loud_cnt += 1
if h['max'] >= 127:
extreamely_loud_count += 1
if h['max'] <= 30:
too_soft_cnt += 1
if h['max'] >= 110:
max_cnt += 1
if h['max'] <= 80:
min_cnt += 1
if h['min'] >= 80:
min_too_loud_cnt += 1
if h['max'] <= 20 and h['min'] == 0:
silent_cnt += 1
if silent_cnt >= 1 or bad_cnt:
adj = 0
reason = "silent"
if too_loud_cnt >= 2:
adj = -3
reason = "it was silent and, way to loud"
else:
if max_cnt >= 1:
adj = -1
reason = "max_cnt:%s" % (max_cnt,)
if min_cnt >= 1:
adj = 1
reason = "min_cnt:%s" % min_cnt
if max_cnt == min_cnt:
adj = 0
reason = "equal parts"
if min_too_loud_cnt >= 2:
adj = -1
reason = "min too loud"
if too_loud_cnt >= 2:
adj = -4
reason = "Way too loud"
if extreamely_loud_count >= 2:
adj = -10
reason = "127 all the way"
if too_soft_cnt >= 2:
adj = 3
reason = "way to soft"
print "reason:",reason
self.adjust_volume(adj)
def setup_monitor(self):
sink_input_info = self.sink_input_info_p.contents
self.index = sink_input_info.index
self.application_name = sink_input_info.name
samplespec = pa_sample_spec()
samplespec.channels = 1
samplespec.format = PA_SAMPLE_U8
samplespec.rate = self.rate
pa_stream = pa_stream_new(context, "input-sink %s" % sink_input_info.name, samplespec, None)
pa_stream_set_monitor_stream(pa_stream, sink_input_info.index);
pa_stream_set_read_callback(pa_stream,
self._stream_input_read_cb,
sink_input_info.index,
None)
pa_stream_connect_record(pa_stream,
self.monitor_source_name,
None,
PA_STREAM_PEAK_DETECT)
def adjust_volume(self, adj):
if adj == 0:
return
vol = self.vol + adj
if vol < 150:
new_vol = int(self.convert_vol_to_k(vol))
exe = "pacmd set-sink-input-volume %s %s" % (self.index, new_vol)
print "exe:",exe
subprocess.check_output(exe, shell=True)
class VolumeAdjuster:
def __init__(self, METER_RATE=METER_RATE):
self.index_re = re.compile(r"index\:\s+(\d+)")
# volume: 0: 100%
self.METER_RATE = METER_RATE
self.min_value = 127
self.max_value = 0
self.count = 0
self.upper_silence = 40
self.lower_silence = 5
self.too_loud = 115
self.target = 100
self.too_soft = 70
self.one_k = 65536
self.one_percent = self.one_k * 0.01
self.total = 0
self.constant_test = False
self.vol = -1
self.idx = -1
self.last_min_value = 127
self.last_max_value = 0
self.target_history_len = 2
self.history = []
self.input_sink_samples = {}
self.volume_re = re.compile(r"volume\: \d+\:\s+(\d+)\%")
self.colon_re = re.compile(r"([A-z\ ]+)\:\ (.*)$")
self.dangling_colon_re = re.compile(r"([A-z\ ]+)\:$")
self.equal_re = re.compile(r"(.*)\ \=\ (.*)$")
self.vol_re = re.compile(r"(\d+)\:\s+([\d]+)\%")
self.digit_re = re.compile(r"^(\d+)$")
self.double_quote_re = re.compile(r"^\"(.*)\"$")
self.quote_re = re.compile(r"^\'(.*)\'$")
def get_sink_input_info(self):
sinks = []
try:
output = subprocess.check_output("pacmd list-sink-inputs", shell=True)
except:
# TODO
# return sinks
return sinks
sink = {}
lines = output.split("\n")
# print output
inside = ""
for l in lines:
colon_match = self.colon_re.search(l)
if colon_match:
inside = ""
k = colon_match.group(1).strip()
v = colon_match.group(2).strip()
if k == 'index':
if sink != {}:
sinks.append(sink)
sink = {}
if k == 'volume':
# volume: 0: 100% 1: 100%
vol_match = self.vol_re.findall(v)
v = {}
if vol_match:
for channel, value in vol_match:
v[channel] = int(value)
sink[k] = self.convert_value(v)
dangling_match = self.dangling_colon_re.search(l)
if dangling_match:
inside = dangling_match.group(1)
sink[inside] = {}
if inside:
matches = self.equal_re.search(l)
if matches:
k = matches.group(1).strip()
v = matches.group(2).strip()
sink[inside][k] = self.convert_value(v)
if sink != {}:
sinks.append(sink)
# pprint.pprint(sinks)
return sinks
def convert_value(self, v):
if isinstance(v, dict):
return v
# print "started:", v.__repr__(), type(v)
double_quote_match = self.double_quote_re.match(v)
quote_match = self.quote_re.match(v)
if double_quote_match:
v = double_quote_match.group(1)
elif quote_match:
v = quote_match.group(1)
digit_match = self.digit_re.match(v)
if digit_match:
v = int(digit_match.group(1))
# print "ended:", v.__repr__(), type(v)
return v
def convert_to_dec(self, vol):
vol = float(vol)
return vol / 100
def convert_vol_to_k(self, vol):
return (self.convert_to_dec(vol) * 65536)
def process_sample(self, sample, input_samples):
self.count += 1
self.total += sample
for k, s in input_samples.iteritems():
if k not in self.input_sink_samples:
self.input_sink_samples[k] = {
"count": 0,
"total": 0,
"min": 127,
"max": 0
}
self.input_sink_samples[k]['count'] += 1
self.input_sink_samples[k]['total'] += s
if s < self.input_sink_samples[k]['min']:
self.input_sink_samples[k]['min'] = s
if s > self.input_sink_samples[k]['max']:
self.input_sink_samples[k]['max'] = s
if sample < self.min_value:
self.min_value = sample
if sample > self.max_value:
self.max_value = sample
if self.count >= self.METER_RATE:
self.process_levels()
def process_levels(self):
self.sinks = self.get_sink_input_info()
if len(self.sinks) == 0:
self.count = 0
return
self.calculate_average()
self.caclulate_mid_value()
self.append_history()
self.process_history()
self.hard_reset()
def calculate_average(self):
self.average = 0
try:
self.average = self.total / self.count
except ZeroDivisionError:
self.average = 0
for k, s in self.input_sink_samples.iteritems():
try:
self.input_sink_samples[k]['avg'] = s['total'] / s['count']
except ZeroDivisionError:
self.input_sink_samples[k]['avg'] = 0
if self.average != 0:
self.total = 0
def caclulate_mid_value(self):
self.mid_value = -1
try:
self.mid_value = ((self.max_value - self.min_value) / 2) + self.min_value
except ZeroDivisionError:
self.mid_value = 0
for k, s in self.input_sink_samples.iteritems():
try:
self.input_sink_samples[k]['mid'] = (
(s['max'] - s['min']) / 2) + s['min']
except ZeroDivisionError:
self.input_sink_samples[k]['mid'] = 0
def append_history(self):
this_history = []
for s in self.sinks:
idx = "%s" % s['index']
try:
sink_input = self.input_sink_samples[idx]
this_history.append({
"min": sink_input['min'],
"max": sink_input['max'],
"avg": sink_input['avg'],
"mid": sink_input['mid'],
"idx": s["index"],
"vol": s['volume']["0"],
"name": s['properties']['application.name']
})
except KeyError, e:
print "KeyError:",e
if this_history:
self.history.append(this_history)
if len(self.history) > self.target_history_len:
self.history = self.history[1:]
return
def hard_reset(self):
self.count = 0
self.total = 0
self.min_value = 127
self.max_value = 0
self.input_sink_samples = {}
def print_history(self):
print "["
# [{'name': 'fmp-pg.py', 'idx': 70, 'min': 40, 'vol': 97, 'max': 102, 'mid': 71, 'avg': 73}]
for i, h in enumerate(self.history):
for sink in h:
print "%3s:" % i,
for k, v in sink.iteritems():
print "%s:%3s" % (k, v),
print ""
print "]"
def print_bar(self, adj, reason):
bar_data = {}
for i in range(-1, 200):
if self.count >= self.METER_RATE:
bar_data[str(i)] = ["-"]
else:
bar_data[str(i)] = [" "]
bar_data[str(self.min_value / 2)] += ['[%3d' % self.min_value]
bar_data[str(self.mid_value / 2)] += ['%3d|' % self.mid_value]
bar_data[str(self.average / 2)] += ['%3da' % self.average]
bar_data[str(self.max_value / 2)] += ['%3d]' % self.max_value]
for s in self.sinks:
vol = s['volume']["0"]
vol_str = str(vol / 2)
if vol > 127:
vol_str = str(127 / 2)
bar_data[vol_str] += ["%3d@" % vol]
new_bar = ""
for i in range(0,64):
key = "%s" % i
new_bar += " ".join(bar_data[key])
new_bar = "-"*90
mid_pos = int(self.mid_value / 2) + 2
new_bar = new_bar[:mid_pos-2] + ("%3d|" % self.mid_value ) + new_bar[mid_pos+2:]
min_pos = int(self.min_value / 2) + 2
new_bar = new_bar[:min_pos-2] + ("[%3d" % self.min_value ) + new_bar[min_pos+2:]
avg_pos = int(self.average / 2) + 2
new_bar = new_bar[:avg_pos-2] + ("%3da" % self.average ) + new_bar[avg_pos+2:]
for s in self.sinks:
vol = s['volume']["0"]
vol_pos = int(vol/2) + 2
new_bar = new_bar[:vol_pos-2] + ("%3d@" % vol ) + new_bar[vol_pos+2:]
max_pos = int(self.max_value/2) + 2
new_bar = new_bar[:max_pos-2] + ("%3d]" % self.max_value) + new_bar[max_pos+2:]
new_bar = new_bar[:48] + "T" + new_bar[48:]
self.print_history()
# pprint.pprint(self.history)
print "nb [",new_bar,"]",
if adj > 0:
print "+%s" % adj,reason
elif adj < 0:
print adj,reason
else:
print "%2d" % adj,reason
def process_history(self):
self.adj = 0
self.reason = ""
max_cnt = 0
min_cnt = 0
silent_cnt = 0
bad_cnt = 0
too_loud_cnt = 0
too_soft_cnt = 0
min_too_loud_cnt = 0
extreamely_loud_count = 0
for sink_history in self.history:
if len(sink_history) == 0:
bad_cnt += 1
try:
h = sink_history[0]
except IndexError:
break
if h['max'] >= 120:
too_loud_cnt += 1
if h['max'] >= 127:
extreamely_loud_count += 1
if h['max'] <= 30:
too_soft_cnt += 1
if h['max'] >= 110:
max_cnt += 1
if h['max'] <= 80:
min_cnt += 1
if h['min'] >= 80:
min_too_loud_cnt += 1
if h['max'] <= 20 and h['min'] == 0:
silent_cnt += 1
if silent_cnt >= 1 or bad_cnt:
adj = 0
reason = "silent"
if too_loud_cnt >= 2:
adj = -3
reason = "it was silent and, way to loud"
else:
if max_cnt >= 1:
adj = -1
reason = "max_cnt:%s" % (max_cnt,)
if min_cnt >= 1:
adj = 1
reason = "min_cnt:%s" % min_cnt
if max_cnt == min_cnt:
adj = 0
reason = "equal parts"
if min_too_loud_cnt >= 2:
adj = -1
reason = "min too loud"
if too_loud_cnt >= 2:
adj = -4
reason = "Way too loud"
if extreamely_loud_count >= 2:
adj = -10
reason = "127 all the way"
if too_soft_cnt >= 2:
adj = 3
reason = "way to soft"
self.print_bar(adj, reason)
self.adjust_volume(adj)
def adjust_volume(self, adj):
if adj == 0:
return
for s in self.sinks:
vol = s['volume']['0']
idx = s['index']
vol += adj
if vol <= 150:
new_vol = int(self.convert_vol_to_k(vol))
exe = "pacmd set-sink-input-volume %s %s" % (idx, new_vol)
# print exe
try:
input_sink_sample = self.input_sink_samples["%s" % idx]
except KeyError, e:
print "KeyError:",e
continue
print "input_sink_sample:", input_sink_sample
if self.count >= METER_RATE and new_vol > 0 and \
input_sink_sample['min'] > 0:
subprocess.check_output(exe, shell=True)
def main():
# pacmd list-sink-inputs | grep index | awk '{print $2}'
monitor = PeakMonitor(SINK_NAME, METER_RATE)
volume_adjuster = VolumeAdjuster(METER_RATE=METER_RATE)
for sample in monitor:
input_samples = monitor.get_sink_input_samples()
volume_adjuster.process_sample(sample, input_samples)
# print "input_samples:", input_samples
sys.stdout.flush()
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env python2
# A good portion of this script was taken from
# http://freshfoo.com/blog/pulseaudio_monitoring
import sys
from Queue import Queue, Empty
from ctypes import POINTER, c_ubyte, c_void_p, c_ulong, cast
import subprocess
import re
import pprint
import math
import os
import datetime
import time
import math
import gtk
import cairo
from copy import deepcopy
# From https://github.com/Valodim/python-pulseaudio
sys.path.append(os.path.join(sys.path[0], "python_pulseaudio", "pulseaudio"))
from lib_pulseaudio import *
# edit to match your sink
# alsa_output.pci-0000_00_14.2.analog-stereo
SINK_NAME = 'alsa_output.pci-0000_00_14.2.analog-stereo'
# METER_RATE = 344
METER_RATE = 10
MAX_SAMPLE_VALUE = 127
DISPLAY_SCALE = 2
MAX_VOLUME = 153
MAX_SPACES = MAX_SAMPLE_VALUE >> DISPLAY_SCALE
def wait():
# print "leave1"
gtk.gdk.threads_leave()
# print "/leave1"
# print "enter"
gtk.gdk.threads_enter()
# print "/enter"
if gtk.events_pending():
while gtk.events_pending():
# print "pending:"
gtk.main_iteration(False)
# print "leave"
gtk.gdk.threads_leave()
window = gtk.Window()
drawing_area = gtk.DrawingArea()
window.add(drawing_area)
black = gtk.gdk.color_parse("#000")
red = gtk.gdk.color_parse("#F00")
green = gtk.gdk.color_parse("#0F0")
blue = gtk.gdk.color_parse("#00F")
white = gtk.gdk.color_parse("#FFF")
global cr, widget, show_window
cr = None
_widget = None
show_window = True
if '--no-window' in sys.argv:
show_window = False
def expose(widget, event):
global _widget
_widget = widget
cr = _widget.window.cairo_create()
cr.set_source_rgb(1.0, 1.0, 1.0)
width, height = window.get_size()
cr.rectangle(1, 1, width, height)
cr.fill()
return
def invert(num, _max, height):
percent = (num / _max)
inverse = (1.0 - percent)
res = inverse * height
# print "--"
# print "num:", num
# print "max:", _max
# print "height:", height
# print "percent:", percent
# print "res:", res
# print "inverse:", inverse
return int(res)
def d(*args):
res = []
for val in args:
res.append(int(val) / 255.0)
return res
def high(cr):
cr.set_source_rgb(*d(69, 81, 185))
def avg(cr):
cr.set_source_rgb(*d(8, 18, 109))
def low(cr):
cr.set_source_rgb(*d(4, 10, 58))
def black(cr):
cr.set_source_rgb(0.0, 0.0, 0.0)
def white(cr):
cr.set_source_rgb(1.0, 1.0, 1.0)
def light_grey(cr):
cr.set_source_rgb(0.5, 0.5, 0.5)
def draw_lines(cr, x, vol, part_width, half):
# black(cr)
# cr.rectangle(x, vol, part_width, 3)
# cr.fill()
white(cr)
cr.rectangle(x, half, part_width, 2)
cr.fill()
def draw_history(history):
global _widget, show_window
if not show_window:
return
if _widget is None or _widget.window is None:
return
# print "_widget.window.height", window.get_size()
# print "HISTORY:", history
cr = _widget.window.cairo_create()
width, height = window.get_size()
max_value = 154.0
part_width = width / 10.0
while len(history) < 10:
history.insert(0, {
"avg": 0,
"min": 0,
"vol": 0,
"max": 0
})
reverse_history = deepcopy(history)
reverse_history.reverse()
colors = {
'max': d(69, 81, 185),
'avg': d(8, 18, 109),
'min': d(4, 10, 58),
'white': d(255, 255, 255),
'black': d(0, 0, 0),
'grey': d(50, 50, 100)
}
half = height * 0.5
keys = ['max', 'avg', 'min']
for i, k in enumerate(keys):
idx = width
x1 = width
last_el = None
start_vol = invert(reverse_history[0][k], max_value, height)
cr.set_source_rgb(*colors[k])
cr.move_to(idx, start_vol)
cr.line_to(idx, start_vol)
for el in reverse_history:
idx = idx - part_width
vol = invert(el[k], max_value, height)
cr.line_to(idx, vol)
# now we work forward with the next element
cr.line_to(0, vol)
if i != len(keys) - 1:
k2 = keys[i+1]
# print "k2:",k2
start_vol = invert(history[0][k2], max_value, height)
cr.line_to(0, start_vol)
idx = 0
for el in history:
vol = invert(el[k2], max_value, height)
cr.line_to(idx, vol)
idx = idx + part_width
cr.line_to(width, vol)
cr.line_to(width, start_vol)
else:
cr.line_to(0, vol)
cr.line_to(0, height)
cr.line_to(width, height)
cr.line_to(width, start_vol)
cr.set_line_width(2)
cr.close_path()
cr.fill()
cr.stroke()
idx = width
k = 'vol'
start_vol = invert(reverse_history[0][k], max_value, height)
cr.set_source_rgb(*colors['black'])
cr.move_to(idx, start_vol)
for el in reverse_history:
idx = idx - part_width
vol = invert(el[k], max_value, height)
cr.line_to(idx, vol)
cr.stroke()
if i == 0:
idx = width
k = 'max'
start_vol = invert(reverse_history[0][k], max_value, height)
cr.set_source_rgb(*colors['white'])
cr.move_to(idx, start_vol)
cr.line_to(idx, start_vol)
for el in reverse_history:
idx = idx - part_width
vol = invert(el[k], max_value, height)
cr.line_to(idx, vol)
cr.line_to(0, vol)
cr.line_to(0, 0)
cr.line_to(width, 0)
cr.line_to(width, start_vol)
cr.close_path()
cr.fill()
cr.stroke()
idx = width
k = 'vol'
start_vol = invert(reverse_history[0][k], max_value, height)
cr.set_source_rgb(*colors['black'])
cr.move_to(idx, start_vol)
for el in reverse_history:
idx = idx - part_width
vol = invert(el[k], max_value, height)
cr.line_to(idx, vol)
cr.stroke()
cr.set_source_rgb(*colors['black'])
factor = max_value / 154.0
one_hundred_pos = factor * 100
_pos = invert(one_hundred_pos, max_value, height)
# print "_pos:", _pos
cr.set_line_width(1)
cr.set_dash([20, 20])
cr.move_to(0, _pos)
cr.line_to(0, _pos)
cr.line_to(width, _pos)
cr.stroke()
wait()
drawing_area.connect("expose-event", expose)
# drawing_area.draw_rectangle(gc, filled, x, y, width, height)
window.show_all()
if not show_window:
window.iconify()
wait()
def print_mask_type(mask):
print "mask:",mask,
if mask == PA_SUBSCRIPTION_EVENT_SINK:
print "PA_SUBSCRIPTION_EVENT_SINK",
if mask == PA_SUBSCRIPTION_EVENT_SOURCE:
print "PA_SUBSCRIPTION_EVENT_SOURCE",
if mask == PA_SUBSCRIPTION_EVENT_SINK_INPUT:
print "PA_SUBSCRIPTION_EVENT_SINK_INPUT",
if mask == PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT:
print "PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT",
if mask == PA_SUBSCRIPTION_EVENT_MODULE:
print "PA_SUBSCRIPTION_EVENT_MODULE",
if mask == PA_SUBSCRIPTION_EVENT_CLIENT:
print "PA_SUBSCRIPTION_EVENT_CLIENT",
if mask == PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE:
print "PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE",
if mask == PA_SUBSCRIPTION_EVENT_SERVER:
print "PA_SUBSCRIPTION_EVENT_SERVER",
if mask == PA_SUBSCRIPTION_EVENT_AUTOLOAD:
print "PA_SUBSCRIPTION_EVENT_AUTOLOAD",
if mask == PA_SUBSCRIPTION_EVENT_FACILITY_MASK:
print "PA_SUBSCRIPTION_EVENT_FACILITY_MASK",
if mask == PA_SUBSCRIPTION_EVENT_NEW:
print "PA_SUBSCRIPTION_EVENT_NEW",
if mask == PA_SUBSCRIPTION_EVENT_CHANGE:
print "PA_SUBSCRIPTION_EVENT_CHANGE",
if mask == PA_SUBSCRIPTION_EVENT_REMOVE:
print "PA_SUBSCRIPTION_EVENT_REMOVE",
print
class PeakMonitor(object):
def __init__(self, sink_name, rate):
self.sink_name = sink_name
self.rate = rate
self.sinks = {}
self.input_sinks = {}
# Wrap callback methods in appropriate ctypefunc instances so
# that the Pulseaudio C API can call them
self._context_notify_cb = pa_context_notify_cb_t(self.context_notify_cb)
self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
self._stream_input_read_cb = pa_stream_request_cb_t(
self.stream_input_read_cb)
self._subscribe = pa_context_subscribe_cb_t(self.subscribe)
self._subscribe_success = pa_context_success_cb_t(
self.subscribe_success)
# stream_read_cb() puts peak samples into this Queue instance
self._samples = Queue()
# Create the mainloop thread and set our context_notify_cb
# method to be called when there's updates relating to the
# connection to Pulseaudio
_mainloop = pa_threaded_mainloop_new()
_mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
context = pa_context_new(_mainloop_api, 'volume-adjuster')
pa_context_set_state_callback(context, self._context_notify_cb, None)
pa_context_connect(context, None, 0, None)
pa_threaded_mainloop_start(_mainloop)
def subscribe(self, context, event_type, idx, *args, **kwargs):
"""
PA_SUBSCRIPTION_EVENT_SINK = 0, /**< Event type: Sink */
PA_SUBSCRIPTION_EVENT_SOURCE = 1, /**< Event type: Source */
PA_SUBSCRIPTION_EVENT_SINK_INPUT = 2, /**< Event type: Sink input */
PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT = 3, /**< Event type: Source output */
PA_SUBSCRIPTION_EVENT_MODULE = 4, /**< Event type: Module */
PA_SUBSCRIPTION_EVENT_CLIENT = 5, /**< Event type: Client */
PA_SUBSCRIPTION_EVENT_SAMPLE_CACHE = 6, /**< Event type: Sample cache item */
PA_SUBSCRIPTION_EVENT_SERVER = 7, /**< Event type: Global server change, only occuring with PA_SUBSCRIPTION_EVENT_CHANGE. \since 0.4 */
PA_SUBSCRIPTION_EVENT_AUTOLOAD = 8, /**< Event type: Autoload table changes. \since 0.5 */
PA_SUBSCRIPTION_EVENT_FACILITY_MASK = 15, /**< A mask to extract the event type from an event value */
PA_SUBSCRIPTION_EVENT_NEW = 0, /**< A new object was created */
PA_SUBSCRIPTION_EVENT_CHANGE = 16, /**< A property of the object was modified */
PA_SUBSCRIPTION_EVENT_REMOVE = 32, /**< An object was removed */
PA_SUBSCRIPTION_EVENT_TYPE_MASK = 16+32"""
print "event_type:", event_type, "idx:",idx
facility_mask = (event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
print "facility_mask:", facility_mask, "event_type:", event_type,
print "idx:",idx
print_mask_type(facility_mask)
event_mask = (event_type & PA_SUBSCRIPTION_EVENT_TYPE_MASK)
print "event_mask:", event_mask, "event_type:", event_type, "idx:",idx
print_mask_type(event_mask)
if event_type in (5, 18, 37):
return
print "event_type:", event_type, "idx:",idx
print "equal test", (event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == facility_mask
if facility_mask == PA_SUBSCRIPTION_EVENT_SINK_INPUT:
print "!"*100
print "PA_SUBSCRIPTION_EVENT_SINK_INPUT"
print_mask_type(facility_mask)
print_mask_type(event_mask)
if event_mask == PA_SUBSCRIPTION_EVENT_NEW:
print "+"*100
print "NEW SINK", idx
# self._ques["%s" % idx] = Queue()
o = pa_context_get_sink_input_info(context, idx, self._sink_input_info_cb, None)
pa_operation_unref(o)
if event_mask == PA_SUBSCRIPTION_EVENT_REMOVE:
print "-"*100
print "REMOVE SINK", idx
print "event_type:", event_type.__repr__()
print "idx:", idx
# del self._ques["%s" % idx]
try:
del self.input_sinks["%s" % idx]
except KeyError:
pass
def subscribe_success(self, *args, **kwargs):
print "subscribe_success", args
def context_notify_cb(self, context, _):
state = pa_context_get_state(context)
if state == PA_CONTEXT_READY:
print "Pulseaudio connection ready..."
# Connected to Pulseaudio. Now request that sink_info_cb
# be called with information about the available sinks.
o = pa_context_get_sink_info_list(context, self._sink_info_cb, None)
pa_operation_unref(o)
self._sink_input_info_cb = pa_sink_input_info_cb_t(
self.sink_input_info_cb)
elif state == PA_CONTEXT_FAILED :
print "Connection failed"
elif state == PA_CONTEXT_TERMINATED:
print "Connection terminated"
def sink_info_cb(self, context, sink_info_p, _, __):
print "sink_info_p:",sink_info_p
if not sink_info_p:
print "NO sink_info_p"
return
sink_info = sink_info_p.contents
print '-'* 60
print 'index:', sink_info.index
print 'name:', sink_info.name
print 'description:', sink_info.description
print "sink_info.name:", sink_info.name
print "self.sink_name:", self.sink_name
if 'alsa_output' in sink_info.name:
# Found the sink we want to monitor for peak levels.
# Tell PA to call stream_read_cb with peak samples.
print
print 'setting up peak recording using', sink_info.monitor_source_name
print
samplespec = pa_sample_spec()
samplespec.channels = 1
samplespec.format = PA_SAMPLE_U8
samplespec.rate = self.rate
self.monitor_source_name = sink_info.monitor_source_name
"""
THIS IS HOW TO GET THE MAIN VOLUME
print "SINK_INFO:",sink_info
print "SINK_INFO.volume:", sink_info.volume
pprint.pprint((dir(sink_info.volume)))
print "sink_info.volume.values:", sink_info.volume.values
pprint.pprint(sink_info.volume.values)
print "sink_info.volume.channels:", sink_info.volume.channels
pprint.pprint((dir(sink_info.volume.channels)))
pprint.pprint(sink_info.volume.channels)
print "/ sink_info.volume.channels"
for val in sink_info.volume.values:
print "sink_info.volume.values VAL:", val
"""
print "SINK_INFO"
dir_r(sink_info)
# import pdb; pdb.set_trace()
pa_context_subscribe(
context,
PA_SUBSCRIPTION_MASK_ALL,
self._subscribe_success, None)
pa_context_set_subscribe_callback(context, self._subscribe, None)
o = pa_context_get_sink_input_info_list(context, self._sink_input_info_cb, None)
pa_operation_unref(o)
def sink_input_info_cb(self, context, sink_input_info_p, _, __):
print "*"*60
if not sink_input_info_p:
print "NONE", sink_input_info_p
print "/"*60
return
print "="*60
print "sink_input_info_p.contents.name:", sink_input_info_p.contents.name
print "sink_input_info_p.contents.index:", sink_input_info_p.contents.index
time.sleep(0.5)
name = sink_input_info_p.contents.name
if name == "Event Sound":
return
print "NAME:", name
idx = sink_input_info_p.contents.index
self.input_sinks["%s" % idx] = LevelMonitorSink(
context, self.rate, sink_input_info_p, self.monitor_source_name
)
print "/"*60
print "-="*15, "SINK LIST","-="*15
print self.input_sinks
def stream_read_cb(self, stream, length, index_incr):
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
self._samples.put(data[i] - 128)
# print "stream_read_cb:",data[i] - 128
pa_stream_drop(stream)
def stream_input_read_cb(self, stream, length, index_incr):
# print "stream:",stream
# print "index_incr:", index_incr
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
# self._samples.put(data[i] - 128)
# print "stream_input_read_cb:",data[i] - 128
self._ques["%s" % index_incr].put(data[i] - 128)
pa_stream_drop(stream)
print_r = pprint.pprint
def dir_r(obj):
print_r(dir(obj))
print "type:",type(obj)
print "obj:", obj
class LevelMonitorSink:
def __init__(self, context, rate, sink_input_info_p, monitor_source_name):
self.context = context
self.rate = rate
self.monitor_source_name = monitor_source_name
self.sink_input_info_p = sink_input_info_p
self.name = sink_input_info_p.contents.name
self.avg = 0
self.total = 0
self.vol = 100
self.count = 0
self.min = 127
self.max = 0
self.history = []
self.level_history = []
self.long_history = []
self.max_history = 2
self.long_history_length = 10
self.reset_history_samples = METER_RATE
self._samples = Queue()
print "sink_input_info_p:", sink_input_info_p
print "DIR sink_input_info_p:",
pprint.pprint(dir(sink_input_info_p))
contents = sink_input_info_p.contents
print "contents:", sink_input_info_p.contents
# import pdb; pdb.set_trace()
for v in contents.volume.values:
print "VAL:", v
print "(int(contents.volume.values[0]) / 65536.0):", (int(contents.volume.values[0]) / 65536.0)
self.vol = int(math.ceil((int(contents.volume.values[0]) / 65536.0) * 100))
print "VOL:", self.vol
self._stream_input_read_cb = pa_stream_request_cb_t(
self.stream_input_read_cb)
print "monitor_source_name:", monitor_source_name
self.setup_monitor()
def hard_reset(self):
self.total = 0
self.count = 0
self.avg = 0
self.min = 127
self.max = 0
self.level_history = []
def stream_input_read_cb(self, stream, length, index_incr):
if self.name == 'Event Sound':
print "EVENT SOUND"
return
# print self.name
# print "index_incr:", index_incr
data = c_void_p()
pa_stream_peek(stream, data, c_ulong(length))
data = cast(data, POINTER(c_ubyte))
for i in xrange(length):
# When PA_SAMPLE_U8 is used, samples values range from 128
# to 255 because the underlying audio data is signed but
# it doesn't make sense to return signed peaks.
# self._samples.put(data[i] - 128)
# print "stream_input_read_cb:",data[i] - 128
self._samples.put(data[i] - 128)
pa_stream_drop(stream)
level = self._samples.get()
if level < self.min:
self.min = level
if level > self.max:
self.max = level
self.count += 1
self.total += level
self.level_history.append(level)
if self.count > self.reset_history_samples:
print "#"*30, self.name, "#"*30,"%s" % datetime.datetime.now()
self.append_history()
def set_bar_value(self, bar_data, val, fmt):
pos = str(val / 2)
bar_data[pos] += [fmt % val]
def print_bar(self, history):
if self.name == 'Event Sound':
print "EVENT SOUND"
return
try:
draw_history(self.long_history)
except cairo.Error:
pass
bar_data = {}
for i in range(-1, 200):
if self.count >= METER_RATE:
bar_data[str(i)] = ["-"]
else:
bar_data[str(i)] = [" "]
self.set_bar_value(bar_data, history['min'], '[%3d')
self.set_bar_value(bar_data, history['avg'], '%3da')
self.set_bar_value(bar_data, history['max'], '%3d]')
self.set_bar_value(bar_data, history['vol'], '%3d@')
new_bar = "-"*90
new_bar2 = "-"*90
new_bar = new_bar[:48] + "T" + new_bar[48:]
new_bar2 = new_bar[:48] + "T" + new_bar2[48:]
min_pos = int(history['min'] / 2) + 2
new_bar = new_bar[:min_pos-2] + ("[%3d" % history['min'] ) + new_bar[min_pos+2:]
avg_pos = int(history['avg'] / 2) + 2
new_bar = new_bar[:avg_pos-2] + ("%3da" % history['avg'] ) + new_bar[avg_pos+2:]
max_pos = int(history['max']/2) + 2
new_bar = new_bar[:max_pos-2] + ("%3d]" % history['max'] ) + new_bar[max_pos+2:]
vol_pos = int(history['vol']/2) + 2
new_bar2 = new_bar2[:vol_pos-2] + ("%3d@" % history['vol'] ) + new_bar2[vol_pos+2:]
# self.print_history()
# pprint.pprint(self.history)
print self.name, " [",new_bar,"]"
print self.name, " [",new_bar2,"]"
def append_history(self):
if self.name == 'Event Sound':
return
self.avg = sum(self.level_history) / len(self.level_history)
self.history.append({
"min": self.min,
"max": self.max,
"avg": self.avg,
"vol": self.vol
})
self.long_history.append({
"min": self.min,
"max": self.max,
"avg": self.avg,
"vol": self.vol
})
if len(self.history) > self.max_history:
self.history = self.history[1:]
if len(self.long_history) > self.long_history_length:
self.long_history = self.long_history[1:]
print self.name, "history:", pprint.pformat(self.history)
print self.name, "self.level_history:",len(self.level_history), self.level_history
print self.name, "self.long_history:", self.long_history
self.hard_reset()
self.process_history()
self.long_history_has_changed()
for h in self.long_history:
self.print_bar(h)
if self.name == "Playback Stream":
print "re-setting monitor"
self.name = self.sink_input_info_p.contents.name
# self.sink_input_info_p = sink_input_info_p
# self.name = sink_input_info_p.contents.name
def long_history_has_changed(self):
if len(self.long_history) < self.long_history_length:
return
for h1 in self.long_history:
for h2 in self.long_history:
if h1['min'] != h2['min'] or h1['max'] != h2['max']:
# print "LONG HISTORY HAS CHANGED"
return True
print "*!"*60
print "LONG HISTORY HAS NOT CHANGED"
print "*!"*60
return False
# self.long_history = []
# self.setup_monitor()
# return False
def process_history(self):
min_cnt = 0
max_cnt = 0
silent_cnt = 0
too_loud_cnt = 0
too_soft_cnt = 0
extreamely_loud_count = 0
min_too_loud_cnt = 0
bad_cnt = 0
adj = 0
for h in self.history:
if h['avg'] > 89:
print self.name,"reason: avg > 89"
max_cnt += 2
if h['avg'] > 100:
too_loud_cnt += 2
if h['max'] >= 120:
too_loud_cnt += 1
if h['max'] >= 127:
extreamely_loud_count += 1
if h['max'] <= 30:
too_soft_cnt += 1
if h['max'] >= 110:
max_cnt += 1
if h['max'] <= 80:
min_cnt += 1
if h['min'] >= 80:
min_too_loud_cnt += 1
if h['max'] <= 20 and h['min'] == 0:
silent_cnt += 1
if silent_cnt >= 1 or bad_cnt:
adj = 0
reason = "silent"
if too_loud_cnt >= 2:
adj = -4
reason = "it was silent and, way to loud"
else:
if max_cnt >= 1:
adj = -1
reason = "max_cnt:%s" % (max_cnt,)
if min_cnt >= 1:
adj = 1
reason = "min_cnt:%s" % min_cnt
if max_cnt == min_cnt:
adj = 0
reason = "equal parts"
if min_too_loud_cnt >= 2:
adj = -1
reason = "min too loud"
if too_loud_cnt >= 2:
adj = -3
reason = "Way too loud"
if extreamely_loud_count >= 2:
adj = -10
reason = "127 all the way"
if too_soft_cnt >= 2:
adj = 2
reason = "way to soft"
print self.name, "reason:",reason
self.adjust_volume(adj)
def setup_monitor(self):
sink_input_info = self.sink_input_info_p.contents
self.index = sink_input_info.index
self.application_name = sink_input_info.name
samplespec = pa_sample_spec()
samplespec.channels = 1
samplespec.format = PA_SAMPLE_U8
samplespec.rate = self.rate
pa_stream = pa_stream_new(self.context, "input-sink %s" %
sink_input_info.name, samplespec, None)
pa_stream_set_monitor_stream(pa_stream, sink_input_info.index);
pa_stream_set_read_callback(pa_stream,
self._stream_input_read_cb,
sink_input_info.index,
None)
pa_stream_connect_record(pa_stream,
self.monitor_source_name,
None,
PA_STREAM_PEAK_DETECT)
def adjust_volume(self, adj):
if adj == 0:
return
vol = self.vol + adj
if vol > MAX_VOLUME and self.vol != MAX_VOLUME:
vol = MAX_VOLUME
if vol <= MAX_VOLUME:
print "adj:",adj
new_vol = int(self.convert_vol_to_k(vol))
if new_vol < 0:
return
exe = "pacmd set-sink-input-volume %s %s" % (self.index, new_vol)
print "exe:",exe
subprocess.check_output(exe, shell=True)
self.vol = vol
def convert_to_dec(self, vol):
vol = float(vol)
return vol / 100
def convert_vol_to_k(self, vol):
return (self.convert_to_dec(vol) * 65536)
def main():
monitor = PeakMonitor(SINK_NAME, METER_RATE)
while True:
time.sleep(1)
if __name__ == '__main__':
main()
<file_sep>#!/bin/bash
cd /home/erm/git/volume-adjuster
./new-volume-adjuster.py &>/dev/null &
| a5e2d8e124fb63fa5cfa2e8adcd09f78cbb7c658 | [
"Markdown",
"Python",
"Shell"
] | 4 | Markdown | the7erm/volume-adjuster | 71ec604f4646c9f09eee9f0157c689fe4519f97b | 53bafdf248a00212e1c56c0ed1abca49d60fff33 |
refs/heads/main | <file_sep><!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">
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.min.css'?>">
<title>Dashboard</title>
</head>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">login Test here</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a href="">logout</a>
</form>
</div>
</nav>
</header>
</header>
</body>
</html><file_sep><!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">
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.min.css'?>">
<link rel="stylesheet" href="<?php echo base_url().'assets/css/style1.css'?>">
<title>login</title>
</head>
<body>
<form class="form-signin" action="<?php echo base_url().'index.php/Auth/login'?>" name="frm1" id="frm1" method="post">
<?php
$msg=$this->session->flashdata('msg');
if($msg!=""){
?>
<div class="alert alert-danger">
<?php echo $msg;?>
</div>
<?php
}
?>
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="email" class="sr-only">Email address</label>
<input type="text" id="email"name="email" class="form-control" placeholder="Email address" required autofocus>
<?php echo form_error('email'); ?>
<label for="password" class="sr-only">Password</label>
<input type="<PASSWORD>" id="password"name="password" class="form-control" placeholder="<PASSWORD>" required>
<?php echo form_error('password'); ?>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</body>
</html><file_sep><?php
class Auth extends CI_Controller{
//this function will show register page
public function Register()
{ $this->load->view('Dashboard');
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name','First Name','required');
$this->form_validation->set_rules('last_name','Last Name','required');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[user4.email]');
$this->form_validation->set_rules('Phone','Phone','required');
$this->form_validation->set_rules('password','password','required');
if($this->form_validation->run()==false){
//here we will load our view
$this->load->view('register');
}else{
//here we will save user record in db
$this->load->model('Authmodel');
$formArray=array();
$formArray['first_name']=$this->input->post('first_name');
$formArray['last_name']=$this->input->post('last_name');
$formArray['email']=$this->input->post('email');
$formArray['Phone']=$this->input->post('Phone');
$formArray['password']=password_hash($this->input->post('password'),<PASSWORD>);
$formArray['created_at']=date('y-m-d H:i:s');
$this->Authmodel->create($formArray);
$this->session->set_flashdata('msg','your account has been created');
redirect(base_url().'index.php/Auth/register');
}
}
public function login()
{
$this->load->model('Authmodel');
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|valid_email');
$this->form_validation->set_rules('password','<PASSWORD>','<PASSWORD>');
if($this->form_validation->run()==true){
$email=$this->input->post('email');
$user=$this->Authmodel->checkuser($email);
if(!empty($user)){
$password=$this->input->post('password');
if(password_verify($password,$user['password'])==true){
$searchArray['id']=$user['id'];
$searchArray['first_name']=$user['first_name'];
$searchArray['last_name']=$user['last_name'];
$searchArray['email']=$user['email'];
$this->session->set_userdata('user',$searchArray);
redirect(base_url().'index.php/Auth/dashboard');
}else{
$this->session->set_flashdata('msg','either Email or Password is incorrect');
redirect(base_url().'index.php/Auth/Dashboard');
}
}else
{
$this->session->set_flashdata('$msg','Either Email or Password is incorrect');
redirect(base_url().'index.php/Auth/login');
}
}
else{
$this->load->view('login');
}
}
public function dashboard(){
$this->load->view('dashboard');
}
}
?><file_sep><!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">
<link rel="stylesheet" href="<?php echo base_url().'assets/css/bootstrap.min.css'?>">
<title>Register</title>
</head>
<body>
<div class="container" >
<?php
$msg=$this->session->flashdata('msg');
if($msg !=""){
echo "<div class=' alert alert-success'>'.$msg'</div>";
}
?>
<div class="col-md-6">
<div class="card mt-4">
<div class="card-header">
Register
</div>
<form action="<?php echo base_url().'index.php/Auth/register'?>" name="registerForm" id="registerForm" method="post">
<div class="card-body">
<h5 class="card-title">Please fill your details</h5>
<p class="card-text"></p>
<div class="form-group">
<label for="name">First Name</label>
<input type="text" name="first_name" id="first_name" values="" class="form-control" placeholder="first_name">
<p><?php echo form_error('first_name');?></p>
</div>
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" name="last_name" id="last_name" values="" class="form-control" placeholder="last_name">
<p><?php echo form_error('last_name');?></p>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" id="email" values="" class="form-control" placeholder="Email">
<p><?php echo form_error('email');?></p>
</div>
<div class="form-group">
<label for="name">Phone</label>
<input type="text" name="Phone" id="Phone" values="" class="form-control" placeholder="Phone">
<p><?php echo strip_tags(form_error('Phone'));?></p>
</div>
<div class="form-group">
<label for="name">password</label>
<input type="<PASSWORD>" name="password" id="password" values="" class="form-control" placeholder="<PASSWORD>">
<p><?php echo form_error('password');?></p>
</div>
<div class="form-group">
<button class="btn btn-block btn-primary">Register Now</button>
</div>
</body>
</html><file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 28, 2021 at 10:21 PM
-- Server version: 10.4.18-MariaDB
-- PHP Version: 7.3.27
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `frame`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`first_name` varchar(100) NOT NULL,
`last_name` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(100) NOT NULL,
`phone` varchar(100) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`, `password`, `phone`, `created_at`, `updated_at`) VALUES
(6, 'zeeshan', 'haider', '<EMAIL>', '3456', '12345', '2021-09-10 21:56:52', '0000-00-00 00:00:00'),
(7, 'zeeshan', 'bukhari', 'ze<EMAIL>', <PASSWORD>', '22222', '2021-09-10 22:04:00', '0000-00-00 00:00:00'),
(8, 'shahzaib', 'haider', '<EMAIL>', <PASSWORD>', '46777', '2021-09-10 22:04:24', '0000-00-00 00:00:00'),
(9, 'haider', 'ali ', '<EMAIL>', <PASSWORD>', '234567', '2021-09-10 23:36:13', '0000-00-00 00:00:00');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
class Authmodel extends CI_Model{
public function create($formArray){
$this->db->insert('user4',$formArray);
}
//return row array based on entered email
public function checkuser($email)
{
$this->db->where('email',$email);
return $row =$this->db->get('user4')->row_array();
}
}
?> | c8c0704929a364e1bbf8b94558ea2cdf9ae0ce43 | [
"SQL",
"PHP"
] | 6 | PHP | shani113/Rform | 67be764446f64f7381b966fe03f1b20cf9a84f8b | a975a4e75260ce882590fcc650bef8bfc235cd81 |
refs/heads/master | <repo_name>Alischrec/PasswordGenerator_Hwk03<file_sep>/script.js
// Generating a password:
// 1. Prompt user: "How many characters would you like your password to be? Must be between 8-128 characters."
// A. If within range:
// a. Confirm passoword length: "You have selected a password length of __."
// b. Move to prompt 2
// B. If out of range:
// a. Error message, then back to prompt 1
// 2. Prompt user: "Would you like your password to contain lower case characters?"
// A. If 'OK': add lower case characters to generatePassword
// B. If 'Cancel': exclude lower case characters from generatePassword
// 3. Prompt user: "Would you like your password to contain upper case characters?"
// A. If 'OK': add upper case characters to generatePassword
// B. If 'Cancel': exclude upper case characters from generatePassword
// 4. Prompt user: "Would you like your password to contain numbers?"
// A. If 'OK': add numbers to generatePassword
// B. If 'Cancel': exclude numbers from generatePassword
// 5. Prompt user: "Would you like your password to contain special characters?"
// A. If 'OK': add special characters to generatePassword
// B. If 'Cancel': exclude special characters from generatePassword
// 6. Confirm user: "Great job! You have selected a password that is ___ characters long, and contains ______, ______, ______, and ________. Ready to generate your password?"
// A. If 'OK': generatePassword
// Group of arrays:
var arrOfLowcase = 'abcdefghijklmnopqrstuvwxyz'.split('');
var arrOfUppercase = 'abcdefghijklmnopqrstuvwxyz'.toUpperCase().split('');
var arrnumeric = '0123456789'.split('');
var arrSpecialCharacters = '!@#$%^&*()_+~`|}{[]\:;?><,./-='.split('');
var characterPool = [];
// Setting password character length
function generatePassword() {
var passwordLengthInteger = 0;
while (true) {
var passwordLength = prompt('How many characters would you like your password to be? Must be between 8-128 characters.');
if (isNaN(passwordLength)) {
alert('Please, enter a valid number.');
continue;
}
passwordLengthInteger = parseInt(passwordLength);
if (8 <= passwordLengthInteger && passwordLengthInteger <= 128) {
alert('You have selected a password length of ' + passwordLength);
break;
}
else {
alert('Error! You must select a password length between 8-128 characters. Number must be a whole number, no decimals.');
}
}
// Generation of user selected password:
while (true) {
var lowerCase = confirm('Would you like your password to contain lower case characters?');
var upperCase = confirm('Would you like your password to contain upper case characters?');
var numbers = confirm('Would you like your password to contain numbers?');
var specialCharacters = confirm('Would you like your password to contain special characters?');
if (lowerCase) {
characterPool.push(...arrOfLowcase);
lowerCase = 'lower case ';
}
else {
lowerCase = '';
}
if (upperCase) {
characterPool.push(...arrOfUppercase);
upperCase = 'upper case ';
}
else {
upperCase = '';
}
if (numbers) {
characterPool.push(...arrnumeric);
numbers = 'numbers ';
}
else {
numbers = '';
}
if (specialCharacters) {
characterPool.push(...arrSpecialCharacters);
specialCharacters = 'special characters ';
}
else {
specialCharacters = '';
}
// Confirm user selected criteria
if (characterPool.length > 0) {
if (confirm('Great job! You have selected a password that is ' + passwordLength + ' characters long, and contains ' + lowerCase + upperCase + numbers + specialCharacters + ' Ready to generate your password?')) {
var userPassword = [];
var myPassword = '';
// Print password here
for (var i = 0; i < passwordLengthInteger; i++) {
var randomIndex = Math.floor(Math.random() * characterPool.length);
userPassword.push(characterPool[randomIndex]);
}
myPassword = userPassword.join('');
return myPassword;
break;
}
else {
return;
}
} else {
alert('Please, choose at least one option!');
}
}
}
// Assignment Code
var generateBtn = document.querySelector('#generate');
// Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector('#password');
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener('click', writePassword);<file_sep>/README.md
# PasswordGenerator_Hwk03
Explore the [Project Page](https://github.com/Alischrec/PasswordGenerator_Hwk03)
View the [Github-pages](https://alischrec.github.io/PasswordGenerator_Hwk03/)
## Table of Contents
* [About the Project](#about-the-project)
* [HTML](#HTML)
* [CSS](#CSS)
* [JavaScript](#JAVASCRIPT)
* [Built With](#built-with)
* [Getting Started](#getting-started)
* [Prerequisites](#prerequisites)
* [Installation](#installation)
* [Roadmap](#roadmap)
* [Contributing](#contributing)
* [License](#License)
* [Contact](#contact)
* [Acknowledgements](#acknowledgements)
## About the Project:
The focus of this project was to use Javascript to create a working password generator with the following criteria:
* User must choose password length between 8-128 char.
* User must choose whether or not their passwod will include lower/upper case letters, numbers, and/or special characters.
* Password will generate after all criteria have been chosen by the user.
The .html and .css files were created prior to assignment and instructed not to be changed while working through this project.

### HTML:
* [index.html](https://github.com/Alischrec/PasswordGenerator_Hwk03/blob/master/index.html)
### CSS:
* [style.css](https://github.com/Alischrec/PasswordGenerator_Hwk03/blob/master/style.css)
### JAVASCRIPT:
* [script.js](https://github.com/Alischrec/PasswordGenerator_Hwk03/blob/master/script.js)
### Built With:
* This app was not built with any frameworks.
## Getting Started:
To get a local copy up and running follow the steps below.
### Prerequisites:
None.
### Installation:
1. Clone the Repository:
```sh
git clone <EMAIL>:Alischrec/PasswordGenerator_Hwk03.git
```
## Roadmap:
Currently no known issues, but track track [open issues](https://github.com/Alischrec/PasswordGenerator_Hwk03/issues) for proposed features (and known issues) in the future.
## Contributing:
Any contributions you make are **greatly appreciated**.
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## License:
MIT License
Copyright (c) [2020] [<NAME>]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## Contact:
Ali-Schreck. - [@alischrec](https://www.instagram.com/alischrec) - <EMAIL>
Project Link: [https://github.com/Alischrec/PasswordGenerator_Hwk03](https://github.com/Alischrec/PasswordGenerator_Hwk03)
## Acknowledgements:
* University of Washington Coding Bootcamp for providing me with the skills and knowledge to create this project. | 1883ac592eafcac06d840172a37417c583f129e7 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Alischrec/PasswordGenerator_Hwk03 | c0552ffd288d500469c74ffa56ee26824861b56b | 3560305dd023f7f5f8a3844933754b428ccac6e9 |
refs/heads/master | <repo_name>ahmedsameha1/algorithms_and_data_structures<file_sep>/python/binary_search/test_binary_search.py
import unittest
import binary_search
class TestBinarySearch(unittest.TestCase):
def test_binary_search(self):
self.assertFalse(binary_search.search([1, 3, 5], 7))
self.assertTrue(binary_search.search([1, 3, 5], 5))
self.assertTrue(binary_search.search([1, 3, 5], 3))
self.assertTrue(binary_search.search([1, 3, 5], 1))
self.assertTrue(binary_search.search([-536, -66, -1, 1, 3, 5, 100, 1754], -66))
self.assertFalse(binary_search.search([-536, -66, -1, 1, 3, 5, 100, 1754], 7))
if __name__ == "__main__":
unittest.main()
<file_sep>/java/merge_sort/build.gradle
apply plugin: "java"
repositories.jcenter()
test {
useJUnitPlatform()
}
// Copied from: https://docs.gradle.org/current/userguide/java_testing.html#using_junit5
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.4.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.4.0'
}
<file_sep>/javascript/bubble_sort/src/bubble_sort.js
const sort = (arr) => {
let swap = true;
while(swap) {
swap = false;
for (let i = 0; i < arr.length - 1; i++) {
if ( arr[i + 1] < arr[i] ) {
let temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
swap = true;
}
}
}
return arr;
}
exports.sort = sort;
<file_sep>/python/binary_search/binary_search.py
def search(lst, num):
return search_recursive(lst, 0, len(lst) - 1, num)
def search_recursive(lst, start, end, num):
median = (start + end) // 2
if lst[median] == num:
return True
elif end - start < 1:
return False
elif lst[median] > num:
return search_recursive(lst, start, median - 1, num)
else:
return search_recursive(lst, median + 1, end, num)
<file_sep>/javascript/binary_search/src/binary_search.test.js
const {search} = require("./binary_search");
test("Test binary search algorithm implementation", () => expect(search([1, 2, 3], 5)).toEqual(false));
test("Test binary search algorithm implementation", () => expect(search([1, 2, 3], 3)).toEqual(true));
test("Test binary search algorithm implementation", () => expect(search([1, 3, 5], 5)).toEqual(true));
test("Test binary search algorithm implementation", () => expect(search([1, 3, 5], 1)).toEqual(true));
test("Test binary search algorithm implementation", () => expect(search([1, 3, 5], 7)).toEqual(false));
test("Test binary search algorithm implementation", () => expect(search([-536, -66, -1, 1, 3, 5, 100, 1754], 7)).toEqual(false));
test("Test binary search algorithm implementation", () => expect(search([-536, -66, -1, 1, 3, 5, 100, 1754], -66)).toEqual(true));
<file_sep>/python/linear_search/test_linear_search.py
import unittest
import linear_search
class TestLinearSearch(unittest.TestCase):
def test_search(self):
self.assertTrue(linear_search.search([1, 3, 5], 5))
self.assertFalse(linear_search.search([1, 3, 5], 7))
if __name__ == "__main__":
unittest.main()<file_sep>/python/selection_sort/selection_sort.py
def sort(lst):
for i in range(len(lst) - 1):
for j in range(i + 1, len(lst)):
if lst[j] < lst[i]:
temp = lst[j]
lst[j] = lst[i]
lst[i] = temp
return lst
<file_sep>/java/selection_sort/build.gradle
apply plugin: "java"
apply plugin: "application"
mainClassName = "com.ahmedsameha1.edx_algorithms_and_data_structures.selection_sort.selection_sort"
repositories {
jcenter()
}
// Copied from: https://junit.org/junit5/docs/current/user-guide/#running-tests-build-gradle
test {
useJUnitPlatform()
}
// Copied from: https://docs.gradle.org/current/userguide/java_testing.html#using_junit5
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.0'
}
<file_sep>/java/linear_search/src/main/java/com/ahmedsameha1/edx_algorithms_and_data_structures/linear_search/LinearSearch.java
package com.ahmedsameha1.edx_algorithms_and_data_structures.linear_search;
public class LinearSearch {
public boolean search(int num, int... arr) {
for ( int i: arr ) {
if ( i == num ) {
return true;
}
}
return false;
}
}
<file_sep>/javascript/linear_search/src/linear_search.js
const search = (arr, num) => {
for ( let i of arr ) {
if ( i === num ) {
return true;
}
}
return false;
};
exports.search = search;
<file_sep>/python/linear_search/linear_search.py
def search(lst, num):
for i in lst:
if i == num:
return True
return False
<file_sep>/python/bubble_sort/bubble_sort.py
def sort(lst):
swap = True
while swap:
swap = False
for i in range(len(lst) - 1):
if lst[i + 1] < lst[i]:
temp = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = temp
swap = True
return lst
<file_sep>/java/bubble_sort/src/test/java/com/ahmedsameha1/edx_algorithms_and_data_structures/bubble_sort/TestBubbleSort.java
package com.ahmedsameha1.edx_algorithms_and_data_structures.bubble_sort;
// Copied from: https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html
import static org.junit.jupiter.api.Assertions.*;
// Copied from: https://junit.org/junit5/docs/current/user-guide/
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
public class TestBubbleSort {
private BubbleSort bubbleSort;
@BeforeEach
public void setup() {
bubbleSort = new BubbleSort();
}
@Test
public void test() {
assertArrayEquals(new int[]{1, 2, 3, 4, 5}, bubbleSort.sort(5, 4, 3, 2, 1));
assertArrayEquals(new int[] {1, 2, 3, 4}, bubbleSort.sort(4, 3, 2, 1));
assertArrayEquals(new int[] {-1, 1, 2, 3, 4}, bubbleSort.sort(4, 3, 2, 1, -1));
assertArrayEquals(new int[] {-1, 15, 15, 52, 73, 104}, bubbleSort.sort(15, 73, 104, 15, 52, -1));
}
}
<file_sep>/java/binary_search/src/main/java/com/ahmedsameha1/algorithms_and_data_structures/binary_search/BinarySearch.java
package com.ahmedsameha1.algorithms_and_data_structures.binary_search;
public class BinarySearch {
public boolean search(int num, int... arr) {
return search(arr, 0, arr.length - 1, num);
}
private boolean search(int[] arr, int start, int end, int num) {
int median = (start + end) / 2;
if (arr[median] == num) {
return true;
} else if ( end - start < 1) {
return false;
} else if (arr[median] > num) {
return search(arr, start, median - 1, num);
} else {
return search(arr, median + 1, end, num);
}
}
}
<file_sep>/python/merge_sort/merge_sort.py
def sort(lst):
if len(lst) < 2:
return lst
else:
return merge(sort(lst[0:len(lst) // 2]), sort(lst[(len(lst) // 2) : len(lst)]))
def merge(lst1, lst2):
merged = []
i = 0
j = 0
while len(merged) < len(lst1) + len(lst2):
if i >= len(lst1) or (j < len(lst2) and lst2[j] < lst1[i]):
merged.append(lst2[j])
j += 1
else:
merged.append(lst1[i])
i += 1
return merged
<file_sep>/javascript/merge_sort/src/merge_sort.js
const sort = (arr) => {
if (arr.length < 2) {
return arr;
} else {
return merge(sort(arr.slice(0, arr.length / 2)), sort(arr.slice(arr.length / 2, arr.length)));
}
}
const merge = (arr1, arr2) => {
merged_arr = [];
let i = 0, j = 0;
while(merged_arr.length < arr1.length + arr2.length) {
merged_arr.push(i >= arr1.length || (j < arr2.length && arr2[j] < arr1[i])? arr2[j++] : arr1[i++]);
}
return merged_arr;
}
exports.sort = sort;
<file_sep>/python/merge_sort/test_merge_sort.py
import unittest
import merge_sort
class TestMergeSort(unittest.TestCase):
def test_merge_sort(self):
self.assertListEqual(merge_sort.sort([23, 14, 62, -1, 79, 40, 237, 136, -78]),[-78, -1, 14, 23, 40, 62, 79, 136, 237])
self.assertListEqual(merge_sort.sort([4, 3, 2, 1]), [1, 2, 3, 4])
if __name__ == "__main__":
unittest.main()
<file_sep>/java/quick_sort/src/test/java/com/ahmedsameha1/algorithms_and_data_structures/quick_sort/TestQuickSort.java
package com.ahmedsameha1.algorithms_and_data_structures.quick_sort;
// Copied from: https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html
import static org.junit.jupiter.api.Assertions.*;
// Copied from: https://junit.org/junit5/docs/current/user-guide/
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
class TestQuickSort{
private QuickSort quickSort;
@BeforeEach
public void setup() {
quickSort = new QuickSort();
}
@Test
public void test() {
assertArrayEquals(new int[] {1, 2, 3, 4, 5}, quickSort.sort(5, 4, 3, 2, 1));
assertArrayEquals(new int[] {1, 2, 3, 4}, quickSort.sort(4, 3, 2, 1));
assertArrayEquals(new int[] {-1, 1, 2, 3, 4}, quickSort.sort(4, 3, 2, 1, -1));
assertArrayEquals(new int[] {-1, 15, 15, 52, 73, 104}, quickSort.sort(15, 73, 104, 15, 52, -1));
}
}
<file_sep>/python/bubble_sort/test_bubble_sort.py
import unittest
import bubble_sort
class TestBubbleSort(unittest.TestCase):
def test_bubble_sort(self):
self.assertListEqual(bubble_sort.sort([34, 12, -7, 101, 28]), [-7, 12, 28, 34, 101])
self.assertListEqual(bubble_sort.sort([4, 3, 2, 1]), [1, 2, 3, 4])
if __name__ == "__main__":
unittest.main()
<file_sep>/java/merge_sort/src/main/java/com/ahmedsameha1/edx_algorithms_and_data_structures/merge_sort/MergeSort.java
package com.ahmedsameha1.edx_algorithms_and_data_structures.merge_sort;
import java.util.Arrays;
public class MergeSort {
public int[] sort(int... arr) {
if (arr.length < 2) {
return arr;
} else {
return merge(sort(Arrays.copyOfRange(arr, 0, (arr.length / 2))), sort(Arrays.copyOfRange(arr, (arr.length / 2), arr.length)));
}
}
private int[] merge(int[] arr1, int[] arr2) {
int[] sorted_array = new int[arr1.length + arr2.length];
int a = 0, b = 0, c = 0;
while (a < arr1.length || b < arr2.length) {
sorted_array[c++] = b >= arr2.length || ( a < arr1.length && arr1[a] < arr2[b]) ? arr1[a++] : arr2[b++];
}
return sorted_array;
}
}
<file_sep>/python/selection_sort/test_selection_sort.py
import unittest
import selection_sort
class TestSelectionSort(unittest.TestCase):
def test_selection_sort(self):
self.assertListEqual(selection_sort.sort([4, 3, 2, 1]), [1, 2, 3, 4])
self.assertListEqual(selection_sort.sort([-47, -168, 111, 4, 3, 10, 2, 1, 18, 1000, 8, 0]), [-168, -47, 0, 1, 2, 3, 4, 8, 10, 18, 111, 1000])
if __name__ == "__main__":
unittest.main()
| e2b2fbe90c83f7646ab02c12d1dc211ba9a8f748 | [
"JavaScript",
"Java",
"Python",
"Gradle"
] | 21 | Python | ahmedsameha1/algorithms_and_data_structures | e215a91767360b2334db7433317e0de7162e6e91 | bf4b6724146ef932c0ad59d371d131935201def2 |
refs/heads/master | <file_sep>require 'root.rb'
describe 'add' do
it 'adds' do
expect add(1, 2).to eq(3)
end
end<file_sep>def add(n, m)
n + m
end
def subtract(n, m)
n - m
end
def multiply(n, m)
n * m
end
def fib(n)
return 1 if n <= 2
return fib(n - 1) + fib(n - 2)
end<file_sep>require '../root.rb'
describe 'Expectation Matchers' do
it 'will match loose equality with #eq' do
expect(nil).not_to be(false)
end
end
describe 'add' do
it 'adds' do
x = add(1, 2)
expect(x).to eq(3)
end
end
describe 'add' do
it 'adds' do
x = add(1, 2)
expect(x).to_not eq(2)
end
end
describe 'subtract' do
it 'yields difference between two arguments' do
x = subtract(2, 1)
expect(x).to eq(1)
end
end
describe 'multiply' do
it 'finds the product of two numbers' do
expect(multiply(2, 3)).to eq(6)
end
end
describe 'fib' do
it 'finds the number in the fib sequence' do
expect(fib(1)).to eq(1)
expect(fib(3)).to eq(2)
expect(fib(6)).to eq(8)
end
end
| a00bb4bcd822836cf59fe5a37d3fe5b70b8c0ea7 | [
"Ruby"
] | 3 | Ruby | evanfujita/testing | d8cd4f8fbe460457b1329f5bc226e96dc6ea7cf4 | 00b15b1234a32570ece392295f16a60b1dd9367f |
refs/heads/master | <repo_name>anpero-vietnam/signalr<file_sep>/SignalR/Readme.txt
https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency/blob/master/README.md
Install-Package SqlTableDependency -Version 8.5.4
1) Add new connection string with name ="connectionString"
2) Update <httpRuntime targetFramework="4.6.2" or higher to using web socket
update database to test SqlTableDependency
3) ALTER DATABASE [DataBaseName] SET ENABLE_BROKER
4) ALTER DATABASE [DataBaseName] SET TRUSTWORTHY ON
create table to test SqlTableDependency
Create table Users(
UserName nvarchar(300),
UserId [uniqueidentifier] NOT NULL,
Status varchar(30)
)
5) go to /SqlDependency page
6) Insert or update,delete to SqlTableDependency function. In this demo only UserId=1 canbe reveice messenge for Update,remove data
insert into Users(UserId,UserName,Status) values('1','User Name 01','actice')<file_sep>/HubService/UserHub.cs
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HubService
{
[HubName("userTrackingHub")]
//[Authorize]
public class UserHub : Hub
{
private readonly UserTrackingService _userTrackingService;
public UserHub() : this(UserTrackingService.Instance)
{
}
public UserHub(UserTrackingService userTrackingService)
{
_userTrackingService = userTrackingService;
}
}
}
<file_sep>/Readme.txt
https://github.com/christiandelbianco/monitor-table-change-with-sqltabledependency/blob/master/README.md
Install-Package SqlTableDependency -Version 8.5.4
1) Add new connection string with name ="connectionString"
2) Update <httpRuntime targetFramework="4.6.2" or higher to using web socket
update database to test SqlTableDependency
3) ALTER DATABASE [DataBaseName] SET ENABLE_BROKER
4) ALTER DATABASE [DataBaseName] SET TRUSTWORTHY ON
create table to test SqlTableDependency
Create table Users(
UserName nvarchar(300),
UserId [uniqueidentifier] NOT NULL,
Status varchar(30)
)<file_sep>/SignalR/Startup.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR.Startup))]
namespace SignalR
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var idProvider = new CustomUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);
app.MapSignalR();
}
//private string CustomUserIdProvider()
//{
// return "1";
//}
}
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
// can be get token data from cookie
return "1";
}
}
}
<file_sep>/README.md
# SignalR simple example and SignalR + SqlTableDependency
1) Signalr simple example
2) Signalr simple example trigger Hub function from MVC Control
3) Simple set userid and send messege to logger by userid
3) SqlTableDependency example
SqlTableDependency is a high-level C# component to used to audit, monitor and receive notifications on SQL Server's record table change.
For all Insert/Update/Delete operation on monitored table, TableDependency receive events containing values for the record inserted, changed or deleted, as well as the DML operation executed on the table, eliminating the need of an additional SELECT to update application’s data cache.
How to user user SqlTableDependency
1) Install-Package SqlTableDependency -Version 8.5.4
2) Add new connection string with name ="connectionString"
3) Update .net Framework="4.6.2" or higher to using web socket
update database
3) ALTER DATABASE [DataBaseName] SET ENABLE_BROKER
4) ALTER DATABASE [DataBaseName] SET TRUSTWORTHY ON
create table to test SqlTableDependency
Create table Users(
UserName nvarchar(300),
UserId [uniqueidentifier] NOT NULL,
Status varchar(30)
)
5) go to page /SqlDependency
6) Insert/Update/Delete and see change in /SqlDependency page
# Optimization
1) Open Startup.cs to see how to set or get userId
If you need help don't hesitate to mail me: <EMAIL>
<file_sep>/SignalR/Controllers/SqlDependencyController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SignalR.Controllers
{
public class SqlDependencyController : Controller
{
// GET: SqlDependency
public ActionResult Index()
{
return View();
}
}
}<file_sep>/SignalR/MyHub1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace SignalR
{
[HubName("SampleHubName")]
public class MyHub1 : Hub
{
public void HelloServerFunction()
{
Clients.All.helloWord("hello word triger from server!");
}
public void SendMessengeToUser(string userId,string messenge)
{
Clients.User(userId).helloWord(messenge);
}
//public override Task OnConnected()
//{
// return base.OnConnected();
//}
//// turning on user refresh page
//public override Task OnDisconnected(bool stopCalled)
//{
// return base.OnDisconnected(stopCalled);
//}
//public override Task OnReconnected()
//{
// return base.OnReconnected();
//}
}
}<file_sep>/HubService/UserTrackingService.cs
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Configuration;
using TableDependency.SqlClient;
using TableDependency.SqlClient.Base;
using TableDependency.SqlClient.Base.Enums;
using TableDependency.SqlClient.Base.EventArgs;
namespace HubService
{
public class UserTrackingService : IDisposable
{
private readonly static Lazy<UserTrackingService> _instance = new Lazy<UserTrackingService>(() => new UserTrackingService(GlobalHost.ConnectionManager.GetHubContext<UserHub>().Clients));
private SqlTableDependency<UserTracking> SqlTableDependency { get; }
private IHubConnectionContext<dynamic> Clients { get; }
public static UserTrackingService Instance => _instance.Value;
private UserTrackingService(IHubConnectionContext<dynamic> clients)
{
this.Clients = clients;
//Because our C# model has a property not matching database table name, an explicit mapping is required just for this property.
var mapper = new ModelToTableMapper<UserTracking>();
mapper.AddMapping(x => x.Status, "Status");
// Because our C# model name differs from table name we have to specify database table name.
this.SqlTableDependency = new SqlTableDependency<UserTracking>(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString, "Users", mapper: mapper);
this.SqlTableDependency.OnChanged += this.TableDependency_OnChanged;
this.SqlTableDependency.Start();
}
private void TableDependency_OnChanged(object sender, RecordChangedEventArgs<UserTracking> e)
{
switch (e.ChangeType)
{
case ChangeType.Delete:
this.Clients.User(e.Entity.UserId).removeUserTrigger(e.Entity);
break;
case ChangeType.Insert:
this.Clients.All.addUserTrigger(e.Entity);
break;
case ChangeType.Update:
this.Clients.User(e.Entity.UserId).updateUserTrigger(e.Entity);
break;
}
}
public void Dispose()
{
// Invoke Stop() in order to remove all DB objects genetated from SqlTableDependency.
this.SqlTableDependency.Stop();
}
}
public class UserTracking
{
public string UserId { get; set; }
public string Status { get; set; }
public string UserName { get; set; }
}
}
<file_sep>/SignalR/Controllers/HomeController.cs
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SignalR.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public void CallHelloWordService()
{
var hubContex = GlobalHost.ConnectionManager.GetHubContext<MyHub1>();
hubContex.Clients.All.helloWord("hello word from HomeController!");
}
/// <summary>
/// see Startup Config current user login, in this example default user is "1"
/// to change get userId in Startup.cs file
/// </summary>
}
} | 864db803f4d8cff709a497f35fab28cf25e69ede | [
"Markdown",
"C#",
"Text"
] | 9 | Text | anpero-vietnam/signalr | 72bb261a03c350768cb8417f78573196fc236f2b | 59074e1c8d5208d92788ab746d9ca586acc9de5f |
refs/heads/master | <file_sep>package at.fh.swenga.f4u.report;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.view.document.AbstractXlsxView;
import at.fh.swenga.f4u.model.FinanceModel;
import at.fh.swenga.f4u.model.UserModel;
public class ExcelFinanceReportView extends AbstractXlsxView {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<FinanceModel> finances = (List<FinanceModel>) model.get("finances");
UserModel user = (UserModel) model.get("user");
// create a worksheet
Sheet sheet = workbook.createSheet("Finance Report");
// create style for header cells
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontName("Arial");
style.setFillForegroundColor(HSSFColor.BLUE.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.WHITE.index);
style.setFont(font);
// create a new row in the worksheet
Row headerRow = sheet.createRow(0);
// create a new cell in the row
Cell cell0 = headerRow.createCell(0);
cell0.setCellValue("Date");
cell0.setCellStyle(style);
// create a new cell in the row
Cell cell1 = headerRow.createCell(1);
cell1.setCellValue("Note");
cell1.setCellStyle(style);
// create a new cell in the row
Cell cell2 = headerRow.createCell(2);
cell2.setCellValue("Category");
cell2.setCellStyle(style);
// create a new cell in the row
Cell cell3 = headerRow.createCell(3);
cell3.setCellValue("Sucategory");
cell3.setCellStyle(style);
// create a new cell in the row
Cell cell4 = headerRow.createCell(4);
cell4.setCellValue("Incoming");
cell4.setCellStyle(style);
// create a new cell in the row
Cell cell5 = headerRow.createCell(5);
cell5.setCellValue("Outgoing");
cell5.setCellStyle(style);
// create multiple rows with finance data
int rowNum = 1;
double sumIncoming = 0;
double sumOutgoing = 0;
for (FinanceModel finance : finances) {
// create the row data
Row row = sheet.createRow(rowNum++);
if(finance.isPayment() == false)
sumOutgoing = sumOutgoing + finance.getValue()*-1;
else sumIncoming = sumIncoming + finance.getValue();
row.createCell(0).setCellValue(finance.getBookDate().toString());
row.createCell(1).setCellValue(finance.getNotes());
row.createCell(2).setCellValue(finance.getCategorie().getName());
if(finance.getSubcategorie()==null)
row.createCell(3).setCellValue("-");
else
row.createCell(3).setCellValue(finance.getSubcategorie().getName());
if(finance.isPayment())
row.createCell(4).setCellValue(finance.getValue());
else
row.createCell(5).setCellValue(finance.getValue()*-1);
}
Row sumRow = sheet.createRow(rowNum++);
Row lastRow = sheet.createRow(rowNum+1);
Row userRow = sheet.createRow(rowNum+3);
Row dateRow = sheet.createRow(rowNum+4);
sumRow.createCell(3).setCellValue("Sum");
sumRow.createCell(4).setCellValue(sumIncoming);
sumRow.createCell(5).setCellValue(sumOutgoing);
lastRow.createCell(3).setCellValue("Total");
lastRow.createCell(5).setCellValue(sumIncoming+sumOutgoing);
userRow.createCell(1).setCellValue("User: "+user.getUsername());
dateRow.createCell(1).setCellValue("Date: "+ new Date());
// adjust column width to fit the content
sheet.autoSizeColumn((short) 0);
sheet.autoSizeColumn((short) 1);
sheet.autoSizeColumn((short) 2);
}
}
| 0c051451f48ca5f9e39126ad491244a69cb378a3 | [
"Java"
] | 1 | Java | danielkandlhofer/F4U | 8733cc3300b4868bb6da5d1459599566afcbab03 | b26aec098449908e8d2a9319f43cf165698f7c35 |
refs/heads/master | <file_sep>Read me test
On modifie
<file_sep>package fr.burgers;
import java.util.ArrayList;
import java.util.List;
public class Hamburger {
protected String nom;
protected String pain;
protected String viande;
protected double prix;
protected List<IngredientSup> ingredients = new ArrayList<>();
protected int nombreMaxIngredients = 4;
protected int positionAjoutIngredient;
// Constructeurs
public Hamburger(String nom, String pain, String viande, double prix) {
super();
this.nom = nom;
this.pain = pain;
this.viande = viande;
this.prix = prix;
}
public Hamburger(String nom, String pain, double prix) {
super();
this.nom = nom;
this.pain = pain;
this.prix = prix;
}
// Méthodes
public void ajouterIngredient(IngredientSup ingredient) {
if (positionAjoutIngredient < nombreMaxIngredients) {
ingredients.add(ingredient);
positionAjoutIngredient++;
prix = prix + ingredient.getPrixIngredient();
}else {
System.out.println("Vous avez atteint le nombre maximum d'ingrédients supplémentaires pour ce burger");
}
}
// Accesseurs
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPain() {
return pain;
}
public void setPain(String pain) {
this.pain = pain;
}
public String getViande() {
return viande;
}
public void setViande(String viande) {
this.viande = viande;
}
public double getPrix() {
return prix;
}
public List<IngredientSup> getIngredients() {
return ingredients;
}
}
| 9a23d1535c75ef1486e4eb4ea5743e04219d3ce9 | [
"Markdown",
"Java"
] | 2 | Markdown | Mathilde1/projet1 | 15a02571606a0349d4981c24005d290f904e645f | 0aab81442aca28abbe5513d2ff960ff6ee613800 |
refs/heads/master | <file_sep># A minimal pdftotext service for the POC.
FROM ubuntu:18.04
MAINTAINER vgheorgh (<EMAIL>)
RUN apt-get update && apt-get install -y python python-pip poppler-utils
COPY run_pdftotext.sh /tmp/run_pdftotext.sh
ENTRYPOINT ["/bin/bash", "/tmp/run_pdftotext.sh"]<file_sep>import re
import csv
def hettichSetMatGet(iterator, matSetPair):
matSetCorrect = [n[1] for n in matSetPair]
matSetStr = str(matSetCorrect).strip('[]').replace("'", "").replace(",", "")
firstSpaceInOriginalMatIndex = iterator.find(' ')
newMaterialWithSet = iterator[:firstSpaceInOriginalMatIndex] + ' ' + matSetStr + iterator[firstSpaceInOriginalMatIndex:]
return newMaterialWithSet
def hettichMatGet(matRegexText):
materialMatches = re.findall('(1_?[a-zA-Z0-9-_]+.)(?:[ \t]+)(\*\*|CE|TW)(?:[ \t]+)(\d+(?:\.?\d+)?)(?:[ \t]+)(SET|PCE)(?:[ \t]+)(\d{0,3}(?:\d{1,3}(?:.?\d{3})*(?:\,\d{1,2})))?(?:[ \t]+)(\d{1,6})(?:[ \t]+)(\d{0,3}(?:\d{1,3}(?:.?\d{3})*(?:\,\d{1,2})))?', matRegexText)
materialNumbers = [i[0] + ' ' + i[1] + ' ' + i[2] + ' ' + i[3] + ' ' + i[4] + ' ' + i[5] + ' ' + i[6] for i in materialMatches]
materialStr = str(materialNumbers).split(', ')
materialStringed = ';'.join(materialStr).strip('[]').replace("'", "")
materialSetIterators = materialStringed.split(';')
newMaterialSetIterators = [ mat.split()[0] for mat in materialSetIterators ] #get the page splits for sets
i = 0
for id, iterator in enumerate(materialSetIterators):
if " SET " in iterator:
if i + 1 == len(materialSetIterators):
matSetPair = re.findall('{}(?:[.*\s\S]+)left (1_[a-zA-Z0-9-_]+.) and(?:[.*\s\S]+)right (1_[a-zA-Z0-9-_]+.)'.format(newMaterialSetIterators[i]), matRegexText)
materialSetIterators[id] = hettichSetMatGet(iterator, matSetPair)
else:
matSetPair = re.findall('{}(?:[.*\s\S]+)left (1_[a-zA-Z0-9-_]+.) and(?:[.*\s\S]+)right (1_[a-zA-Z0-9-_]+.)(?:[.*\s\S]+){}'.format(newMaterialSetIterators[i], newMaterialSetIterators[i+1]), matRegexText)
materialSetIterators[id] = hettichSetMatGet(iterator, matSetPair)
i += 1
else:
i += 1
materialStringedWithSets = ';'.join(materialSetIterators).strip('[]').replace("'", "")
# must remove CE/TW from return
return materialStringedWithSets
def hettichGet(filename):
with open(filename, 'r') as invoiceTxt:
fileContent = invoiceTxt.read().replace('\n\n', '\n')
# All the POs
poNoMatches = re.findall('(?:Your Order:|Votre commande :) 4[0-9]{9}', fileContent)
poNoStr = str(poNoMatches[0])
poNo = poNoStr.strip("Your Order: ").strip("Votre commande : ")
# Nr of invoice
invoiceNrMatch = re.search('(Invoice:|Facture:)(?:[ \t]+)9[0-9]{9}', fileContent)
invoiceNrStr = invoiceNrMatch.group(0).strip("Invoice: ").strip("Facture: ")
# Date of invoice
invoiceDateMatch = re.search('(?:Date\:[ \t]+)((?:\d{2})[\.](?:\d{2})[\.](?:\d{4}))', fileContent)
invoiceDateStr = invoiceDateMatch.group(0).strip("Date: ")
# Total amount
totalAmountMatch = re.search('(?:Total amount|Montant total)[ \t]+(\d{0,3}(?:\d{1,3}(?:.?\d{3})*(?:\,\d{1,2})))?', fileContent)
totalAmountStr = totalAmountMatch.group(0).strip("Total amount ").strip("Montant total ")
# Currency
currencyMatch = re.search('(?:MA:Item(?:[ \t]+?)Description|Nr\. d\'article(?:[ \t]+?)Description)(?:[ \t]+?)([a-zA-Z]{3})', fileContent)
currencyStr = currencyMatch.group(0)
currencySymbol = currencyStr[-3:]
if len(poNoMatches) == 1:
materialStringed = hettichMatGet(fileContent)
poStringed = poNo + ";" + materialStringed.replace(" CE ", " ").replace(" TW ", " ").replace(" ", " ")
elif len(poNoMatches) > 1:
i = 0
poComplete = []
for po in poNoMatches:
if i + 1 == len(poNoMatches):
poMatList = re.findall('{}(.*[\s\S]+)'.format(poNoMatches[i]), fileContent)
poMatText = str(poMatList).replace('\\n', '\n')
materialStringed = hettichMatGet(poMatText)
thisPO = po.strip("Your Order: ").strip("Votre commande : ") + ";" + materialStringed
poComplete.append(thisPO)
else:
poMatList = re.findall('{}(.*[\s\S]+){}'.format(poNoMatches[i], poNoMatches[i+1]), fileContent)
poMatText = str(poMatList).replace('\\n', '\n')
materialStringed = hettichMatGet(poMatText)
thisPO = po.strip("Your Order: ").strip("Votre commande : ") + ";" + materialStringed
poComplete.append(thisPO)
i += 1
poStringed = ';'.join(poComplete).strip('[]').replace("'", "").replace(" CE ", " ").replace(' ', ' ').replace(" TW ", " ")
# SAProw = [invoiceNrStr, invoiceDateStr, totalAmountStr, currencySymbol, poStringed]
SAProw = invoiceNrStr + ';' + invoiceDateStr + ';' + totalAmountStr + ';' + currencySymbol + ';"' + poStringed + '"'
invoiceTxt.close()
return(SAProw)
# with open(r"C:\Users\VGHEORGH\Desktop\PDFs\MIRO.txt", "a+", newline='') as f:
# writer = csv.writer(f, delimiter=';')
# writer.writerow(row)
<file_sep>import os
import subprocess
from hettich import hettichGet
from lehmann import lehmannGet
import re
import pyrfc
#original author vgheorgh
##to do
##1. add logger of activity to run.log file
##2. add class for RFC signal handling
##3. think of monitoring and alerting
def get_env(filename):
filepath = os.getcwd() + "/" + filename
cfglines = tuple(open(filepath, 'r'))
for i, a in enumerate(cfglines):
if 'server' in a:
global server
server = a[a.find('=') + 1:a.find(';')]
elif 'pdfpath' in a:
global pdfpath
pdfpath = a[a.find('=') + 1:a.find(';')]
elif 'ashost' in a:
global ashost
ashost = a[a.find('=') + 1:a.find(';')]
elif 'sysnr' in a:
global sysnr
sysnr = a[a.find('=') + 1:a.find(';')]
elif 'client' in a:
global client
client = a[a.find('=') + 1:a.find(';')]
elif 'user' in a:
global user
user = a[a.find('=') + 1:a.find(';')]
elif 'password' in a:
global password
password = a[a.find('=') + 1:a.find(';')]
elif 'testRFCname' in a:
global testRFCname
testRFCname = a[a.find('=') + 1:a.find(';')]
elif 'realRFCname' in a:
global realRFCname
realRFCname = a[a.find('=') + 1:a.find(';')]
else:
print('Unknown parameter in main.cfg')
class Invoice:
ProcessedFilesCounter = 0
def __init__(self, txtname):
self.txtname = txtname
self.fullname = pdfpath + txtname
Invoice.ProcessedFilesCounter += 1
@property
def poNo(self):
with open(self.fullname, 'r') as invoiceTxt:
fileContent = invoiceTxt.read()
if re.match("Hettich Marketing- u\. Vertriebs GmbH & Co\.KG ·", fileContent):
return hettichGet(self.fullname)
elif re.match("LEHMANN Vertriebsgesellschaft mbH & Co\. KG •", fileContent):
return lehmannGet(self.fullname)
else:
return None
class callRFC:
def __init__(self, ashost, sysnr, client, user, password):
self.ashost = ashost
self.sysnr = sysnr
self.client = client
self.user = user
self.password = <PASSWORD>
def helloRFC(self):
try:
rfcConn = pyrfc.Connection(ashost=self.ashost, sysnr=self.sysnr, client=self.client, user=self.user, passwd=<PASSWORD>)
result = rfcConn.call(testRFCname, REQUTEXT='test')
return result
except pyrfc.RFCError as rfcerror:
return rfcerror
def realRFC(self, poString):
try:
rfcConn = pyrfc.Connection(ashost=self.ashost, sysnr=self.sysnr, client=self.client, user=self.user, passwd=<PASSWORD>)
result = rfcConn.call(realRFCname, IV_IMPORT=poString)
return result
except pyrfc.RFCError as rfcerror:
return rfcerror
if __name__ == "__main__":
get_env('main.cfg')
########################################################################################################################
########################### NOT USED IN PRODUCTION ONLY ON LOCAL WINDOWS MACHINE #######################################
if server == 'local':
def dockertxt():
try:
subprocess.check_output("docker run -v" + " " + pdfpath + ":\data" + " " + "mypdftotxt", shell=True)
except subprocess.CalledProcessError as error:
return error
dockertxt()
########################### NOT USED IN PRODUCTION ONLY ON LOCAL WINDOWS MACHINE #######################################
########################################################################################################################
elif server == 'server':
def simpletxt():
try:
subprocess.check_output("/bin/bash /projects/git/pdfmoney/run_pdftotext.sh", shell=True)
except subprocess.CalledProcessError as error:
return error
simpletxt()
else:
print('Edit the main.cfg to either run local or on server. There\'s no other way.')
testconn = callRFC(ashost, sysnr, client, user, password).helloRFC()
if type(testconn) is not dict:
print('ERP is unreachable. Proceed to exit hard.')
exit(99) #exit hard
for file in os.listdir(pdfpath):
if file.endswith(".txt"):
txtFile = Invoice(file)
if txtFile.poNo:
poStringed = str(txtFile.poNo)
realconn = callRFC(ashost, sysnr, client, user, password).realRFC(poStringed)
print(realconn)
os.remove(txtFile.fullname)
<file_sep># pypy
Collection of misc python scripts
<file_sep>Depends on pyRFC and docker IF ran locally.
<file_sep>#!usr/bin/env python
#nagios custom check 1-on-1 between /etc/fstab entries and /proc/self/moounts
__author == "__rzr19__"
import subprocess,sys
#uuidFstabCmd="for i in `cat/etc/fstab|sed 's@\s+@\s@g;s@\(^s3fs\).*\s\(\/.*\)@\1\2@g'|grep -v '^#'|awk '{print$1}'|cut -c6-60`; do blkid -U $i; done"
uuidFstabCmd="cat /etc/fstab | grep -v "^[UUID=]"
proc1=subprocess.Popen(uuidFstabCmd,stdout=subprocess.PIPE,shell=True)
(out1,err)=proc1.communicate()
uuidFstabOut=out1.split()
mountListCmd="cat /proc/self/mounts|awk '{print $1}'"
proc2=subprocess.Popen(mountListCmd, stdout=subprocess.PIPE, shell=True)
(out2,err)=proc2.communicate()
mountListOut=out2.split()
diff=list(set(mountListOut)-set(uuidFstabCmd))
if(diff!=''):
for i in diff:
print("The /etc/fstab entry" + diff[i] + "is not mounted")
syst.exit(2)
else:
print("All the /etc/fstab entries are mounted")
sys.exit(0)
<file_sep>#!/bin/bash
IFS=$'\n';
for file in $(find '/\data/' -iname '*.pdf'); do /usr/bin/pdftotext -layout "$file"; done
<file_sep>import re
import csv
def lehmannMissingMatGet(matRegexText):
splitMatRegexText = matRegexText.split('carry ')[1].split('Hausanschrift:')[0]
convertedMatRegexText = re.sub('\s+', ' ', str(splitMatRegexText).strip('[]').replace("'", ""))
missingMatIdRegex = re.search('(?:over )(?:\d{0,3}(?:\d{1,3}(.?\d{3})*(?:\,\d{1,2})))(?:\s.*?\s)(\d{4,25})', convertedMatRegexText) #lazy search for the first materialId after carry over
if missingMatIdRegex:
missingMatId = missingMatIdRegex.group(2)
return missingMatId
def lehmannMatGet(matRegexText):
pageMatAttrsIndexed = re.findall('(\d{5,20}.?)(?:[ \t]+)(\d{1,5} PCS \d{1,5})(?:[ \t]+)(\d{0,3}(?:\d{1,3}(.?\d{3})*(?:\,\d{1,2})))(?:[ \t]+)(\d{0,3}(?:\d{1,3}(.?\d{3})*(?:\,\d{1,2})))', matRegexText)
pageMatAttrList = [ i[1] + ' ' + i[2] + ' ' + i[3] + ' ' + i[4] for i in pageMatAttrsIndexed ]
pageMatIndexes = [ i[0] for i in pageMatAttrsIndexed ]
pageMatIds = []
n = 0
for index in pageMatIndexes:
if n + 1 < len(pageMatIndexes):
thisIndexMaterialSearch = re.findall('{}([.\s\S]+?){}'.format(pageMatIndexes[n], pageMatIndexes[n+1]), matRegexText)
thisIndexMaterialSearch2 = re.sub('\s+', ' ', str(thisIndexMaterialSearch).strip('[]').replace("'", ""))
thisIndexMaterialSearch3 = thisIndexMaterialSearch2.replace("\\n ", "\n")
thisIndexMaterial = re.search('^(\d[-_a-zA-Z0-9]{3,25})$', thisIndexMaterialSearch3, flags=re.MULTILINE)
if thisIndexMaterial: # if match re.search
if pageMatIndexes[n] == pageMatIndexes[n + 1]:
matRegexText = matRegexText.split(str(thisIndexMaterial.group(0)))[1]
pageMatIds.append(thisIndexMaterial.group(0))
n += 1
else:
lastIndexMaterialSearch = re.findall('{}(.*[\s\S]+?){}'.format(pageMatIndexes[n], '(carry over|Goods value)'), matRegexText) #Can really be last page with no carry over.
#Best also check for Goods value as last page indicator.
lastIndexMaterialSearch2 = re.sub('\s+', ' ', str(lastIndexMaterialSearch).strip('[]').replace("'", ""))
lastIndexMaterialSearch3 = lastIndexMaterialSearch2.replace("\\n ", "\n")
lastIndexMaterial = re.search('^(\d[-_a-zA-Z0-9]{3,25})', lastIndexMaterialSearch3, flags=re.MULTILINE)
if lastIndexMaterial: # if match re.search
pageMatIds.append(lastIndexMaterial.group(0))
thisPageMaterials = [id + ' ' + attr for id, attr in zip(pageMatIds, pageMatAttrList)]
if len(pageMatIds) < len(pageMatAttrList):
thisPageMaterials.append("missingMatId" + ' ' + pageMatAttrList[len(pageMatAttrList) - 1])
pageMaterials = str(thisPageMaterials).strip('[]').replace("', '", ";").replace("'", "").replace(" ", " ")
return pageMaterials
def lehmannGet(filename):
with open(filename, 'r') as invoiceTxt:
# For Lehmann we do line by line instead of one-big-string i.e. Hettich. The re.findall regex is 10 times faster nowo in MULTILINE mode
fileContent = invoiceTxt.read().replace('\n\n', '\n')
# Nr of invoice
invoiceNrMatch = re.search('INVOICE NO\.: [0-9]{6}', fileContent)
invoiceNrStr = invoiceNrMatch.group(0).strip("INVOICE NO\.: ")
# Date of invoice
invoiceDateMatch = re.search('(?:Date[ \t]+\: )((\d{2})[\.](\d{2})[\.](\d{4}))', fileContent)
if invoiceDateMatch:
invoiceDateStr = invoiceDateMatch.group(1)
else:
invoiceDateStr = ''
poNoMatch = re.search('(?:Order[ \t]+\: )(4[0-9]{9})', fileContent)
if poNoMatch:
poNo = poNoMatch.group(1)
else:
poNo = ''
# Pages to scan for Materials
listedPagesMatch = re.findall('Page \d{1,4}\\n', fileContent)
i = 0
poMatList = []
# First page is not "Paged". These go without iteration over listedPagesMatch.
pageOneContent = fileContent.split('Page 2\n')[0]
pageOneMaterialsStr = lehmannMatGet(pageOneContent)
if "missingMatId" in pageOneMaterialsStr:
missingMatIdText = fileContent.split('Page 2\n')[1].split('Page 3\n')[0]
missingMatId = lehmannMissingMatGet(missingMatIdText)
newPageOneMaterialsStr = pageOneMaterialsStr.replace("missingMatId", missingMatId, 1)
poMatList.append(newPageOneMaterialsStr)
else:
poMatList.append(pageOneMaterialsStr)
for page in listedPagesMatch:
if i + 1 < len(listedPagesMatch):
thisPageString = re.findall('{}(.*[\s\S]+){}'.format(listedPagesMatch[i], listedPagesMatch[i+1]), fileContent, flags=re.MULTILINE)
thisPageStringed = str(thisPageString).replace('\\n', '\n')
thisPageMaterialStr = lehmannMatGet(thisPageStringed)
poMatList.append(thisPageMaterialStr)
i += 1
else:
lastPageString = re.findall('{}(.*[\s\S]+)'.format(listedPagesMatch[i]), fileContent, flags=re.MULTILINE)
lastPageStringed = str(lastPageString).replace('\\n', '\n')
lastPageMaterialStr = lehmannMatGet(lastPageStringed)
# Total Amount & currency
lastPageForTotal = lastPageStringed.split('Total value')[1]
totalAmountMatch = re.search('(\d{0,3}(?:\d{1,3}(.?\d{3})*(?:\,\d{1,2})))$(?<!0,00)', lastPageForTotal, flags=re.MULTILINE) #here be dragons on 0,00 logic
currencyStr = 'EUR'
if totalAmountMatch:
totalAmountStr = totalAmountMatch.group(1)
else:
totalAmountStr = '0,00'
if lastPageMaterialStr:
poMatList.append(lastPageMaterialStr)
totalMaterialsListed = ';'.join(poMatList)
poStringed = poNo + ';' + totalMaterialsListed
# SAProw = [invoiceNrStr, invoiceDateStr, totalAmountStr, currencyStr,'"' + poStringed + '"']
SAProw = invoiceNrStr + ';' + invoiceDateStr + ';' + totalAmountStr + ';' + currencyStr + ';"' + poStringed + '"'
invoiceTxt.close()
return(SAProw)
# with open(r"C:\Users\VGHEORGH\Desktop\PDFs\MIRO.txt", "a+", newline='') as f:
# writer = csv.writer(f, delimiter=';')
# writer.writerow(row)
| 4275fd41442cc19fd37eae6583f2eee94d1294ee | [
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 8 | Dockerfile | rzr19/pypy | aa247ecfc63e6d53bd73ddee257d265cfdadee8b | 5da607341f8b6ab85e6ec3ce644482bc84cbcb91 |
refs/heads/master | <file_sep>import Controller from './controller/Controller.js'
var game = new Controller();
game.init();<file_sep># e-snake-6
[Demo](https://bdeglane.github.io/e-snake-6/ "demo")
## install
```
npm install
npm run build
```<file_sep>'use strict';
import VertebraView from '../view/VertebraView.js';
class Vertebra {
constructor(coordinate, data) {
this.coor = {
x: coordinate.x,
y: coordinate.y
};
if (typeof data === 'undefined') {
this.data = {
base: "snake-body",
type: "body"
};
} else {
this.data = data;
}
this.domElement = this.create();
}
setCoor(coordinate) {
this.coor = {
x: coordinate.x,
y: coordinate.y
};
}
getCoor() {
return this.coor;
}
setData(data) {
this.data = data;
}
getData() {
return this.data;
}
create() {
var vertebraView = new VertebraView(this);
return vertebraView.createDomElement();
}
setHtmlData() {
this.domElement.className = '';
for (var ii in this.data) {
this.domElement.className += ' ' + this.data[ii];
}
}
render(target) {
this.setHtmlData();
var htmlDivTarget = document.getElementById(target);
htmlDivTarget.appendChild(this.domElement)
}
updateRender() {
this.domElement.style.left = this.coor.x + 'px';
this.domElement.style.top = this.coor.y + 'px';
this.setHtmlData();
}
}
export default Vertebra;<file_sep>/**
* Created by ben on 14/01/2016.
*/
'use strict';
import View from './View.js';
class BoardView extends View {
/**
*
* @param element
*/
constructor(element) {
super();
this.element = element;
}
createDomElement() {
this.domElement = document.createElement('div');
this.domElement.style.width = this.element.width + 'px';
this.domElement.style.height = this.element.height + 'px';
this.domElement.id = 'board';
this.domElement.classList.add('board');
return this.domElement;
}
}
export default BoardView;<file_sep>/**
* Created by ben on 12/01/2016.
*/
'use strict';
class View {
constructor(){}
}
export default View;<file_sep>'use strict';
import ScoreView from '../view/ScoreView.js';
class Score {
constructor() {
this.score = 0;
this.domElement = this.create();
}
add() {
this.score++;
this.render('board');
}
reset() {
this.score = 0;
}
create() {
var scoreView = new ScoreView(this);
return scoreView.createDomElement();
}
render(target) {
var htmlDivTarget = document.getElementById(target);
this.domElement.innerHTML = this.score;
htmlDivTarget.appendChild(this.domElement)
}
}
export default Score;<file_sep>'use strict';
import View from './View.js';
class ScoreView extends View {
constructor(element) {
super();
this.element = element;
}
createDomElement() {
this.domElement = document.createElement('div');
this.domElement.classList.add('score');
return this.domElement;
}
}
export default ScoreView;<file_sep>'use strict';
import Backbone from '../class/Backbone.js';
class Snake {
constructor(caseSize) {
this.coor = {
x: caseSize * 2,
y: caseSize * 2
};
this.dir = {
x: 1,
y: 0
};
this.backbone = new Backbone(caseSize);
this.caseSize = caseSize;
}
moveLeft() {
this.setDir({
x: -1,
y: 0
});
}
moveUp() {
this.setDir({
x: 0,
y: -1
});
}
moveRight() {
this.setDir({
x: 1,
y: 0
});
}
moveDown() {
this.setDir({
x: 0,
y: 1
});
}
move() {
this.coor.x += this.dir.x * this.caseSize;
this.coor.y += this.dir.y * this.caseSize;
this.updateBackbone(this.coor);
}
setDir(coordinate) {
this.dir = {
x: coordinate.x,
y: coordinate.y
};
}
updateBackbone() {
this.backbone.iterate(this.coor,{
base: "snake-body",
type: "body"
});
}
}
export default Snake;<file_sep>'use strict';
import BoardView from '../view/BoardView.js';
class Board {
constructor(caseSize,target) {
var game = document.getElementById(target);
this.width = game.offsetWidth;
this.height = game.offsetHeight;
this.caseSize = caseSize;
this.domElement = this.create();
}
isInBoard(coor){
return !!(
coor.x < 0 ||
coor.x > this.width ||
coor.y < 0 ||
coor.y > this.height
);
}
create() {
var boardView = new BoardView(this);
return boardView.createDomElement();
}
render(target) {
var htmlDivTarget = document.getElementById(target);
htmlDivTarget.appendChild(this.domElement)
}
}
export default Board; | 616bed4c320ae99580efaca4a7ffd6f48292b09b | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | bdeglane/e-snake-6 | 9f4203034075aab7c95cedb3d5ea2382f37575db | 2b40637e2355cf0197d55350435198470c4e2a68 |
refs/heads/master | <file_sep># BAmazon
How to use BAmazon App:
## Getting Started
- In Bash, type git clone "<EMAIL>:Vertigo-1/BAmazon.git"
- Run command in Terminal or Gitbash "npm install" to download required modules.
- Run command depending which mode you would like to be on:
* Customer - 'npm run customer'
* Manager - 'npm run manager'
* Exective - 'npm run exective'
- Run 'ctrl + c' to exit each mode
## Technologies used
[x] Node, Inquire, MYSQL
### Prerequisites
```
- Node.js - Download the latest version of Node https://nodejs.org/en/
- Create a MYSQL database called 'Bamazon', reference schema.sql
```
<file_sep>CREATE DATABASE Bamazon;
USE Bamazon;
CREATE TABLE Products
(
ItemID MEDIUMINT
AUTO_INCREMENT NOT NULL,
ProductName VARCHAR
(100) NOT NULL,
DepartmentName VARCHAR
(50) NOT NULL,
Price DECIMAL
(10,2) NOT NULL,
StockQuantity INT
(10) NOT NULL,
primary key
(ItemID)
);
select *
from Products;
INSERT INTO Products
(ProductName,DepartmentName,Price,StockQuantity)
VALUES
("Red Dead Redemption 2", "ENTERTAINMENT", 59.99, 250),
("Valkyria Chronicles 4", "ENTERTAINMENT", 49.95, 120),
("Tropico 6", "ENTERTAINMENT", 59.99, 100),
("Metro Exodus", "ENTERTAINMENT", 59.99, 200),
("Resident Evil 2", "ENTERTAINMENT", 59.99, 200),
("Grim Dawn", "ENTERTAINMENT", 29.95, 100),
("Crate of Bananas", "GROCERY", 44.50, 50),
("Chex Mix", "GROCERY", 4.50, 500),
("Burbery Sunglasses", "CLOTHING", 275.00, 5),
("Lee Jeans", "CLOTHING", 54.25, 35),
("Survival Towel", "SPORTS & OUTDOORS", 42.42, 42),
("Bill and Ted's Excellent Adventure", "ENTERTAINMENT", 15.00, 25),
("Alien Anthology", "ENTERTAINMENT", 25.99, 57),
("Monopoly", "ENTERTAINMENT", 19.95, 23),
("Chess Set", "ENTERTAINMENT", 30.99, 35);
CREATE TABLE Departments
(
DepartmentID MEDIUMINT
AUTO_INCREMENT NOT NULL,
DepartmentName VARCHAR
(50) NOT NULL,
OverHeadCosts DECIMAL
(10,2) NOT NULL,
TotalSales DECIMAL
(10,2) NOT NULL,
PRIMARY KEY
(DepartmentID));
INSERT INTO Departments
(DepartmentName, OverHeadCosts, TotalSales)
VALUES
('ENTERTAINMENT', 50000.00, 15000.00),
('ELECTRONICS', 20000.00, 12000.00),
('HOME', 30000.00, 15000.00),
('BEAUTY & HEALTH', 3000.00, 12000.00),
('GROCERY', 1200.00, 15000.00),
('KIDS', 40000.00, 12000.00),
('CLOTHING', 35000.00, 15000.00),
('SPORTS & OUTDOORS', 12000.00, 12000.00); | 11907f5234665d2739887f20e864b70594a52b28 | [
"Markdown",
"SQL"
] | 2 | Markdown | Vertigo-1/BAmazon | a0b03b39cc63b87cfe6d959f09f0fa2cf1658c33 | a56e4afdd5fcd25782147f207bb48013e5aa161e |
refs/heads/master | <repo_name>mtn81/sls-python-sample<file_sep>/handler.py
# coding: utf-8
import json
import logging
import boto3
import uuid
import os
# ログの設定
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# DynamoDB
logger.info('DYNAMO_URL:' + str(os.environ.get('DYNAMO_URL')))
dynamodb = (lambda url:
boto3.resource('dynamodb') if url is None
else boto3.resource('dynamodb', endpoint_url=url)
)(os.environ.get('DYNAMO_URL'))
#dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:8000')
#dynamodb = boto3.resource('dynamodb')
persons_tbl = dynamodb.Table('persons')
def create_person(event, context):
logger.info('context:' + str(context))
logger.info('headers:' + str(event['headers']))
logger.info('body:' + event['body'])
body = json.loads(event['body'])
id = str(uuid.uuid4())
persons_tbl.put_item(
Item = {
'id': id,
'name': body['name'],
'age': body['age']
}
)
response = {
"statusCode": 200,
"body": json.dumps({
'id': id
})
}
return response
def get_person(event, context):
logger.info('event' + str(event['pathParameters']))
id = event['pathParameters']['id']
res = persons_tbl.get_item(Key={'id': id})
logger.info(f'dynamodbres = {res}')
person = res.get('Item')
if person is None:
return {
"statusCode": 404,
"body": json.dumps({
'message': 'Not Found'
})
}
else:
return {
"statusCode": 200,
"body": json.dumps(person)
}
| 113b2e93936b99a04100337ac96fe3852b48bb81 | [
"Python"
] | 1 | Python | mtn81/sls-python-sample | 4879d08db98eca840a9c294c4e2d9e2529c20c81 | ece3f5598fd64961124f114efaa3d7fd6831f13f |
refs/heads/master | <repo_name>steedn/SQL-bear-organizer-lab-onl01-seng-ft-072720<file_sep>/lib/insert.sql
-- INSERT INTO bears VALUES (1,"Mr. Chocolate", 20, "M", "dark brown", "calm", 0);
-- INSERT INTO bears VALUES (2,"Rowdy", 10, "M", "black", "intense", 1);
-- INSERT INTO bears VALUES (3,"Tabitha", 6, "F", "dark brown", "Nice", 1);
-- INSERT INTO bears VALUES (4,"<NAME>", 19, "M", "Green", "Slimy", 0);
-- INSERT INTO bears VALUES (5, "Melissa", 14, "F", "brown", "curious", 1);
-- INSERT INTO bears VALUES (6, "Grinch", 66, "M", "pale brown", "very grumpy", 0);
-- INSERT INTO bears VALUES (7, "Wendy", 23 "F", "pale brown", "unbothered" 1);
-- INSERT INTO bears VALUES (8, NULL, 52, "F", "white", "annoyed", 1);
INSERT INTO bears VALUES (1,"Mr. Chocolate", 20, "M", "dark brown", "calm", 1);
INSERT INTO bears VALUES (2,"Rowdy", 10, "M", "black", "intense", 1);
INSERT INTO bears VALUES (3,"Tabitha", 6, "F", "dark brown", "Nice", 0);
INSERT INTO bears VALUES (4,"<NAME>", 19, "M", "Green", "Slimy", 1);
INSERT INTO bears VALUES (5,"Melissa", 13, "F", "dark brown", "goofy", 1);
INSERT INTO bears VALUES (6,"Grinch", 2, "M", "Black", "Grinchy", 1);
INSERT INTO bears VALUES (7,"Wendy", 12, "F", "Blue", "naive", 0);
INSERT INTO bears VALUES (8,null, 20, "M", "black", "aggressive", 0);
| 30f58b54d887699b250c1f9e1cf300cff2f586d3 | [
"SQL"
] | 1 | SQL | steedn/SQL-bear-organizer-lab-onl01-seng-ft-072720 | 3027a0c292da9e80c924428aa900a658ea62c93a | d6670f56395f70b8f69202499b47c694b84bfc7b |
refs/heads/master | <file_sep>const cheerio = require('cheerio');
let htmlTableToArray = function (html) {
console.log('ОК');
const $ = cheerio.load(html, { decodeEntities: false })
console.log('ОК');
let tableLenght = $('table').find('tr').length
console.log(tableLenght);
let result = createArray(tableLenght);
console.log('ОК');
$('table').find('tr').each(function (trIndex, trElement) {
let tdNumber = 0;
let thElements = $(trElement).find('th')
let cellsType = 'td';
if (thElements.length > 0) {
cellsType = 'th'
}
// console.log(cellsType);
$(trElement).find(cellsType).each(function (index, tdElement) {
let rowspanCount = $(tdElement).attr('rowspan');
let colspanCount = $(tdElement).attr('colspan');
if (colspanCount) {
for (let i = 0; i < colspanCount; i++) {
while (result[trIndex][tdNumber]) {
tdNumber = tdNumber + 1;
}
result[trIndex][tdNumber] = $(tdElement).html().trim()
tdNumber = tdNumber + 1;
}
// console.log('rowspan', result);
}
if (rowspanCount) {
for (let i = 0; i < rowspanCount; i++) {
result[trIndex + i][tdNumber] = $(tdElement).html().trim()
}
// console.log('colspan', result);
}
if (!rowspanCount && !colspanCount) {
while (result[trIndex][tdNumber]) {
tdNumber = tdNumber + 1;
}
result[trIndex][tdNumber] = $(tdElement).html().trim()
tdNumber = tdNumber + 1;
// console.log('normal', result);
}
})
})
return result;
}
function createArray(arrayLength) {
let temp = []
for (let i = 0; i < arrayLength; i++) {
temp.push([])
}
return temp;
}
module.exports = htmlTableToArray;
| 274aba82dcc353d604acb5bba4f08f5f545f5781 | [
"JavaScript"
] | 1 | JavaScript | denissakharov/tableToArray | 175c1c2bfd7f027248438383cb665107f6d31e32 | 6d588ce08d541a42ea6a05fb4a79372c103607da |
refs/heads/master | <file_sep>#pragma once
#include <array>
#include <map>
#include "ndarray.hpp"
// ============================================================================
namespace patches2d {
class Database;
// ========================================================================
enum class Field
{
cell_coords,
vert_coords,
conserved,
};
// ========================================================================
enum class MeshLocation
{
vert,
cell,
};
// ========================================================================
struct FieldDescriptor
{
FieldDescriptor(int num_fields, MeshLocation location);
int num_fields;
MeshLocation location;
};
}
// ============================================================================
class patches2d::Database
{
public:
// ========================================================================
using Header = std::map<Field, FieldDescriptor>;
using Index = std::tuple<int, int, int, Field>; // i, j, level, which
using Array = nd::array<double, 3>;
// ========================================================================
Database(int ni, int nj, Header header);
/**
* Insert a deep copy of the given array into the database at the given
* patch index. Any existing data at that location is overwritten.
*/
void insert(Index index, Array data);
/**
* Erase any patch data at the given index.
*/
auto erase(Index index);
/**
* Merge data into the database at index, with the given weighting factor.
* Setting rk_factor=0.0 corresponds to overwriting the existing data.
*
* An exception is throws if a patch does not already exist at the given patch
* index. Use insert to create a new patch.
*/
void commit(Index index, Array data, double rk_factor=0.0);
/**
* Return a deep copy of the data at the patch index, padded with the
* given number of guard zones. If no data exists at that index, or the
* data has the wrong size, an exception is thrown.
*/
Array fetch(Index index, int guard=0) const;
/** Return all patches registered for the given field. */
std::map<Index, Array> all(Field which) const;
/** Return an iterator to the beginning of the container of patches. */
auto begin() const { return patches.begin(); }
/** Return an iterator to the end of the container of patches. */
auto end() const { return patches.end(); }
/** Return the number of patches. */
std::size_t size() const { return patches.size(); }
/** Return the number of patches associated with the given field. */
std::size_t count(Field which) const;
/** Return the total number of cells associated with the given field. */
std::size_t num_cells(Field which) const;
/** Print a description of the patch locations. */
void print(std::ostream& os) const;
private:
// ========================================================================
int num_fields(Index index) const;
MeshLocation location(Index index) const;
std::array<int, 3> expected_shape(Index index) const;
std::array<Index, 4> refine(Index index) const;
Index coarsen(Index index) const;
Array check_shape(Array& array, Index index) const;
Array locate(Index index) const;
Array quadrant(const nd::array<double, 3>& A, int I, int J) const;
Array tile(std::array<Index, 4> indexes) const;
Array prolongation(const nd::array<double, 3>& A) const;
Array restriction(const nd::array<double, 3>& A) const;
template <typename IndexContainer>
bool contains_all(IndexContainer indexes) const
{
for (auto index : indexes)
{
if (patches.count(index) == 0)
{
return false;
}
}
return true;
}
// ========================================================================
int ni;
int nj;
Header header;
std::map<Index, Array> patches;
};
// ============================================================================
namespace patches2d {
std::string to_string(Database::Index index);
}
<file_sep>#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <vector>
#include <thread>
#include <future>
#include "app_utils.hpp"
#include "ndarray.hpp"
#include "physics.hpp"
#include "patches.hpp"
#include "ufunc.hpp"
#include "visit_struct.hpp"
using namespace patches2d;
// ============================================================================
#define MIN3ABS(a, b, c) std::min(std::min(std::fabs(a), std::fabs(b)), std::fabs(c))
#define SGN(x) std::copysign(1, x)
static double minmod(double ul, double u0, double ur, double theta)
{
const double a = theta * (u0 - ul);
const double b = 0.5 * (ur - ul);
const double c = theta * (ur - u0);
return 0.25 * std::fabs(SGN(a) + SGN(b)) * (SGN(a) + SGN(c)) * MIN3ABS(a, b, c);
}
// ============================================================================
struct gradient_plm
{
gradient_plm(double theta) : theta(theta) {}
double inline operator()(double a, double b, double c) const
{
return minmod(a, b, c, theta);
}
double theta;
};
struct shocktube
{
inline std::array<double, 5> operator()(std::array<double, 1> x) const
{
return x[0] < 0.5
? std::array<double, 5>{1.0, 0.0, 0.0, 0.0, 1.000}
: std::array<double, 5>{0.1, 0.0, 0.0, 0.0, 0.125};
}
};
struct shocktube_2d
{
inline std::array<double, 5> operator()(std::array<double, 2> x) const
{
return x[0] + x[1] < 1.0 + 1e-10
? std::array<double, 5>{1.0, 0.0, 0.0, 0.0, 1.000}
: std::array<double, 5>{0.1, 0.0, 0.0, 0.0, 0.125};
}
};
struct cylindrical_explosion
{
inline std::array<double, 5> operator()(std::array<double, 2> X) const
{
auto x = X[0] - 0.5;
auto y = X[1] - 0.5;
return x * x + y * y < 0.05
? std::array<double, 5>{1.0, 0.0, 0.0, 0.0, 1.000}
: std::array<double, 5>{0.1, 0.0, 0.0, 0.0, 0.125};
}
};
struct gaussian_density
{
inline std::array<double, 5> operator()(std::array<double, 2> X) const
{
auto x = X[0] - 0.25;
auto y = X[1] - 0.25;
auto d = 1 + std::exp(-(x * x + y * y) / 0.01);
return std::array<double, 5>{d, 0.5, 0.5, 0.0, 1.000};
}
};
// ============================================================================
void write_database(const Database& database)
{
auto parts = std::vector<std::string>{"data", "chkpt.0000.bt"};
FileSystem::removeRecursively(FileSystem::joinPath(parts));
for (const auto& patch : database)
{
parts.push_back(to_string(patch.first));
FileSystem::ensureParentDirectoryExists(FileSystem::joinPath(parts));
nd::tofile(patch.second, FileSystem::joinPath(parts));
parts.pop_back();
}
std::cout << "Write checkpoint " << FileSystem::joinPath(parts) << std::endl;
}
// ============================================================================
struct run_config
{
void print(std::ostream& os) const;
static run_config from_dict(std::map<std::string, std::string> items);
static run_config from_argv(int argc, const char* argv[]);
std::string outdir = ".";
double tfinal = 0.1;
int rk = 1;
int ni = 100;
int nj = 100;
int num_levels = 1;
int threaded = 0;
};
VISITABLE_STRUCT(run_config,
outdir,
tfinal,
rk,
ni,
nj,
num_levels,
threaded);
// ============================================================================
run_config run_config::from_dict(std::map<std::string, std::string> items)
{
run_config cfg;
visit_struct::for_each(cfg, [items] (const char* name, auto& value)
{
if (items.find(name) != items.end())
{
cmdline::set_from_string(items.at(name), value);
}
});
return cfg;
}
run_config run_config::from_argv(int argc, const char* argv[])
{
return from_dict(cmdline::parse_keyval(argc, argv));
}
void run_config::print(std::ostream& os) const
{
using std::left;
using std::setw;
using std::setfill;
using std::showpos;
const int W = 24;
os << std::string(52, '=') << "\n";
os << "Config:\n\n";
std::ios orig(nullptr);
orig.copyfmt(os);
visit_struct::for_each(*this, [&os] (std::string name, auto& value)
{
os << left << setw(W) << setfill('.') << name + " " << " " << value << "\n";
});
os << "\n";
os.copyfmt(orig);
}
// ============================================================================
auto advance_2d(nd::array<double, 3> U0, double dt, double dx, double dy)
{
auto _ = nd::axis::all();
auto update_formula = [dt,dx,dy] (std::array<double, 5> arg)
{
double u = arg[0];
double fri = arg[1];
double fli = arg[2];
double frj = arg[3];
double flj = arg[4];
return u - (fri - fli) * dt / dx - (frj - flj) * dt / dy;
};
auto gradient_est = ufunc::from(gradient_plm(2.0));
auto advance_cons = ufunc::nfrom(update_formula);
auto cons_to_prim = ufunc::vfrom(newtonian_hydro::cons_to_prim());
auto godunov_flux_i = ufunc::vfrom(newtonian_hydro::riemann_hlle({1, 0, 0}));
auto godunov_flux_j = ufunc::vfrom(newtonian_hydro::riemann_hlle({0, 1, 0}));
auto extrap_l = ufunc::from([] (double a, double b) { return a - b * 0.5; });
auto extrap_r = ufunc::from([] (double a, double b) { return a + b * 0.5; });
auto mi = U0.shape(0);
auto mj = U0.shape(1);
auto P0 = cons_to_prim(U0);
auto Fhi = [&] ()
{
auto Pa = P0.select(_|0|mi-2, _|2|mj-2, _);
auto Pb = P0.select(_|1|mi-1, _|2|mj-2, _);
auto Pc = P0.select(_|2|mi-0, _|2|mj-2, _);
auto Gb = gradient_est(Pa, Pb, Pc);
auto Pl = extrap_l(Pb, Gb);
auto Pr = extrap_r(Pb, Gb);
auto Fh = godunov_flux_i(Pr.take<0>(_|0|mi-3), Pl.take<0>(_|1|mi-2));
return Fh;
}();
auto Fhj = [&] ()
{
auto Pa = P0.select(_|2|mi-2, _|0|mj-2, _);
auto Pb = P0.select(_|2|mi-2, _|1|mj-1, _);
auto Pc = P0.select(_|2|mi-2, _|2|mj-0, _);
auto Gb = gradient_est(Pa, Pb, Pc);
auto Pl = extrap_l(Pb, Gb);
auto Pr = extrap_r(Pb, Gb);
auto Fh = godunov_flux_j(Pr.take<1>(_|0|mj-3), Pl.take<1>(_|1|mj-2));
return Fh;
}();
return advance_cons(std::array<nd::array<double, 3>, 5>
{
U0 .select(_|2|mi-2, _|2|mj-2, _),
Fhi.take<0>(_|1|mi-3),
Fhi.take<0>(_|0|mi-4),
Fhj.take<1>(_|1|mj-3),
Fhj.take<1>(_|0|mj-4)
});
}
// ============================================================================
void update_2d_nothread(Database& database, double dt, double dx, double dy, double rk_factor)
{
auto results = std::map<Database::Index, Database::Array>();
for (const auto& patch : database.all(Field::conserved))
{
auto U = database.fetch(patch.first, 2);
auto p = std::get<2>(patch.first);
results[patch.first].become(advance_2d(U, dt, dx / (1 << p), dy / (1 << p)));
}
for (const auto& res : results)
{
database.commit(res.first, res.second, rk_factor);
}
}
void update_2d_threaded(Database& database, double dt, double dx, double dy, double rk_factor)
{
struct ThreadResult
{
Database::Index index;
nd::array<double, 3> U1;
};
auto threads = std::vector<std::thread>();
auto futures = std::vector<std::future<ThreadResult>>();
for (const auto& patch : database.all(Field::conserved))
{
auto U = database.fetch(patch.first, 2);
auto p = std::get<2>(patch.first);
auto promise = std::promise<ThreadResult>();
futures.push_back(promise.get_future());
threads.push_back(std::thread([index=patch.first,U,p,dt,dx,dy] (auto promise)
{
promise.set_value({index, advance_2d(U, dt, dx / (1 << p), dy / (1 << p))});
}, std::move(promise)));
}
for (auto& f : futures)
{
auto res = f.get();
database.commit(res.index, res.U1, rk_factor);
}
for (auto& t : threads)
{
t.join();
}
}
void update(Database& database, double dt, double dx, double dy, int rk, int threaded)
{
auto up = threaded ? update_2d_threaded : update_2d_nothread;
switch (rk)
{
case 1:
up(database, dt, dx, dy, 0.0);
break;
case 2:
up(database, dt, dx, dy, 0.0);
up(database, dt, dx, dy, 0.5);
break;
default:
throw std::invalid_argument("rk must be 1 or 2");
}
}
// ============================================================================
nd::array<double, 3> mesh_vertices(int ni, int nj, std::array<double, 4> extent)
{
auto X = nd::array<double, 3>(ni + 1, nj + 1, 2);
auto x0 = extent[0];
auto x1 = extent[1];
auto y0 = extent[2];
auto y1 = extent[3];
for (int i = 0; i < ni + 1; ++i)
{
for (int j = 0; j < nj + 1; ++j)
{
X(i, j, 0) = x0 + (x1 - x0) * i / ni;
X(i, j, 1) = y0 + (y1 - y0) * j / nj;
}
}
return X;
}
nd::array<double, 3> mesh_cell_coords(nd::array<double, 3> verts)
{
auto _ = nd::axis::all();
auto ni = verts.shape(0) - 1;
auto nj = verts.shape(1) - 1;
return (
verts.select(_|0|ni+0, _|0|nj+0, _) +
verts.select(_|0|ni+0, _|1|nj+1, _) +
verts.select(_|1|ni+1, _|0|nj+0, _) +
verts.select(_|1|ni+1, _|1|nj+1, _)) * 0.25;
}
// ============================================================================
Database build_database(int ni, int nj, int num_levels)
{
auto extent = [] (int i, int j, int level)
{
auto Ni = 3 * (1 << level);
auto Nj = 3 * (1 << level);
double x0 = double(i + 0) / Ni;
double x1 = double(i + 1) / Ni;
double y0 = double(j + 0) / Nj;
double y1 = double(j + 1) / Nj;
return std::array<double, 4>{x0, x1, y0, y1};
};
auto header = Database::Header
{
{Field::conserved, {5, MeshLocation::cell}},
{Field::cell_coords, {2, MeshLocation::cell}},
{Field::vert_coords, {2, MeshLocation::vert}},
};
auto database = Database(ni, nj, header);
auto initial_data = ufunc::vfrom(cylindrical_explosion()); // gaussian_density());
auto prim_to_cons = ufunc::vfrom(newtonian_hydro::prim_to_cons());
auto Ni = 3; // number of base blocks
auto Nj = 3;
for (int i = 0; i < Ni; ++i)
{
for (int j = 0; j < Nj; ++j)
{
if (num_levels == 1 || (i != 1 || j != 1))
{
auto x_verts = mesh_vertices(ni, nj, extent(i, j, 0));
auto x_cells = mesh_cell_coords(x_verts);
auto U = prim_to_cons(initial_data(x_cells));
database.insert(std::make_tuple(i, j, 0, Field::cell_coords), x_cells);
database.insert(std::make_tuple(i, j, 0, Field::vert_coords), x_verts);
database.insert(std::make_tuple(i, j, 0, Field::conserved), U);
}
}
}
for (int i = 0; i < Ni * 2; ++i)
{
for (int j = 0; j < Nj * 2; ++j)
{
if (num_levels == 2 && (i == 2 || i == 3) && (j == 2 || j == 3))
{
auto x_verts = mesh_vertices(ni, nj, extent(i, j, 1));
auto x_cells = mesh_cell_coords(x_verts);
auto U = prim_to_cons(initial_data(x_cells));
database.insert(std::make_tuple(i, j, 1, Field::cell_coords), x_cells);
database.insert(std::make_tuple(i, j, 1, Field::vert_coords), x_verts);
database.insert(std::make_tuple(i, j, 1, Field::conserved), U);
}
}
}
// [0 ] [1 ] [2 ]
// [0 1 ] [2 3 ] [4 5 ]
// [0 1 2 3] [4 5 6 7] [8 9 a b]
return database;
}
// ============================================================================
int main_2d(int argc, const char* argv[])
{
auto cfg = run_config::from_argv(argc, argv);
auto wall = 0.0;
auto ni = cfg.ni;
auto nj = cfg.nj;
auto iter = 0;
auto t = 0.0;
auto dx = 1.0 / ni;
auto dy = 1.0 / nj;
auto dt = std::min(dx, dy) * 0.125;
auto database = build_database(ni, nj, cfg.num_levels);
// ========================================================================
std::cout << "\n";
cfg.print(std::cout);
database.print(std::cout);
std::cout << std::string(52, '=') << "\n";
std::cout << "Main loop:\n\n";
// ========================================================================
// Main loop
// ========================================================================
while (t < cfg.tfinal)
{
auto timer = Timer();
update(database, dt, dx, dy, cfg.rk, cfg.threaded);
t += dt;
iter += 1;
wall += timer.seconds();
auto kzps = database.num_cells(Field::conserved) / 1e3 / timer.seconds();
std::printf("[%04d] t=%3.2lf kzps=%3.2lf\n", iter, t, kzps);
}
std::printf("average kzps=%f\n", database.num_cells(Field::conserved) / 1e3 / wall * iter);
write_database(database);
return 0;
}
// ============================================================================
int main(int argc, const char* argv[])
{
std::set_terminate(Debug::terminate_with_backtrace);
return main_2d(argc, argv);
}
<file_sep>#include <fstream>
#include <iostream>
#include <map>
// ============================================================================
namespace nd {
template<typename Writeable>
void tofile(const Writeable& writeable, const std::string& fname)
{
std::ofstream outfile(fname, std::ofstream::binary | std::ios::out);
if (! outfile.is_open())
{
throw std::invalid_argument("file " + fname + " could not be opened for writing");
}
auto s = writeable.dumps();
outfile.write(s.data(), s.size());
outfile.close();
}
}
// ============================================================================
template <class T, std::size_t N>
std::ostream& operator<<(std::ostream& o, const std::array<T, N>& arr)
{
std::copy(arr.cbegin(), arr.cend(), std::ostream_iterator<T>(o, " "));
return o;
}
// ============================================================================
namespace cmdline
{
std::map<std::string, std::string> parse_keyval(int argc, const char* argv[]);
template <typename T>
inline void set_from_string(std::string source, T& value);
template <>
inline void set_from_string<std::string>(std::string source, std::string& value)
{
value = source;
}
template <>
inline void set_from_string<int>(std::string source, int& value)
{
value = std::stoi(source);
}
template <>
inline void set_from_string<double>(std::string source, double& value)
{
value = std::stod(source);
}
}
// ============================================================================
class Timer
{
public:
Timer() : instantiated(std::clock())
{
}
double seconds() const
{
return double (std::clock() - instantiated) / CLOCKS_PER_SEC;
}
private:
std::clock_t instantiated;
};
// ============================================================================
class FileSystem
{
public:
static std::vector<std::string> splitPath(std::string pathName);
static std::string joinPath(std::vector<std::string> parts);
static std::string fileExtension(std::string pathName);
static std::string getParentDirectory(std::string pathName);
static void ensureDirectoryExists(std::string pathName);
static void ensureParentDirectoryExists(std::string dirName);
static int removeRecursively(std::string pathName);
static std::string makeFilename(
std::string directory,
std::string base,
std::string extension,
int number,
int rank=-1);
};
// ============================================================================
class Debug
{
public:
static void backtrace();
static void terminate_with_backtrace();
};
<file_sep># `binary-torques`
## A 2D hydro code for evolving circumbinary black hole accretion disks
<file_sep>#include <sstream>
#include <iomanip>
#include <vector>
#include <libunwind.h>
#include <cxxabi.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include "app_utils.hpp"
// ============================================================================
std::map<std::string, std::string> cmdline::parse_keyval(int argc, const char* argv[])
{
std::map<std::string, std::string> items;
for (int n = 0; n < argc; ++n)
{
std::string arg = argv[n];
std::string::size_type eq_index = arg.find('=');
if (eq_index != std::string::npos)
{
std::string key = arg.substr(0, eq_index);
std::string val = arg.substr(eq_index + 1);
items[key] = val;
}
}
return items;
}
// ============================================================================
std::vector<std::string> FileSystem::splitPath(std::string pathName)
{
auto remaining = pathName;
auto dirs = std::vector<std::string>();
while (true)
{
auto slash = remaining.find('/');
if (slash == std::string::npos)
{
dirs.push_back(remaining);
break;
}
dirs.push_back(remaining.substr(0, slash));
remaining = remaining.substr(slash + 1);
}
return dirs;
}
std::string FileSystem::joinPath(std::vector<std::string> parts)
{
auto res = std::string();
for (auto part : parts)
{
res += "/" + part;
}
return res.substr(1);
}
std::string FileSystem::fileExtension(std::string pathName)
{
auto dot = pathName.rfind('.');
if (dot != std::string::npos)
{
return pathName.substr(dot);
}
return "";
}
std::string FileSystem::getParentDirectory(std::string pathName)
{
std::string::size_type lastSlash = pathName.find_last_of("/");
return pathName.substr(0, lastSlash);
}
void FileSystem::ensureDirectoryExists(std::string dirName)
{
auto path = std::string(".");
for (auto dir : splitPath(dirName))
{
path += "/" + dir;
mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
}
}
void FileSystem::ensureParentDirectoryExists(std::string pathName)
{
std::string parentDir = getParentDirectory(pathName);
ensureDirectoryExists(parentDir);
}
int FileSystem::removeRecursively(std::string path)
{
/**
* Adapted from:
*
* https://stackoverflow.com/questions/2256945/removing-a-non-empty-directory-programmatically-in-c-or-c
*
* Uses methods:
* opendir, closedir, readdir, rmdir, unlink, stat, S_ISDIR
*
* Uses structs:
* dirent, statbuf
*
*/
int res = -1;
if (auto d = opendir(path.data()))
{
struct dirent *p;
res = 0;
while (! res && (p = readdir(d)))
{
if (! std::strcmp(p->d_name, ".") || ! std::strcmp(p->d_name, ".."))
{
continue;
}
int res2 = -1;
auto buf = std::string(path.size() + std::strlen(p->d_name) + 2, 0);
std::snprintf(&buf[0], buf.size(), "%s/%s", path.data(), p->d_name);
struct stat statbuf;
if (! stat(buf.data(), &statbuf))
{
if (S_ISDIR(statbuf.st_mode))
{
res2 = removeRecursively(buf.data());
}
else
{
res2 = unlink(buf.data());
}
}
res = res2;
}
closedir(d);
}
if (! res)
{
res = rmdir(path.data());
}
return res;
}
std::string FileSystem::makeFilename(
std::string directory,
std::string base,
std::string extension,
int number,
int rank)
{
std::stringstream filenameStream;
filenameStream << directory << "/" << base;
if (number >= 0)
{
filenameStream << "." << std::setfill('0') << std::setw(4) << number;
}
if (rank != -1)
{
filenameStream << "." << std::setfill('0') << std::setw(4) << rank;
}
filenameStream << extension;
return filenameStream.str();
}
// ============================================================================
void Debug::backtrace()
{
std::cout << std::string(52, '=') << std::endl;
std::cout << "Backtrace:\n";
std::cout << std::string(52, '=') << std::endl;
unw_cursor_t cursor;
unw_context_t context;
// Initialize cursor to current frame for local unwinding.
unw_getcontext(&context);
unw_init_local(&cursor, &context);
// Unwind frames one by one, going up the frame stack.
while (unw_step(&cursor) > 0)
{
unw_word_t offset, pc;
unw_get_reg(&cursor, UNW_REG_IP, &pc);
if (pc == 0)
{
break;
}
std::printf("0x%llx:", pc);
char sym[1024];
if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0)
{
int status;
char* nameptr = sym;
char* demangled = abi::__cxa_demangle(sym, nullptr, nullptr, &status);
if (status == 0)
{
nameptr = demangled;
}
std::printf("(%s+0x%llx)\n", nameptr, offset);
std::free(demangled);
}
else
{
std::printf(" -- error: unable to obtain symbol name for this frame\n");
}
}
}
void Debug::terminate_with_backtrace()
{
try {
auto e = std::current_exception();
if (e)
{
std::rethrow_exception(e);
}
}
catch(std::exception& e)
{
std::cout << std::string(52, '=') << std::endl;
std::cout << "Uncaught exception: "<< e.what() << std::endl;
}
backtrace();
exit(1);
}
<file_sep>#include <ostream>
#include "patches.hpp"
using namespace patches2d;
// ============================================================================
std::string patches2d::to_string(Database::Index index)
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
auto f = std::string();
switch (std::get<3>(index))
{
case Field::conserved: f = "conserved"; break;
case Field::cell_coords: f = "cell_coords"; break;
case Field::vert_coords: f = "vert_coords"; break;
}
return std::to_string(p) + ":" + std::to_string(i) + "-" + std::to_string(j) + "/" + f;
}
// ============================================================================
FieldDescriptor::FieldDescriptor(int num_fields, MeshLocation location)
: num_fields(num_fields)
, location(location)
{
}
// ============================================================================
Database::Database(int ni, int nj, Header header)
: ni(ni)
, nj(nj)
, header(header)
{
}
void Database::insert(Index index, Array data)
{
patches[index].become(check_shape(data, index).copy());
}
auto Database::erase(Index index)
{
return patches.erase(index);
}
void Database::commit(Index index, Array data, double rk_factor)
{
if (location(index) != MeshLocation::cell)
{
throw std::invalid_argument("Can only commit cell data (for now)");
}
auto target = patches.at(index);
if (rk_factor == 0.0)
{
target = data;
}
else
{
target = data * (1 - rk_factor) + target * rk_factor;
}
}
Database::Array Database::fetch(Index index, int guard) const
{
if (location(index) != MeshLocation::cell)
{
throw std::invalid_argument("Can only fetch cell data (for now)");
}
auto _ = nd::axis::all();
auto ng = guard;
auto shape = std::array<int, 3>{ni + 2 * ng, nj + 2 * ng, 5};
auto res = nd::array<double, 3>(shape);
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
auto f = std::get<3>(index);
auto Ri = std::make_tuple(i + 1, j, p, f);
auto Li = std::make_tuple(i - 1, j, p, f);
auto Rj = std::make_tuple(i, j + 1, p, f);
auto Lj = std::make_tuple(i, j - 1, p, f);
res.select(_|ng|ni+ng, _|ng|nj+ng, _) = patches.at(index);
res.select(_|ni+ng|ni+2*ng, _|ng|nj+ng, _) = locate(Ri).select(_|0|ng, _, _);
res.select(_|ng|ni+ng, _|nj+ng|nj+2*ng, _) = locate(Rj).select(_, _|0|ng, _);
res.select(_|0|ng, _|ng|nj+ng, _) = locate(Li).select(_|ni-ng|ni, _, _);
res.select(_|ng|ni+ng, _|0|ng, _) = locate(Lj).select(_, _|nj-ng|nj, _);
return res;
}
std::map<Database::Index, Database::Array> Database::all(Field which) const
{
auto res = std::map<Index, Array>();
for (const auto& patch : patches)
{
if (std::get<3>(patch.first) == which)
{
res.insert(patch);
}
}
return res;
}
std::size_t Database::count(Field which) const
{
std::size_t n = 0;
for (const auto& patch : patches)
{
if (std::get<3>(patch.first) == which)
{
++n;
}
}
return n;
}
std::size_t Database::num_cells(Field which) const
{
return count(which) * ni * nj;
}
void Database::print(std::ostream& os) const
{
os << std::string(52, '=') << "\n";
os << "Mesh patches:\n\n";
for (const auto& patch : patches)
{
os << to_string(patch.first) << "\n";
}
os << "\n";
}
// ========================================================================
int Database::num_fields(Index index) const
{
return header.at(std::get<3>(index)).num_fields;
}
MeshLocation Database::location(Index index) const
{
return header.at(std::get<3>(index)).location;
}
Database::Array Database::check_shape(Array& array, Index index) const
{
if (array.shape() != expected_shape(index))
{
throw std::invalid_argument("input patch data has the wrong shape");
}
return array;
}
Database::Index Database::coarsen(Index index) const
{
std::get<0>(index) /= 2;
std::get<1>(index) /= 2;
std::get<2>(index) -= 1;
return index;
}
std::array<Database::Index, 4> Database::refine(Index index) const
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
auto f = std::get<3>(index);
return {
std::make_tuple(i * 2 + 0, j * 2 + 0, p + 1, f),
std::make_tuple(i * 2 + 0, j * 2 + 1, p + 1, f),
std::make_tuple(i * 2 + 1, j * 2 + 0, p + 1, f),
std::make_tuple(i * 2 + 1, j * 2 + 1, p + 1, f),
};
}
std::array<int, 3> Database::expected_shape(Index index) const
{
switch (location(index))
{
case MeshLocation::cell: return {ni + 0, nj + 0, num_fields(index)};
case MeshLocation::vert: return {ni + 1, nj + 1, num_fields(index)};
}
}
nd::array<double, 3> Database::locate(Index index) const
{
if (patches.count(index))
{
return patches.at(index);
}
if (patches.count(coarsen(index)))
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
return prolongation(quadrant(patches.at(coarsen(index)), i % 2, j % 2));
}
if (contains_all(refine(index)))
{
return restriction(tile(refine(index)));
}
// Return a value based on some physical boundary conditions
auto _ = nd::axis::all();
auto res = nd::array<double, 3>(ni, nj, num_fields(index));
res.select(_, _, 0) = 0.1;
res.select(_, _, 1) = 0.0;
res.select(_, _, 2) = 0.0;
res.select(_, _, 3) = 0.0;
res.select(_, _, 4) = 0.125;
return res;
}
nd::array<double, 3> Database::quadrant(const nd::array<double, 3>& A, int I, int J) const
{
auto _ = nd::axis::all();
if (I == 0 && J == 0) return A.select(_|0 |ni/2, _|0 |nj/2, _);
if (I == 0 && J == 1) return A.select(_|0 |ni/2, _|nj/2|nj, _);
if (I == 1 && J == 0) return A.select(_|ni/2|ni, _|0 |nj/2, _);
if (I == 1 && J == 1) return A.select(_|ni/2|ni, _|nj/2|nj, _);
throw std::invalid_argument("quadrant: I and J must be 0 or 1");
}
nd::array<double, 3> Database::tile(std::array<Index, 4> indexes) const
{
auto _ = nd::axis::all();
nd::array<double, 3> res(ni * 2, nj * 2, num_fields(indexes[0]));
res.select(_|0 |ni*1, _|0 |nj*1, _) = patches.at(indexes[0]);
res.select(_|0 |ni*1, _|nj|nj*2, _) = patches.at(indexes[1]);
res.select(_|ni|ni*2, _|0 |nj*1, _) = patches.at(indexes[2]);
res.select(_|ni|ni*2, _|nj|nj*2, _) = patches.at(indexes[3]);
return res;
}
nd::array<double, 3> Database::prolongation(const nd::array<double, 3>& A) const
{
auto _ = nd::axis::all();
nd::array<double, 3> res(ni, nj, A.shape(2));
res.select(_|0|ni|2, _|0|nj|2, _) = A;
res.select(_|0|ni|2, _|1|nj|2, _) = A;
res.select(_|1|ni|2, _|0|nj|2, _) = A;
res.select(_|1|ni|2, _|1|nj|2, _) = A;
return res;
}
nd::array<double, 3> Database::restriction(const nd::array<double, 3>& A) const
{
auto _ = nd::axis::all();
auto mi = A.shape(0);
auto mj = A.shape(1);
auto B = std::array<nd::array<double, 3>, 4>
{
A.select(_|0|mi|2, _|0|mj|2, _),
A.select(_|0|mi|2, _|1|mj|2, _),
A.select(_|1|mi|2, _|0|mj|2, _),
A.select(_|1|mi|2, _|1|mj|2, _),
};
return (B[0] + B[1] + B[2] + B[3]) * 0.25;
}
<file_sep>#pragma once
#include <cmath>
// ============================================================================
namespace newtonian_hydro {
// Indexes to primitive quanitites P
enum {
RHO = 0,
V11 = 1,
V22 = 2,
V33 = 3,
PRE = 4,
};
// Indexes to conserved quanitites U
enum {
DDD = 0,
S11 = 1,
S22 = 2,
S33 = 3,
NRG = 4,
};
using Vars = std::array<double, 5>;
using Unit = std::array<double, 3>;
struct cons_to_prim;
struct prim_to_cons;
struct prim_to_flux;
struct prim_to_eval;
struct riemann_hlle;
}
// ============================================================================
struct newtonian_hydro::cons_to_prim
{
inline Vars operator()(Vars U) const
{
const double gm1 = gammaLawIndex - 1.0;
const double pp = U[S11] * U[S11] + U[S22] * U[S22] + U[S33] * U[S33];
auto P = Vars();
P[RHO] = U[DDD];
P[PRE] = (U[NRG] - 0.5 * pp / U[DDD]) * gm1;
P[V11] = U[S11] / U[DDD];
P[V22] = U[S22] / U[DDD];
P[V33] = U[S33] / U[DDD];
return P;
}
double gammaLawIndex = 5. / 3;
};
// ============================================================================
struct newtonian_hydro::prim_to_cons
{
inline Vars operator()(Vars P) const
{
const double gm1 = gammaLawIndex - 1.0;
const double vv = P[V11] * P[V11] + P[V22] * P[V22] + P[V33] * P[V33];
auto U = Vars();
U[DDD] = P[RHO];
U[S11] = P[RHO] * P[V11];
U[S22] = P[RHO] * P[V22];
U[S33] = P[RHO] * P[V33];
U[NRG] = P[RHO] * 0.5 * vv + P[PRE] / gm1;
return U;
}
double gammaLawIndex = 5. / 3;
};
// ============================================================================
struct newtonian_hydro::prim_to_flux
{
inline Vars operator()(Vars P, Unit N) const
{
const double vn = P[V11] * N[0] + P[V22] * N[1] + P[V33] * N[2];
auto U = prim_to_cons()(P);
auto F = Vars();
F[DDD] = vn * U[DDD];
F[S11] = vn * U[S11] + P[PRE] * N[0];
F[S22] = vn * U[S22] + P[PRE] * N[1];
F[S33] = vn * U[S33] + P[PRE] * N[2];
F[NRG] = vn * U[NRG] + P[PRE] * vn;
return F;
}
double gammaLawIndex = 5. / 3;
};
// ============================================================================
struct newtonian_hydro::prim_to_eval
{
inline Vars operator()(Vars P, Unit N) const
{
const double gm0 = gammaLawIndex;
const double cs = std::sqrt(gm0 * P[PRE] / P[RHO]);
const double vn = P[V11] * N[0] + P[V22] * N[1] + P[V33] * N[2];
auto A = Vars();
A[0] = vn - cs;
A[1] = vn;
A[2] = vn;
A[3] = vn;
A[4] = vn + cs;
return A;
}
double gammaLawIndex = 5. / 3;
};
// ============================================================================
struct newtonian_hydro::riemann_hlle
{
riemann_hlle(Unit nhat) : nhat(nhat) {}
inline Vars operator()(Vars Pl, Vars Pr) const
{
auto Ul = p2c(Pl);
auto Ur = p2c(Pr);
auto Al = p2a(Pl, nhat);
auto Ar = p2a(Pr, nhat);
auto Fl = p2f(Pl, nhat);
auto Fr = p2f(Pr, nhat);
const double epl = *std::max_element(Al.begin(), Al.end());
const double eml = *std::min_element(Al.begin(), Al.end());
const double epr = *std::max_element(Ar.begin(), Ar.end());
const double emr = *std::min_element(Ar.begin(), Ar.end());
const double ap = std::max(0.0, std::max(epl, epr));
const double am = std::min(0.0, std::min(eml, emr));
Vars U, F;
for (int q = 0; q < 5; ++q)
{
U[q] = (ap * Ur[q] - am * Ul[q] + (Fl[q] - Fr[q])) / (ap - am);
F[q] = (ap * Fl[q] - am * Fr[q] - (Ul[q] - Ur[q]) * ap * am) / (ap - am);
}
return F;
}
Unit nhat;
prim_to_cons p2c;
prim_to_eval p2a;
prim_to_flux p2f;
};
<file_sep>-include Makefile.in
CXXFLAGS = -std=c++14 -Wall -Wextra -Wno-missing-braces -O3
THIRD_P = src/visit_struct.hpp src/ndarray.hpp
HEADERS = $(filter-out $(THIRD_P), $(wildcard src/*.hpp))
SOURCES = $(wildcard src/*.cpp)
OBJECTS = $(SOURCES:.cpp=.o)
default: bt
src/main.o: $(HEADERS) $(THIRD_P)
src/app_utils.o: src/app_utils.hpp
bt: $(OBJECTS)
$(CXX) -o $@ $^
src/visit_struct.hpp: third_party/visit_struct/include/visit_struct/visit_struct.hpp
cp $< $@
src/ndarray.hpp: third_party/ndarray/include/ndarray.hpp
cp $< $@
clean:
$(RM) src/*.o bt
| c318dfa7b39b63ff0f7a0d0c22681154020f7203 | [
"Markdown",
"Makefile",
"C++"
] | 8 | C++ | jzrake/binary-torques | 22ef80108e6559e4ca781d7205f75a370da49580 | 128098209fac67393efe2230e8421f08faa503cf |
refs/heads/master | <repo_name>ianatha/morsidium<file_sep>/Frameworks/AIUtilities.framework/Versions/A/Headers/AIFunctions.h
/*-------------------------------------------------------------------------------------------------------*\
| Adium, Copyright (C) 2001-2005, <NAME> (<EMAIL> | http://www.adiumx.com) |
\---------------------------------------------------------------------------------------------------------/
| This program is free software; you can redistribute it and/or modify it under the terms of the GNU
| General Public License as published by the Free Software Foundation; either version 2 of the License,
| or (at your option) any later version.
|
| This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
| the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
| Public License for more details.
|
| You should have received a copy of the 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.
\------------------------------------------------------------------------------------------------------ */
/*! @brief Obtains the high and low surrogate for a Unicode code-point.
*
* If \a in is lower than U+10FFF (which means it would not require surrogates to construct), \c *outHigh will be 0, and \c *outLow will be \a in.
*
* @return The high and low surrogate (if applicable), or 0 and the input character.
*/
BOOL AIGetSurrogates(UTF32Char in, UTF16Char *outHigh, UTF16Char *outLow);
#pragma mark Wired memory
/*! @defgroup AIWiredMemory Wired memory
*
* Functions for allocating and handling wired memory.
*/
/*@{*/
/*! @brief Clobbers a region of memory with gibberish.
*
* Use this to sanitize memory that you don't want to be viewed in the future. For example, if you had a password in this memory, you would clobber it using this function so that the password cannot be peeked later.
*/
void AIWipeMemory(void *buf, size_t len);
/*! @brief Allocate or resize a region of wired memory.
*
* AIReallocWired is for use with wired memory. It returns a block that is already wired in core memory.
* Before freeing the old block, it wipes (see AIWipeMemory) and unlocks it.
*
* If the new block could not be allocated or wired, the old block is still valid, wired, and unchanged.
* All other aspects of its behaviour are the same as \c realloc(3) (for example, \c realloc(NULL, x) == \c malloc(x)).
* When you are done with the memory, call \c munlock on it, followed by \c free.
*
* @return The new region of memory, or \c NULL if one could not be created and wired.
*/
void *AIReallocWired(void *oldBuf, size_t newLen);
/*! @brief Sets every byte in \a buf within \a range to \a ch.
* Qux.
*/
void AISetRangeInMemory(void *buf, NSRange range, int ch);
/*@}*/
#pragma mark Rect utilities
/*! @defgroup AIRectUtilities Rectangle utilities
*
* Functions for managing the placement and alignment of rectangles relative to other rectangles.
*/
/*@{*/
/*! @enum AIRectEdgeMask
* A bit mask of zero or more edges of a rectangle.
*/
typedef enum AIRectEdgeMask {
//!No edges.
AINoEdges = 0,
//!Far right.
AIMaxXEdgeMask = (1 << NSMaxXEdge),
//!Top.
AIMaxYEdgeMask = (1 << NSMaxYEdge),
//!Far left.
AIMinXEdgeMask = (1 << NSMinXEdge),
//!Bottom.
AIMinYEdgeMask = (1 << NSMinYEdge)
} AIRectEdgeMask;
enum {
//!This value in an NSRectEdge variable indicates no edge.
AINotARectEdge = -1
};
/*! @brief Returns the coordinate for an edge of a rectangle.
*
* For example, AICoordinateForRect_edge_(rect, NSMaxXEdge) is the same as NSMaxX(rect).
*
* @return An X or Y coordinate.
*/
float AICoordinateForRect_edge_(NSRect rect, NSRectEdge edge);
/*! @brief Measures a line from \a edge to \a point.
*
* Returns the distance that \a point lies outside of \a rect on a particular side (\a edge).
* If the point lies on the interior side of that edge, the number returned will be negative, even if the point is outside the rectangle itself.
* For example, if \c rect.origin.x is 50, and \c rect.size.width is 50, and \c point.x is 25, and \a edge is \c NSMaxXEdge, the result will be -75.0f.
*
* @return The distance between the edge and the point. It is positive if the point is outside the edge, negative if it is inside the edge (even it is outside the rectangle).
*/
float AISignedExteriorDistanceRect_edge_toPoint_(NSRect rect, NSRectEdge edge, NSPoint point);
/*! @brief Returns the edge that would be across a rectangle from \a edge.
*
* For example, AIOppositeRectEdge_(NSMaxXEdge) is NSMinXEdge.
*
* @return An edge.
*/
NSRectEdge AIOppositeRectEdge_(NSRectEdge edge);
// translate mobileRect so that it aligns with stationaryRect
// undefined if aligning left to top or something else that does not make sense
NSRect AIRectByAligningRect_edge_toRect_edge_(NSRect mobileRect,
NSRectEdge mobileRectEdge,
NSRect stationaryRect,
NSRectEdge stationaryRectEdge);
/*! @brief Returns whether \a edge1 of \a rect1 is within \a tolerance units of \a edge2 of \a rect2.
* @return \c YES if the distance between the two edges is less than \a tolerance; \c NO if not.
*/
BOOL AIRectIsAligned_edge_toRect_edge_tolerance_(NSRect rect1,
NSRectEdge edge1,
NSRect rect2,
NSRectEdge edge2,
float tolerance);
// minimally translate mobileRect so that it lies within stationaryRect
NSRect AIRectByMovingRect_intoRect_(NSRect mobileRect, NSRect stationaryRect);
/*@}*/
<file_sep>/Frameworks/Adium.framework/Versions/A/Headers/ESDebugAILog.h
/*
* Adium is the legal property of its developers, whose names are listed in the copyright file included
* with this source distribution.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the 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.
*/
#ifdef DEBUG_BUILD
/* For a debug build, declare the AILog() function */
void AILogWithPrefix (const char *signature, NSString *format, ...);
#define AILogWithSignature(fmt, args...) AILogWithPrefix(__PRETTY_FUNCTION__, fmt, ##args);
void AILog (NSString *format, ...);
#else
/* For a non-debug build, define it to be a comment so there is no overhead in using it liberally */
#define AILog(fmt, ...) /**/
#define AILogWithSignature(fmt, ...) /**/
#define AILogWithPrefix(sig, fmt, ...) /**/
#endif
| 60bf991c7fa9baae612ef18c78ae9b5de2663c41 | [
"C"
] | 2 | C | ianatha/morsidium | f5ba0732fb2173b0b86afaad021919d3ecdf296f | c4e9d88bcfb20e31b64596b6479c1ae89a775d03 |
refs/heads/main | <repo_name>Stevens-DSC/storemeta-pull<file_sep>/parse/shopify.js
const { log, warn, test, okay, fail } = require('../utils/logger')
const fetch = require('node-fetch')
const delay = require('../utils/delay')
const xml = require("xml-parse")
const { Parser } = require('htmlparser2')
const { Handler } = require('htmlmetaparser')
async function parse(store, HOST_URL) {
const { shortname, homepage } = store
const homeURL = store['store-home']
const productLinks = await getAllProductLinks(homeURL)
okay("Loaded ", productLinks.length, " product links")
let payload = []
const rs = await Promise.allSettled(productLinks.map(link => getProductMeta(homeURL, link, shortname)))
for (let r of rs) {
// console.log(link)
if(r.status == 'fulfilled') {
payload.push(r.value)
} else {
fail("Failed loading product link ")
fail(JSON.stringify(r))
}
}
// payload = payload.map()
payload.forEach(a=> a.seller=shortname )
okay("Successfully loaded ", payload.length, " product meta into memory")
return payload
}
function parseMicrocode(html, url) {
return new Promise((resolve, reject) => {
const handler = new Handler((err, result) => {
if(err)
return reject(err)
resolve(result)
}, { url });
const parser = new Parser(handler, { decodeEntities: true });
parser.write(html);
parser.done();
})
}
function getDesc(microdata) {
try {
return microdata[1].offers[0].description[0]
}catch(e) {}
try {
return microdata[1].description[0]
}catch(e) {}
return ""
}
async function getProductMeta(homeURL, productURL, storename) {
// console.log("query " + productURL)
const req = await fetch(productURL)
const rawHTML = await req.text()
const parsed = await parseMicrocode(rawHTML, productURL)
// console.log(parsed)
let { rdfa, microdata } = parsed
try {
// console.log(microdata)
const builder = {
description: getDesc(microdata),
displayname: rdfa[0]['og:title'][0],
tags: [],
image: rdfa[0]['og:image:secure_url'][0],
price: parseFloat(rdfa[0]['og:price:amount']),
currency: rdfa[0]['og:price:currency'][0],
url: rdfa[0]['og:url'][0] || productURL,
shortcode: storename + '-' + productURL.substring(homeURL.length).split('/').reverse()[0]
}
// console.log(builder)
// process.exit(0)
return builder
}catch(e) {
console.log(e)
}
return {}
}
let done = 0
let wait = time => new Promise((r,rj)=> setTimeout(r,time))
async function getAllProductLinks(homeURL) {
done++
if(done > 20) {
console.log("Breathing for 200ms...")
await wait(time)
done = 0
}
const req = await fetch(homeURL + '/sitemap.xml')
const rawXML = await req.text()
let obj = xml.parse(rawXML)
.filter(a => a.tagName == "sitemapindex")[0].childNodes
.filter(a => a.tagName == "sitemap")
.map(a =>
a.childNodes
.filter(b => b.tagName == "loc")
.map(c => c.childNodes)[0][0]
).map(a => a.text)
.filter(a => a.includes("products"))
let productLinkCollection = []
for (let sitemapLink of obj) {
productLinkCollection = [...productLinkCollection, ...await parseSitemap(homeURL, sitemapLink)]
}
return productLinkCollection
}
async function parseSitemap(homeURL, sitemapLink) {
const req = await fetch(sitemapLink)
const rawXML = await req.text()
let obj = rawXML.split('\n').map(a => a.trim()).filter(a => a.startsWith('<loc>')).map(a => a.replace('<loc>', '').replace('</loc>', ''))
obj = obj.filter(a => shouldDiscard(homeURL, a))
return obj
}
function shouldDiscard(homeURL, link) {
if (link.endsWith("/") && !homeURL.endsWith('/'))
homeURL += '/'
return homeURL != link
}
module.exports = parse<file_sep>/run.sh
#!/bin/bash
git stash
git pull
npm i
node index.js<file_sep>/parse/little-city-custom.js
const { log, warn, test, okay, fail } = require('../utils/logger')
const fetch = require('node-fetch')
const striptags = require("striptags")
const delay = require('../utils/delay')
const xml = require("xml-parse")
const { Parser } = require('htmlparser2')
const { Handler } = require('htmlmetaparser')
var DomParser = require('dom-parser')
const jsdom = require("jsdom")
const { JSDOM } = jsdom
var parser = new DomParser()
async function parse(store, HOST_URL) {
const { shortname, homepage } = store
const homeURL = store['store-home']
const productLinks = await getAllProductLinks(homeURL)
okay("Loaded ", productLinks.length, " product links")
let payload = []
for (let link of productLinks) {
try {
payload.push(await getProductMeta(homeURL, link, shortname))
} catch (e) {
fail("Failed loading product link ", link)
fail(e)
}
}
payload.forEach(a=> a.seller=shortname )
okay("Successfully loaded ", payload.length, " product meta into memory")
return payload
}
async function getProductMeta(homeURL, productURL, storename) {
const p = await fetch(productURL)
const rawHTML = await p.text()
const { document } = (new JSDOM(rawHTML)).window
let b = {
description: striptags(document.getElementsByClassName('abaproduct-body')[0].innerHTML).replace('Description', '').trim(),
displayname: document.getElementsByClassName('page-title')[0].innerHTML,
tags: striptags(Object.values(document.getElementsByClassName('abaproduct-related-editions'))
.filter(a=>striptags(a.innerHTML).includes("Categories"))[0].innerHTML).split('Categories')[1].trim().split('\n'),
image: Object.values(document.getElementsByTagName('img')).filter(a=>a.src.includes("booksense"))[0].src,
price: parseFloat(document.getElementsByClassName('abaproduct-price')[0].innerHTML.trim().substring(1)),
currency: 'USD',
url: productURL,
shortcode: storename + '-' + striptags(document.getElementById('aba-product-details-fieldset').innerHTML).split(': ')[1].split('\n')[0], //isbn
seller: storename
}
return b
}
async function getAllProductLinks(homeURL) {
// take first 10 pages
let fetches = []
for(let i = 0; i < 10; i++) {
const link = `https://www.littlecitybooks.com/browse/book?page=${i}`
const promise = fetch(link)
fetches.push(promise)
}
fetches = await Promise.all(fetches)
let a = []
for(let prom of fetches) {
try {
let rawHTML = await prom.text()
const { document } = (new JSDOM(rawHTML)).window
let links = Object.values(document.getElementsByTagName('a')).map(a=>a.href).filter(a=>(a + "").startsWith('/book/'))
for(let link of links) {
if(!(link || "").includes("littlecitybooks.com")) {
link = "https://www.littlecitybooks.com" + link
}
a.push(link)
}
}catch(e) {
throw("Could not load product link")
}
}
return a
}
function shouldDiscard(homeURL, link) {
if (link.endsWith("/") && !homeURL.endsWith('/'))
homeURL += '/'
return homeURL != link
}
module.exports = parse<file_sep>/index.js
const { log, warn, test, okay, fail } = require('./utils/logger')
const unix = Date.now()
let success = 0
let total = -1
const fetchAllStores = require('./utils/fetchAllStores')
const fetch = require('node-fetch')
require('dotenv').config()
if(!process.env.HOST_URL) {
process.env.HOST_URL = "https://us-central1-dsc-marketplace.cloudfunctions.net"
}
const {HOST_URL} = process.env
okay("Using host URL ", HOST_URL)
let only = false
let ONLY_DO = ""
if(process.env.ONLY_DO) {
only = true
ONLY_DO = process.env.ONLY_DO
console.log("ONLY DOING " + ONLY_DO)
}
const parser = require('./parse/parser')
async function _() {
log("Timestamp: ", unix, " / ", new Date(unix).toGMTString())
log("Evaluating environment variables...")
if(!process.env.KEY) {
throw("You must use a KEY environment variable (or with .env file) to connect to server.")
}
okay("Read authentication key")
let allStores = await fetchAllStores(HOST_URL)
if(only)
allStores = allStores.filter(a=>a.shortname == ONLY_DO)
okay("Fetched ", allStores.length, " stores from server!")
total = allStores.length
let promises = []
let payload = []
let values = await Promise.allSettled(allStores.map(runStore))
for(let v of values) {
let { status } = v
if(status == "rejected") {
fail("Failed fetching product: " + v.reason)
continue;
}
let { value } = v
for(let a of value)
payload.push(a)
success++
}
const build = JSON.stringify({
key: process.env.KEY,
payload
})
const rawResponse = await fetch(HOST_URL + '/cronpayload', {
method: 'POST',
headers: {
},
body: build
})
log(await rawResponse.text())
}
async function runStore(store) {
try {
log("Updating products for ", (store.shortname || "???"))
const type = store['store-type']
log("Has store-type ", type)
if(!parser[type]) {
throw("No parser found for store type.")
}
okay("Queued products for ", (store.shortname || "???"))
let a = await (parser[type](store, HOST_URL))
return a
} catch(e) {
fail("Failed queueing products ", (store.shortname || "???"))
fail(e)
console.log(e)
}
}
_().then(result => {
log("Done.")
log(`${success}/${total} (${Math.round(success/total*100)}%) succeded`)
process.exit(0)
}).catch(error => {
fail(error)
log("0/0 (0%) succeded")
process.exit(-1)
}) | ae2e6a1cb3d2f8616056b8df40630a6311d34ea0 | [
"JavaScript",
"Shell"
] | 4 | JavaScript | Stevens-DSC/storemeta-pull | a5d696156a472674d86477e19cc9b7a16004eb2a | f2ab1278ff1364e60d141f9481a04fb71ad0e772 |
refs/heads/main | <file_sep><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
id="svg111"
width="400"
height="388"
viewBox="0 0 400 388"
sodipodi:docname="sd.svg"
inkscape:version="1.0.1 (3bc2e813f5, 2020-09-07)">
<metadata
id="metadata117">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs115" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="739"
inkscape:window-height="480"
id="namedview113"
showgrid="false"
inkscape:zoom="1.3865979"
inkscape:cx="200"
inkscape:cy="251.69517"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="0"
inkscape:current-layer="g119" />
<g
inkscape:groupmode="layer"
inkscape:label="Image"
id="g119">
<image
width="400"
height="388"
preserveAspectRatio="none"
xlink:href="data:image/jpeg;base64,/9j/4AAQSkZ<KEY>4
Arn<KEY>
<KEY>
"
id="image121"
x="0"
y="0" />
</g>
</svg>
<file_sep><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Gallego SVG</title>
</head>
<body>
<svg viewBox="0 -3 30 30" preserveAspectRatio="none" style="margin: 0 auto;border: none;">
<rect x= "10" y = "10" r = "5" r= "5" width = "10" height = "10" rx="2" fill="white"strokewidth="1" stroke="white"/>
<rect x= "15" y = "15" r = "5" r= "5" width = "10" height = "10" rx="2" fill="none"strokewidth="1" stroke="white"/>
</svg>
</body>
</html>
<file_sep><html>
<head>
<title> Junsay Canvas </title>
</head>
<script>
window.onload=function() {
var canvas=document.getElementById("canvas1");
var ctx=canvas.getContext('2d');
var canvas=document.getElementById("canvas2");
var context_2=canvas.getContext('2d');
var canvas = document.getElementById("canvas3");
var smileCtx = canvas.getContext("2d");
var radgrad = smileCtx.createRadialGradient(100,100,10,100,100,100);
var canvas = document.getElementById("canvas4");
var ctx4 = canvas.getContext("2d");
var canvas = document.getElementById("canvas5");
var context_3 = canvas.getContext("2d");
var canvas = document.getElementById("canvas6");
var ctx6 = canvas.getContext("2d");
var canvas = document.getElementById("canvas7");
var ctx7 = canvas.getContext("2d");
var canvas = document.getElementById("canvas8");
var context_1 = canvas.getContext("2d");
ctx.fillStyle = '#0065BD';
ctx.fillRect(0, 0, 200, 200);
ctx.beginPath();
ctx.lineWidth = "15";
ctx.strokeStyle = "white";
ctx.moveTo(0, 0);
ctx.lineTo(100, 110);
ctx.moveTo(200, 0);
ctx.lineTo(100, 100);
ctx.stroke();
context_2.beginPath();
context_2.rect(10, 30, 90, 50);
context_2.lineWidth = "6";
context_2.stroke();
context_2.beginPath();
context_2.fillRect(20, 70, 70, 30);
context_2.fillStyle = "#FF0000";
context_2.beginPath();
context_2.rect(30, 6, 50, 20);
context_2.lineWidth = "3";
context_2.stroke();
context_2.beginPath();
context_2.rect(35, 11, 40, 1);
context_2.lineWidth = "1";
context_2.stroke();
context_2.beginPath();
context_2.rect(35, 15, 40, 1);
context_2.lineWidth = "1";
context_2.stroke();
context_2.beginPath();
context_2.rect(35, 19, 40, 1);
context_2.lineWidth = "1";
context_2.stroke();
radgrad.addColorStop(.5, 'rgba(247,241,192,1)');
radgrad.addColorStop(1, 'rgba(244,225,56,1)');
smileCtx.beginPath();
smileCtx.fillStyle = radgrad;
smileCtx.arc(100,100,99,0,Math.PI*2);
smileCtx.stroke();
smileCtx.fill();
smileCtx.beginPath();
smileCtx.moveTo(170,100);
smileCtx.arc(100,100,70,0,Math.PI);
smileCtx.stroke();
smileCtx.beginPath();
smileCtx.fillStyle = 'black';
smileCtx.moveTo(60, 65);
smileCtx.arc(60,65,12,0,Math.PI*2);
smileCtx.fill();
smileCtx.beginPath();
smileCtx.moveTo(140,65);
smileCtx.arc(140,65,12,0,Math.PI*2);
smileCtx.fill();
ctx4.fillStyle = 'white';
ctx4.fillRect(90,30,30,120);
ctx4.fillStyle = 'white';
ctx4.fillRect(50,75,110,30);
context_3.beginPath();
context_3.rect(10, 20, 80, 10);
context_3.lineWidth = "6";
context_3.stroke();
context_3.beginPath();
context_3.fillRect(37.5, 2, 25, 15);
context_3.fillStyle = "#FF0000";
context_3.beginPath();
context_3.rect(10, 37, 80, 70);
context_3.lineWidth = "5";
context_3.stroke();
context_3.beginPath();
context_3.rect(30, 50, 1, 40);
context_3.lineWidth = "1";
context_3.stroke();
context_3.beginPath();
context_3.rect(50, 50, 1, 40);
context_3.lineWidth = "1";
context_3.stroke();
context_3.beginPath();
context_3.rect(70, 50, 1, 40);
context_3.lineWidth = "1";
context_3.stroke();
ctx6.strokeStyle = "green";
ctx6.lineWidth = 4;
ctx6.strokeRect(90, 50, 100, 90);
ctx6.fillStyle = "red";
ctx6.fillRect(30, 30, 120, 120);
ctx6.fillStyle = "orange";
ctx6.beginPath();
ctx6.arc(90, 90, 55, 0, 2 * Math.PI);
ctx6.fill();
ctx7.beginPath();
ctx7.arc(100, 100, 100, 0, 2 * Math.PI, false);
ctx7.closePath();
ctx7.fillStyle = "rgb(255, 0, 0)";
ctx7.stroke();
ctx7.fill();
ctx7.beginPath();
ctx7.arc(100, 100, 20, 0, 2 * Math.PI, false);
ctx7.closePath();
ctx7.fillStyle = "rgb(255, 255, 255)";
ctx7.stroke();
ctx7.fill();
ctx7.beginPath();
ctx7.arc(100, 100, 4, 0, 2 * Math.PI, false);
ctx7.closePath();
ctx7.fillStyle = "rgb(0, 0, 255)";
ctx7.stroke();
ctx7.fill();
ctx7.beginPath();
ctx7.arc(160, 100, 20, 0, 2 * Math.PI, false);
ctx7.closePath();
ctx7.fillStyle = "rgb(255, 255, 255)";
ctx7.stroke();
ctx7.fill();
ctx7.beginPath();
ctx7.arc(160, 100, 4, 0, 2 * Math.PI, false);
ctx7.closePath();
ctx7.fillStyle = "rgb(0, 0, 255)";
ctx7.stroke();
ctx7.fill();
ctx7.beginPath();
ctx7.arc(115, 130, 60, 0, 3, false);
ctx7.closePath();
ctx7.lineWidth = 5;
ctx7.strokeStyle = "rgb(255, 255, 0)";
ctx7.fillStyle = "rgb(255, 255, 255)";
ctx7.stroke();
ctx7.fill();
context_1.beginPath();
context_1.arc(50,50,40,0,2*Math.PI);
context_1.fillStyle = "red";
context_1.fill();
context_1.beginPath();
context_1.arc(50,50,30,0,2*Math.PI);
context_1.fillStyle = "gray";
context_1.fill();
context_1.beginPath();
context_1.fillStyle = "#000000";
context_1.fillRect(48, 0, 5, 105);
context_1.beginPath();
context_1.fillStyle = "#000000";
context_1.fillRect(0, 50, 105, 5);
}
</script>
<body>
<div class = "container">
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas>
<canvas id="canvas3" width="200" height="200"></canvas>
<canvas id="canvas4" width="200" height="200" style="background:#D52B1E"></canvas>
<canvas id="canvas5" width="200" height="200"></canvas>
<canvas id="canvas6" width="200" height="200"></canvas>
<canvas id="canvas7" width="200" height="200"></canvas>
<canvas id="canvas8" width="200" height="200"></canvas>
</div><file_sep><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Junsay SVG</title>
</head>
<body>
<table style="float:left; margin:auto;">
<tr>
<th>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid;width:200px; height:300px; background-color:#f1f1f1;">
<path stroke="black" stroke-width="1" d="M5 0, v100" />
<path stroke="black" stroke-width="1" d="M10 0, v95" />
<path stroke="black" stroke-width="1" d="M15 0, v25" />
<path stroke="black" stroke-width="1" d="M20 0, v20" />
<path stroke="black" stroke-width="1" d="M25 0, v19" />
<path stroke="black" stroke-width="1" d="M30 0, v20" />
<path stroke="black" stroke-width="1" d="M35 0, v25" />
<path stroke="black" stroke-width="1" d="M40 0, v100" />
<path stroke="black" stroke-width="1" d="M45 0, v85" />
<path stroke="black" stroke-width="1" d="M50 0, v95" />
<path stroke="black" stroke-width="1" d="M15 35, v25" />
<path stroke="black" stroke-width="1" d="M20 40, v15" />
<path stroke="black" stroke-width="1" d="M25 41, v13" />
<path stroke="black" stroke-width="1" d="M30 40, v15" />
<path stroke="black" stroke-width="1" d="M35 35, v25" />
<path stroke="black" stroke-width="1" d="M15 70, v20" />
<path stroke="black" stroke-width="1" d="M20 75, v22" />
<path stroke="black" stroke-width="1" d="M25 76, v19" />
<path stroke="black" stroke-width="1" d="M30 75, v17" />
<path stroke="black" stroke-width="1" d="M35 70, v19" />
<circle cx="25" cy="30" r="11" fill="none" stroke="black" stroke-width="1" />
<circle cx="25" cy="65" r="11" fill="none" stroke="black" stroke-width="1" />
<circle cx="94" cy="10" r="0.5" fill="black" stroke="black" stroke-width="1" />
<circle cx="90" cy="14" r="1" fill="black" stroke="black" stroke-width="1" />
<circle cx="83" cy="20" r="3" fill="black" stroke="black" stroke-width="1" />
<circle cx="75" cy="31" r="6" fill="none" stroke="black" stroke-width="1" />
<circle cx="65" cy="50" r="10" fill="black" stroke="black" stroke-width="1" />
<circle cx="58" cy="70" r="6" fill="none" stroke="black" stroke-width="1" />
<circle cx="63" cy="83" r="3" fill="black" stroke="black" stroke-width="1" />
<circle cx="70" cy="90" r="1" fill="black" stroke="black" stroke-width="1" />
<circle cx="77" cy="97" r="0.5" fill="black" stroke="black" stroke-width="1" />
</svg></th>
<th>
<svg viewBox="0 0 100 100"preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:f1f1f1;">
<path stroke="black" stroke-width="1" d="M10 80, v10 , h80 , v-10 , h-80" fill="none" />
<path stroke="black" stroke-width="1" d="M10 10, v68, h15 , v-68 , h-15" fill="none" />
<circle cx="42" cy="62" r="15" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="68" r="9" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="71" r="6" fill="none" stroke-width="1" stroke="black" />
<circle cx="76" cy="74" r="3" fill="none" stroke-width="1" stroke="black" />
</svg></th>
<th>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:#f1f1f1;">
<circle cx="0" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 20, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 23, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<circle cx="0" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="25" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="25" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="25" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="25" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="25" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="32" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 40, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 43, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<circle cx="0" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="45" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="45" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="45" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="45" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="45" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="52" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 60, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 63, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<circle cx="0" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="65" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="65" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="65" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="65" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="65" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="72" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 80, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 83, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<circle cx="0" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="85" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="85" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="85" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="85" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="85" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="92" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 100, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 103, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
</svg></th>
</tr>
<tr>
<td>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:#f1f1f1;">
<path stroke-width="1" stroke="black" fill="none" d="M10 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M13 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<ellipse cx="25" cy="10" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="25" cy="30" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="25" cy="50" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="25" cy="70" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="25" cy="90" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<path stroke-width="1" stroke="black" fill="none" d="M35 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M38 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M60 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M63 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<ellipse cx="75" cy="10" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="75" cy="30" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="75" cy="50" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="75" cy="70" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<ellipse cx="75" cy="90" rx="10" ry="5" fill="none" stroke="black" stroke-width="1"/>
<path stroke-width="1" stroke="black" fill="none" d="M85 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M88 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
</svg>
</td>
<td>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:#f1f1f1;">
<circle cx="8" cy="2" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="2" cy="8" r="1" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M15 0, l-17 17 ," />
<path stroke-width="1" stroke="black" fill="none" d="M20 0, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M13 6.5, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M6 13, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M30 0, l-30 30 ," />
<circle cx="33" cy="2" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="28" cy="8" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="22" cy="14" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="16" cy="20" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="26" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="4" cy="33" r="1" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M42 0, l-50 50," />
<path stroke-width="1" stroke="black" fill="none" d="M46 0, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M39 7, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M32 14, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M25 21, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M18 28, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M11 35, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M4 42, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M57 0, l-57 57," />
<circle cx="62" cy="2" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="55" cy="9" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="48" cy="16" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="41" cy="23" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="34" cy="30" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="27" cy="37" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="44" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="13" cy="51" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="6" cy="58" r="1" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M70 0, l-70 70," />
<path stroke-width="1" stroke="black" fill="none" d="M74 0, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M67 7, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M60 14, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M53 21, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M46 28, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M39 35, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M32 42, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M25 49, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M18 56, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M11 63, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M4 70, l-5 5, l3 3, l5 -5, l-3.3 -3.3" />
<path stroke-width="1" stroke="black" fill="none" d="M85 0, l-85 85," />
<circle cx="90" cy="2" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="83" cy="9" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="76" cy="16" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="69" cy="23" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="62" cy="30" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="55" cy="37" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="48" cy="44" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="41" cy="51" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="34" cy="58" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="27" cy="65" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="72" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="13" cy="79" r="1" fill="none" stroke-width="1" stroke="black" />
<circle cx="6" cy="86" r="1" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M100 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M105 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M110 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M115 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M120 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M125 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M130 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M135 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M140 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M145 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M150 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M155 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M160 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M165 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M170 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M175 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M180 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M185 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M190 0, l-100 100," />
<path stroke-width="1" stroke="black" fill="none" d="M195 0, l-100 100," />
</svg>
</svg>
</td>
<td>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:#f1f1f1;">
<path stroke-width="1" stroke="black" fill="none" d="M10 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M13 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M20 15, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M20 35, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M20 55, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M20 75, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M20 95, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M35 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M38 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M60 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M63 0, l-10 10, l10 10, l-10 10, l10 10, l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10 " />
<path stroke-width="1" stroke="black" fill="none" d="M70 15, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M70 35, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M70 55, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M70 75, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M70 95, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M85 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M88 0, l10 10, l-10 10 ,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10,l10 10,l-10 10" />
</svg>
</td>
</tr>
<tr>
<td>
<svg viewBox="0 0 100 100" preserveAspectRatio="none" style="border: black solid; width:200px; height:300px; background-color:#f1f1f1;">
<circle cx="0" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="10" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="20" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="30" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="40" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="50" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="60" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="70" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="80" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="90" cy="5" r="2" fill="none" stroke-width="1" stroke="black" />
<circle cx="100" cy="12" r="2" fill="none" stroke-width="1" stroke="black" />
<path stroke-width="1" stroke="black" fill="none" d="M0 20, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 23, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M5 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M25 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M45 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M65 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M85 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M105 30, h10, v-5,h-10,v5" />
<path stroke-width="1" stroke="black" fill="none" d="M0 45, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 48, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M0 51, h100, " />
<path stroke-width="1" stroke="black" fill="none" d="M0 53, h100, " />
<path stroke-width="1" stroke="black" fill="none" d="M0 55, h100, " />
<path stroke-width="1" stroke="black" fill="none" d="M0 57, h100, " />
<path stroke-width="1" stroke="black" fill="none" d="M0 72, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 75, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="black" fill="none" d="M84 87.5, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M59 87.5, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M33 87.5, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M5 87.5, h10, l5 -5, l-5 -5, h-10, l-5 5,l5 5" />
<path stroke-width="1" stroke="black" fill="none" d="M0 100, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
<path stroke-width="1" stroke="gray" fill="none" d="M0 103, l10 -10 , l10 10 , l10 -10 , l10 10 , l10 -10, l10 10 , l10 -10 , l10 10 ,l10 -10 , l10 10" />
</svg>
</td>
</tr>
</table>
</body>
</html>
| 697f51dec808bc9e59642dfb75a102932628ca98 | [
"PHP"
] | 4 | PHP | fonzroevykjunsay/finalportfolio | 2fbf60eacc7b649f40bf7621693a39d98e5da63c | f44a20cff50671ba70a93b08c78fc0d90970f215 |
refs/heads/master | <repo_name>zgwldrc/dab-kubectl<file_sep>/init.sh
#!/bin/sh
# 作者: 夏禹
# 邮箱: <EMAIL>
# 运行环境: zgwldrc/kubectl:v1.11.7
# 加载kubeconfig文件
# Env Var Must
# CONTEXT
# KUBECONFIG_CONTENT
# 必要的环境变量
ENV_CHECK_LIST='
CONTEXT
KUBECONFIG_CONTENT
'
function check_env(){
local r
for i do
eval "r=\${${i}:-undefined}"
if [ "$r" == "undefined" ];then
echo "$i is not defined"
exit 1
fi
done
}
function _init_env(){
mkdir -p $HOME/.kube/
echo -e "$KUBECONFIG_CONTENT" > $HOME/.kube/config
kubectl config use-context $CONTEXT
}
check_env $ENV_CHECK_LIST
_init_env<file_sep>/Dockerfile
FROM lachlanevenson/k8s-kubectl:v1.11.7
RUN sed -i -re 's|http://[^/]+/(.*)|http://mirrors.aliyun.com/\1|' /etc/apk/repositories && \
apk add curl
RUN wget https://get.helm.sh/helm-v2.14.1-linux-amd64.tar.gz && \
tar xf helm-v2.14.1-linux-amd64.tar.gz && \
mv linux-amd64/helm /usr/local/bin/
ENTRYPOINT ["sh", "-c"]
| 998054f61705dceb9af1aec1a0213995f95e6ae2 | [
"Dockerfile",
"Shell"
] | 2 | Shell | zgwldrc/dab-kubectl | 64feef71d898eb52cd9778db8fc575ec541b351c | 88057e3c50e8711fe71cd2b92d75c1ef38332738 |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 19:32:56 2021
@author: 91913
"""
radius=int(input("enter the radius of cirle"))
area=radius*radius
print(+area)<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Sep 28 21:36:10 2021
@author: 91913
""
start, end = -4, 19
for num in range(start, end + 1):
if num >= 0:
print(num, end = " ")
| 2f1800728411f9bacb940509189f024243a723ac | [
"Python"
] | 2 | Python | deadly115/mycap.py | 52ff6c1c5cbf740a7dcc14180e1aa957efa54eb9 | 7cd6307a5d40db324ea62deab864c25f6e24d470 |
refs/heads/master | <file_sep>package Text;
import java.util.ArrayList;
public class Sentence {
private ArrayList<Word> sentence = new ArrayList<>();
public Sentence() {}
public Sentence(Word word) {
this.sentence.add(word);
}
public void addWord(Word word) {
this.sentence.add(word);
}
public String toString(){
StringBuilder string = new StringBuilder();
for(Word word:sentence){
if(string.length()==0){
string.append(word.getWord());
}else{
string.append(" ").append(word.getWord());
}
}
return string.toString();
}
}
<file_sep>package Text;
import java.util.ArrayList;
public class Text {
private String heading;
private ArrayList<Sentence> text = new ArrayList<>();
public Text(){}
public Text(String heading, Sentence sentence) {
this.heading = heading;
this.text.add(sentence);
}
public void setHeading(String heading) {
this.heading = heading;
}
public void addSentence(Sentence sentence){
text.add(sentence);
}
public void printText(){
for (Sentence sentence : text) {
System.out.println(sentence.toString());
}
}
public String getText() {
StringBuilder textString = new StringBuilder();
for (Sentence sentence : text) {
textString.append(sentence.toString()).append(" ");
}
return textString.toString();
}
public void printHeading(){
System.out.println(heading);
}
}
<file_sep>package Text;
public class TextRunner {
public static void main(String[] args) {
Word word = new Word("First."), word1 = new Word("Second"),
word2 = new Word("Third,"), word3 = new Word("Fourth");
Sentence sentence = new Sentence(), sentence1 = new Sentence();
sentence.addWord(word);
sentence.addWord(word1);
sentence1.addWord(word2);
sentence1.addWord(word3);
Text text = new Text(), text1 = new Text("Heading", sentence);
text1.addSentence(sentence1);
text.addSentence(sentence1);
text.addSentence(sentence);
text.setHeading("TEST");
text.printHeading();
text.printText();
text1.printHeading();
text1.printText();
System.out.println(text1.getText());
System.out.println(text.getText());
}
}
<file_sep>package TaxiTariffCalculator;
public class TaxiRunner {
public static void main(String[] args) {
StandartTariff standartTariff = new StandartTariff();
FamilyTariff familyTariff = new FamilyTariff();
TaxiRide ride = new TaxiRide(1,5,11);
TaxiRide ride1 = new TaxiRide(2, 3, 4);
TaxiRide ride2 = new TaxiRide(1, 5, 3);
TaxiRides taxiRides = new TaxiRides();
taxiRides.addRide(ride);
taxiRides.addRide(ride1);
taxiRides.addRide(ride2);
System.out.println(taxiRides.getPrice(standartTariff));
System.out.println(taxiRides.getPriceOfOneRide(familyTariff, 1));
}
}
| 8f4d325c40c5f810399820c11d1fab7329c1b2c9 | [
"Java"
] | 4 | Java | kvalenty/HomeWorkLess3 | 79fc979f48ba40296f84d59ebfd022e56e3717ee | 983443632330c3cb95f415c4b7502c580772bbb3 |
refs/heads/master | <repo_name>max-antip/dev_portable_pmg<file_sep>/portable.ino
#include <SoftwareSerial.h>
const int START_MESS = 0;
const int END_MESS = 1;
const char START_CH = '~';
const char STOP_CH = '$';
const int btn2 = 8;
const int btn1 = 7;
const int btn4 = 6;
const int btn3 = 5;
const int led = 4;
const String MESS_RESIEVE_ANSWER = "MR";
int state = -1;
const boolean debug = false;
int bluetoothTx = 2;
int bluetoothRx = 3;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
int i = 1;
//------------Message--------
const int m_max_size = 50;
char message[m_max_size];
int m_pointer = 0;
//------------Queue----------
const int q_max_size = 20;
String queue[q_max_size];
int q_pointer = 0;
int q_size = 0;
//-------------------------------------------------------------------------
boolean addToMessage(char c) {
if (m_pointer >= m_max_size) {
return false;
} else {
message[m_pointer] = c;
m_pointer++;
}
return true;
}
void clearMessage() {
for (int idx = 0; idx < m_max_size; idx++) {
message[idx] = '\0';
}
m_pointer = 0;
}
void printMessage() {
for (int idx = 0; idx < m_pointer + 1; idx++) {
if (message[idx] == '\0') {
Serial.println("");
return;
}
Serial.print(message[idx]);
}
Serial.println("");
}
//int messToCardNum() {
// char trimArr [m_pointer+1];
// memcpy(trimArr, message, m_pointer+1);
// return atoi(trimArr);
//}
boolean hasCardNum(String cardNum) {
if (q_size == 0) {
return false;
}
for (int idx = 0; idx < q_max_size; idx++) {
String str = queue[idx];
if (str.equals(cardNum)) {
return true;
}
}
return false;
}
boolean addCard(String cardNum) {
if (q_size > q_max_size) {
return false;
}
if (hasCardNum(cardNum)) {
if (debug) {
Serial.print(cardNum);
Serial.println(" Has already!");
}
return false;
} else {
queue[q_size] = cardNum;
if (debug) {
Serial.println(" Add to queue!");
}
q_size++;
return true;
}
}
String getNextCard() {
if (q_size == 0) {
return "N/A";
} else if (q_pointer > q_size) {
return "N/A";
}
String answer = queue[q_pointer];
q_pointer++;
return answer;
}
void resetQueuePointer() {
if (debug) {
Serial.println("Pointer reset");
}
q_pointer = 0;
}
void clearQueue() {
for (int idx = 0; idx < q_size; idx++) {
queue[idx] = "";
}
q_pointer = 0;
q_size = 0;
if (debug) {
Serial.println("Queue cleared");
}
delay(500);
}
void printCardQueue() {
for (int idx = 0; idx < q_size; idx++) {
String str = queue[idx];
Serial.println(str);
}
}
//-----------------------------------------------------------------
void setup() {
Serial.begin(9600);
bluetooth.begin(9600);
pinMode(btn1, INPUT_PULLUP);
pinMode(btn2, INPUT_PULLUP);
pinMode(btn3, INPUT_PULLUP);
pinMode(btn4, INPUT_PULLUP);
pinMode(led, OUTPUT);
while (!Serial) {}
bluetooth.write("AT+ADDR?");
delay(500);
while (bluetooth.available())
{
Serial.write(bluetooth.read());
}
delay(200);
Serial.println("");
bluetooth.write("AT+IMME0");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
delay(200);
Serial.println("");
bluetooth.write("AT+ROLE0");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
delay(200);
bluetooth.write("AT+POWE3");
delay(500);
while (bluetooth.available())
{
Serial.write(bluetooth.read());
}
delay(100);
Serial.println("");
delay(500);
bluetooth.write("AT+NAMEPortable");
delay(500);
while (bluetooth.available()) {
Serial.write((char)bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+UUID0x1811"); //add charicteristic
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
Serial.println("");
bluetooth.write("AT+CHAR0x2A46"); //add charicteristic
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+RELI0");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+SHOW1");
delay(100);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
}
void blink() {
digitalWrite(led, HIGH);
delay(600);
digitalWrite(led, LOW);
}
boolean hasBLEConnected() {
if (debug) {
Serial.println("CheckingBLE");
}
bluetooth.write("AT+PIO1?");
delay(500);
while (bluetooth.available())
{
String str = bluetooth.readString();
if (str.equals("OK+Get:0")) {
if (debug) {
Serial.println("No connection");
}
return false;
}
}
if (debug) {
Serial.println("Device Connected");
}
return true;
}
void sendMessRecieved() {
for (int idx = 0; idx < MESS_RESIEVE_ANSWER.length(); idx++)
bluetooth.write(MESS_RESIEVE_ANSWER[idx]);
}
void disconnect() {
bluetooth.write("AT");
delay(500);
while (bluetooth.available())
{
String answer = bluetooth.readString();
if (answer.indexOf("OK") > 0) {
if (debug) {
Serial.println("disconnected");
}
}
if (debug) {
Serial.println("coud not disconnected");
}
}
}
void loop()
{
while (bluetooth.available())
{
char toSend = (char)bluetooth.read();
if (toSend == STOP_CH) {
state = END_MESS;
}
if (state == START_MESS) {
addToMessage(toSend);
} else if (state == END_MESS) {
String str = String(message);
addCard(str);
printCardQueue();
clearMessage();
state = -1;
blink();
}
if (toSend == START_CH) {
state = START_MESS;
}
}
int nextCardPressed = digitalRead(btn1);
int resetPoinetr = digitalRead(btn2);
int clearQPressed = digitalRead(btn3);
int disconnectPressed = digitalRead(btn4);
if (!disconnectPressed) {
disconnect();
}
if (!clearQPressed) {
clearQueue();
}
if (!resetPoinetr) {
resetQueuePointer();
delay(500);
}
if (!nextCardPressed) {
// boolean connected = hasBLEConnected();
// if (connected) {
String cardStr = getNextCard();
Serial.println(cardStr);
// bluetooth.write(START_CH);
for (int i = 0; i < cardStr.length(); i++)
{
bluetooth.write(cardStr[i]);
}
// bluetooth.write(STOP_CH);
// }
delay(500);
}
}
| 03dc591d0f34bec7cc9f7f7abe6e91c8e8da8c68 | [
"C++"
] | 1 | C++ | max-antip/dev_portable_pmg | d9563cd6a5915112d5e932520fa6907497c5d2e4 | 7b3b53b45127ff25fed778f1ac88f64046aaed4a |
refs/heads/master | <file_sep>// Importa JSON(AJAX)
function importaJSON(elemento, url){
elemento.addEventListener("click", function(){
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.addEventListener("load", function(){
var listaJson = JSON.parse(xhr.responseText);
listaJson.forEach(function (json){
adicionarTr(json);
});
});
xhr.send();
});
}
<file_sep>//validar paciente
function validarPaciente(paciente){
var listaErro = [];
if(paciente.altura <= 0 || paciente.altura >= 3.00){
listaErro.push('Altura invalida!')
}
if(paciente.peso <= 0 || paciente.peso >= 500){
listaErro.push('Peso invalido!')
}
return listaErro;
}
<file_sep>class NegociacoesView extends ViewBase{
constructor(elemento){
// Mesma ideia do base c#
super(elemento)
}
// private
_template(negociacoesModel){
return `
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>DATA</th>
<th>QUANTIDADE</th>
<th>VALOR</th>
<th>VOLUME</th>
</tr>
</thead>
<tbody>
${negociacoesModel.map((negociacao) =>
` <tr>
<td>${DataHelper.dataParaTexto(negociacao.data)}</td>
<td>${negociacao.quantidade}</td>
<td>${negociacao.valor}</td>
<td>${negociacao.volume}</td>
</tr>`
).join('')}
<tr>
<td colspan='3'></td>
<td>${
// Reduz/"soma" os valores de um array , o valor 0.0 como segundo parametro é o valor inicial da "soma"
negociacoesModel.reduce((total, negociacao) => total += negociacao.volume, 0.0)
}</td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
`
}
}<file_sep>// montar tr paciente
function montarTrPaciente(paciente){
// criar elementos(tag) html para o objeto
var pacienteTr = criarElemnto("tr");
var nomeTd = criarElemnto("td");
var pesoTd = criarElemnto("td");
var alturaTd = criarElemnto("td");
var gorduraTd = criarElemnto("td");
var imcTd = criarElemnto("td");
// adiciona classes e ids no elemento
pacienteTr.setAttribute("class", "paciente");
nomeTd.setAttribute("class", "info-nome");
pesoTd.setAttribute("class", "info-peso");
alturaTd.setAttribute("class", "info-altura");
gorduraTd.setAttribute("class", "info-gordura");
imcTd.setAttribute("class", "info-imc");
// populo os elementos
nomeTd.textContent = paciente.nome;
pesoTd.textContent = paciente.peso;
alturaTd.textContent = paciente.altura;
gorduraTd.textContent = paciente.gordura;
imcTd.textContent = calcularIMC(paciente.altura,paciente.peso);
// adiciona filhos da tr
pacienteTr.appendChild(nomeTd);
pacienteTr.appendChild(pesoTd);
pacienteTr.appendChild(alturaTd);
pacienteTr.appendChild(gorduraTd);
pacienteTr.appendChild(imcTd);
return pacienteTr;
}
// Busca pacientes da tabela
function buscarPacientes(elemento){
elemento.addEventListener("input", function(){
var listaPacientes = document.querySelectorAll(".paciente");
var inputNome = this.value;
if(inputNome.length > 1){
listaPacientes.forEach(function(paciente){
var nome = paciente.querySelector('.info-nome').textContent;
var regex = new RegExp(inputNome,"i");
// condição ternaria
!regex.test(nome)? paciente.classList.add("invisivel") : paciente.classList.remove("invisivel");
});
}else{
listaPacientes.forEach(function(paciente){
paciente.classList.remove("invisivel");
});
}
});
}
//adicionar paciente tabela
function adicionarPacienteTabela(elementoBotao){
elementoBotao.addEventListener('click', function(event){
event.preventDefault();
var form = $('#form-adiciona');
var paciente = criarObjetoPaciente(form);
var ulListaErro = $('#validacaoForm');
ulListaErro.innerHTML = "";
// verifica se existe erros no form de valores
var listaErro = validarPaciente(paciente);
if(listaErro.length > 0){
listaErro.forEach(function(msgErro){
var li = criarElemnto("li");
li.setAttribute('class', 'validarCampoForm');
li.textContent = msgErro;
ulListaErro.appendChild(li);
})
listaErro = 0;
return;
}
// injeta na tabela o objeto criado
adicionarTr(paciente);
limparCamposForm(form);
});
}
// criar paciente
function criarObjetoPaciente(form){
// objeto paciente
return {
nome: form.nome.value,
peso: form.peso.value,
altura: form.altura.value,
gordura: form.gordura.value,
imc: calcularIMC(form.altura.value,form.peso.value)
};
}
// limpar campos e dar foco no campo nome
function limparCamposForm(form){
form.nome.value = '';
form.peso.value = '';
form.altura.value = '';
form.gordura.value = '';
form.nome.focus();
}<file_sep>// Joga a funcionalidade das funções em variavel referenciado sempre ao objeto DOM
var $ = document.querySelector.bind(document);
var criarElemnto = document.createElement.bind(document);
// calcular IMC
function calcularIMC(altura, peso){
var resultado = peso / (altura * altura);
return resultado.toFixed(2); // fixa duas casas decimas após o ponto
}
// deletar elemento da tabela
function deletarElemento(elemento){
elemento.addEventListener('dblclick', function(event){
var alvo = event.target.parentNode;
alvo.setAttribute('class', 'fadeOut');
setTimeout(function(){
alvo.remove();
}, 500);
});
}
<file_sep>// buscar elementos no DOM
var corpoTabela = $("#tabela-pacientes");
var filtro = $("#filtro");
// buscar pacientes tabela
buscarPacientes(filtro);
// deletar elemento
deletarElemento(corpoTabela);
// Adicionar tr paciente na tabela
function adicionarTr(paciente){
corpoTabela.appendChild(montarTrPaciente(paciente));
}
<file_sep>class ListaNegociacoes{
constructor() {
this._negociacoes = []
}
adicionar(negociacao){
this._negociacoes.push(negociacao);
}
get negociacoes(){
// retorna uma nova referencia de um novo array, mesmo que seja alterado a instancia antiga não afetara no novo retorno
return [].concat(this._negociacoes);
}
}<file_sep>//obter o elemento botao do form.
var botaoAdiciona = $("#adicionar-paciente");
// Adicina paciente na tabela
adicionarPacienteTabela(botaoAdiciona);
| e92edffa375ce0615c6246f772249e0a89afe02e | [
"JavaScript"
] | 8 | JavaScript | AndersonGimenes/EstudoJs | ae49c44bb211fdc794075b81d24bff42b026cc9a | 2140e2f341f3209ceb6e1557b9d33ade9e426e13 |
refs/heads/master | <file_sep>from flask import Flask, Blueprint, session, redirect, url_for, escape, request
from flask_assets import Bundle, Environment
from flask_sqlalchemy import SQLAlchemy
import os.path, zipfile, psycopg2
app = Flask(__name__)
wsgi_app = app.wsgi_app
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# = 'sqlite:///users.db'
app.secret_key = '<KEY>'
db = SQLAlchemy(app)
from util.assets import *
from views.admin import *
from views.loci import *
from views.barcodes import *
from views.companies import *
from views.ari import *
from views.seattle import *
if not os.path.isfile("static/data/loci_activity_connections.json"):
zip_ref = zipfile.ZipFile("static/data/data.zip", 'r')
zip_ref.extractall("static/data/")
zip_ref.close()
assets = Environment(app)
assets.register(bundles)
app.register_blueprint(admin)
app.register_blueprint(companies)
app.register_blueprint(barcodes)
app.register_blueprint(loci)
app.register_blueprint(ari)
app.register_blueprint(seattle)
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
<file_sep>from flask import Blueprint
from views.admin import *
seattle = Blueprint('seattle', __name__)
def seattle_template():
side = "Barcode Information"
side_desc = "Hover over or search for a barcode to see its information"
return side, side_desc
################################################################################
# Generated Data #
################################################################################
################################################################################
# Activity Hierarchy #
################################################################################
@seattle.route("/seattle/gen/activity/downstream")
def gen_activity_downstream():
graphURL = "/static/data/seattle_gen_activity_downstream.json"
main = "Generated Seattle Supply Chain Connections, Activity Hierarchy - " \
"Downstreamness Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/activity/markov")
def gen_activity_markov():
graphURL = "/static/data/seattle_gen_activity_markov.json"
main = "Generated Seattle Supply Chain Connections, Activity Hierarchy - " \
"Markovian Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/activity/maxflow")
def gen_activity_maxflow():
graphURL = "/static/data/seattle_gen_activity_maxflow.json"
main = "Generated Seattle Supply Chain Connections, Activity Hierarchy - Max Flow"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/activity/mean")
def gen_activity_mean():
graphURL = "/static/data/seattle_gen_activity_mean.json"
main = "Generated Seattle Supply Chain Connections, Activity Hierarchy - Mean"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Resource Hierarchy #
################################################################################
@seattle.route("/seattle/gen/resource/downstream")
def gen_resource_downstream():
graphURL = "/static/data/seattle_gen_resource_downstream.json"
main = "Generated Seattle Supply Chain Connections, Resource Hierarchy - " \
"Downstreamness Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/resource/markov")
def gen_resource_markov():
graphURL = "/static/data/seattle_gen_resource_markov.json"
main = "Generated Seattle Supply Chain Connections, Resource Hierarchy - " \
"Markovian Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/resource/maxflow")
def gen_resource_maxflow():
graphURL = "/static/data/seattle_gen_resource_maxflow.json"
main = "Generated Seattle Supply Chain Connections, Resource Hierarchy - Max Flow"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/gen/resource/mean")
def gen_resource_mean():
graphURL = "/static/data/seattle_gen_resource_mean.json"
main = "Generated Seattle Supply Chain Connections, Resource Hierarchy - Mean"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Real Data #
################################################################################
################################################################################
# Activity Hierarchy #
################################################################################
@seattle.route("/seattle/real/activity/downstream")
def real_activity_downstream():
graphURL = "/static/data/seattle_real_activity_downstream.json"
main = "Real Seattle Supply Chain Connections, Activity Hierarchy - " \
"Downstreamness Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/activity/markov")
def real_activity_markov():
graphURL = "/static/data/seattle_real_activity_markov.json"
main = "Real Seattle Supply Chain Connections, Activity Hierarchy - " \
"Markovian Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/activity/maxflow")
def real_activity_maxflow():
graphURL = "/static/data/seattle_real_activity_maxflow.json"
main = "Real Seattle Supply Chain Connections, Activity Hierarchy - Max Flow"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/activity/mean")
def real_activity_mean():
graphURL = "/static/data/seattle_real_activity_mean.json"
main = "Real Seattle Supply Chain Connections, Activity Hierarchy - Mean"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Resource Hierarchy #
################################################################################
@seattle.route("/seattle/real/resource/downstream")
def real_resource_downstream():
graphURL = "/static/data/seattle_real_resource_downstream.json"
main = "Real Seattle Supply Chain Connections, Resource Hierarchy - " \
"Downstreamness Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/resource/markov")
def real_resource_markov():
graphURL = "/static/data/seattle_real_resource_markov.json"
main = "Real Seattle Supply Chain Connections, Resource Hierarchy - " \
"Markovian Distance"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/resource/maxflow")
def real_resource_maxflow():
graphURL = "/static/data/seattle_real_resource_maxflow.json"
main = "Real Seattle Supply Chain Connections, Resource Hierarchy - Max Flow"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)
@seattle.route("/seattle/real/resource/mean")
def real_resource_mean():
graphURL = "/static/data/seattle_real_resource_mean.json"
main = "Real Seattle Supply Chain Connections, Resource Hierarchy - Mean"
side, side_desc = seattle_template()
return quick_render(graphURL, main, side, side_desc)<file_sep>from flask import Blueprint
from views.admin import *
ari = Blueprint('ari', __name__)
def ari_template():
side = "Barcode Information"
side_desc = "Hover over or search for a barcode to see its information"
return side, side_desc
################################################################################
# Generated Data #
################################################################################
################################################################################
# Activity Hierarchy #
################################################################################
@ari.route("/ari/gen/activity/downstream")
def gen_activity_downstream():
graphURL = "/static/data/ari_gen_activity_downstream.json"
main = "Generated Ari Supply Chain Connections, Activity Hierarchy - " \
"Downstreamness Distance (Top 100 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/activity/markov")
def gen_activity_markov():
graphURL = "/static/data/ari_gen_activity_markov.json"
main = "Generated Ari Supply Chain Connections, Activity Hierarchy - " \
"Markovian Distance (Top 5 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/activity/maxflow")
def gen_activity_maxflow():
graphURL = "/static/data/ari_gen_activity_maxflow.json"
main = "Generated Ari Supply Chain Connections, Activity Hierarchy - " \
"Max Flow (Top 1 input & output with edge weight > 0.1)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/activity/mean")
def gen_activity_mean():
graphURL = "/static/data/ari_gen_activity_mean.json"
main = "Generated Ari Supply Chain Connections, Activity Hierarchy - " \
"Mean (Top 20 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Resource Hierarchy #
################################################################################
@ari.route("/ari/gen/resource/downstream")
def gen_resource_downstream():
graphURL = "/static/data/ari_gen_resource_downstream.json"
main = "Generated Ari Supply Chain Connections, Resource Hierarchy - " \
"Downstreamness Distance (Top 100 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/resource/markov")
def gen_resource_markov():
graphURL = "/static/data/ari_gen_resource_markov.json"
main = "Generated Ari Supply Chain Connections, Resource Hierarchy - " \
"Markovian Distance (Top 5 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/resource/maxflow")
def gen_resource_maxflow():
graphURL = "/static/data/ari_gen_resource_maxflow.json"
main = "Generated Ari Supply Chain Connections, Resource Hierarchy - " \
"Max Flow (Top 1 input & output with edge weight > 500)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/gen/resource/mean")
def gen_resource_mean():
graphURL = "/static/data/ari_gen_resource_mean.json"
main = "Generated Ari Supply Chain Connections, Resource Hierarchy - " \
"Mean (Top 20 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Real Data #
################################################################################
################################################################################
# Activity Hierarchy #
################################################################################
@ari.route("/ari/real/activity/downstream")
def real_activity_downstream():
graphURL = "/static/data/ari_real_activity_downstream.json"
main = "Real Ari Supply Chain Connections, Activity Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/activity/markov")
def real_activity_markov():
graphURL = "/static/data/ari_real_activity_markov.json"
main = "Real Ari Supply Chain Connections, Activity Hierarchy - " \
"Markovian Distance (Top 5 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/activity/maxflow")
def real_activity_maxflow():
graphURL = "/static/data/ari_real_activity_maxflow.json"
main = "Real Ari Supply Chain Connections, Activity Hierarchy - " \
"Max Flow (Top 1 input & output with edge weight > 500)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/activity/mean")
def real_activity_mean():
graphURL = "/static/data/ari_real_activity_mean.json"
main = "Real Ari Supply Chain Connections, Activity Hierarchy - " \
"Mean (Top 10 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Resource Hierarchy #
################################################################################
@ari.route("/ari/real/resource/downstream")
def real_resource_downstream():
graphURL = "/static/data/ari_real_resource_downstream.json"
main = "Real Ari Supply Chain Connections, Resource Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/resource/markov")
def real_resource_markov():
graphURL = "/static/data/ari_real_resource_markov.json"
main = "Real Ari Supply Chain Connections, Resource Hierarchy - " \
"Markovian Distance (Top 5 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/resource/maxflow")
def real_resource_maxflow():
graphURL = "/static/data/ari_real_resource_maxflow.json"
main = "Real Ari Supply Chain Connections, Resource Hierarchy - " \
"Max Flow (Top 1 input & output with edge weight > 0.1)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)
@ari.route("/ari/real/resource/mean")
def real_resource_mean():
graphURL = "/static/data/ari_real_resource_mean.json"
main = "Real Ari Supply Chain Connections, Resource Hierarchy - " \
"Mean (Top 10 inputs & outputs)"
side, side_desc = ari_template()
return quick_render(graphURL, main, side, side_desc)<file_sep>import calendar, time
from flask import Flask, Blueprint, render_template, redirect, \
url_for, session, escape, request
from app import db
from util.models import User
admin = Blueprint('admin', __name__)
################################################################################
# Rendering templates #
################################################################################
admin_key = "ultrapowerpie"
EXPIRATION = 1800
expired_key = 'Your demo has expired.\n Please contact ' \
'<EMAIL> to request another demo key, ' \
'or click "About" to try again. '
invalid_key = 'You do not have a valid key.\n Please contact ' \
'<EMAIL> to request a demo key, ' \
'or click "About" to try again. ' \
demo = "Please enter your demo key for a 30 minute demo session."
demo_admin = "USER CREATION"
def check_session(default):
if 'time' not in session:
return render_template("invalid.html", mes = invalid_key, starttime=-1,
expire=EXPIRATION)
if (calendar.timegm(time.gmtime())-session['time']) > EXPIRATION:
return render_template("invalid.html", mes = expired_key, starttime=-1,
expire=EXPIRATION)
return default
def quick_render(graphURL, main, side, side_desc):
if 'time' not in session:
session['time'] = -1
return check_session(render_template("visualize.html",
graphURL=graphURL,
main=main,
side=side,
side_desc=side_desc,
starttime=session['time'],
expire=EXPIRATION))
################################################################################
# #
# Administrative Pages #
# #
################################################################################
@admin.route('/login', methods=['GET', 'POST'])
def login():
if 'time' in session:
if (calendar.timegm(time.gmtime()) - session['time']) < EXPIRATION:
return check_session(render_template("about.html",
starttime=session['time'],
expire=EXPIRATION))
if request.method == 'POST':
u = User.query.filter(User.username ==
request.form['username']).first()
if request.form['username'] == admin_key:
if u:
db.session.delete(u)
db.session.commit()
new_u = User(username=admin_key, time=calendar.timegm(time.gmtime()))
db.session.add(new_u)
db.session.commit()
session['username'] = admin_key
session['time'] = new_u.time
return redirect(url_for('admin.create'))
else:
if not u:
return render_template("invalid.html", mes=invalid_key,
starttime=-1, expire=EXPIRATION)
session['username'] = u.username
session['time'] = u.time
if u.time < 0:
new_u = User(username=u.username,
time=calendar.timegm(time.gmtime()))
session['time'] = new_u.time
db.session.delete(u)
db.session.commit()
db.session.add(new_u)
db.session.commit()
return check_session(render_template("about.html",
starttime=session['time'],
expire=EXPIRATION))
return render_template("login.html",
demo_desc=demo,
starttime=-1,
expire=EXPIRATION)
@admin.route('/create', methods=['GET', 'POST'])
def create():
if 'username' in session and session['username'] == admin_key:
if request.method == 'POST':
u = User.query.filter(User.username == request.form['username']).first()
if u:
db.session.delete(u)
db.session.commit()
new_u = User(username=request.form['username'], time=-1)
db.session.add(new_u)
db.session.commit()
userlist=User.query.all()
users = []
for u in userlist:
users.append([u.username, time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(u.time))])
return render_template("create.html",
demo_desc=demo_admin,
starttime=session['time'],
expire=EXPIRATION,
users=users)
return render_template("invalid.html", mes = invalid_key, starttime=-1,
expire=EXPIRATION)
@admin.route("/")
def index():
return redirect(url_for('admin.login'))
<file_sep>from flask import Blueprint
from views.admin import *
companies = Blueprint('companies', __name__)
def companies_template():
side = "Company Information"
side_desc = "Hover over or search for a company to see its information"
return side, side_desc
################################################################################
# #
# Activity Hierarchy #
# #
################################################################################
@companies.route("/companies/activity/fprox/nodes")
def activity_fprox_nodes():
graphURL = "/static/data/companies_activity_fprox_nodes.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/fprox/edges")
def activity_fprox_edges():
graphURL = "/static/data/companies_activity_fprox_edges.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/fprox/simrank")
def activity_fprox_simrank():
graphURL = "/static/data/companies_activity_fprox_simrank.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Simrank Score (Top 10 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/fprox/neighbor")
def activity_fprox_neighbor():
graphURL = "/static/data/companies_activity_fprox_neighbor.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/fprox/vector")
def activity_fprox_vector():
graphURL = "/static/data/companies_activity_fprox_vector.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Vector Similarity (Top 10 inputs & outputs, edge weight > 0.01)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/fprox/mean")
def activity_fprox_mean():
graphURL = "/static/data/companies_activity_fprox_mean.json"
main = "Company Functional Proximity, Activity Hierarchy - " \
"Mean Similarity (Top 10 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@companies.route("/companies/activity/supply/downstream")
def activity_supply_downstream():
graphURL = "/static/data/companies_activity_supply_downstream.json"
main = "Supply Chain Company Connections, Activity Hierarchy - " \
"Downstreamness Distance (Top 30 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/supply/markov")
def activity_supply_markov():
graphURL = "/static/data/companies_activity_supply_markov.json"
main = "Supply Chain Company Connections, Activity Hierarchy - " \
"Markov Distance (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/supply/maxflow")
def activity_supply_maxflow():
graphURL = "/static/data/companies_activity_supply_maxflow.json"
main = "Supply Chain Company Connections, Activity Hierarchy - " \
"Max Flow (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/supply/mean")
def activity_supply_mean():
graphURL = "/static/data/companies_activity_supply_mean.json"
main = "Supply Chain Company Connections, Activity Hierarchy - " \
"Mean Distance (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Competition #
################################################################################
@companies.route("/companies/activity/competition/connections")
def activity_competition_connections():
graphURL = "/static/data/companies_activity_competition_connections.json"
main = "Competition Company Connections, Activity Hierarchy - " \
"Connections (Top 5 Inputs & Outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/activity/competition/competitiveness")
def activity_competition_competitiveness():
graphURL = "/static/data/companies_activity_competition_competitiveness.json"
main = "Competition Company Connections, Activity Hierarchy - " \
"Competitiveness (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# #
# Resource Hierarchy #
# #
################################################################################
@companies.route("/companies/resource/fprox/nodes")
def resource_fprox_nodes():
graphURL = "/static/data/companies_resource_fprox_nodes.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/fprox/edges")
def resource_fprox_edges():
graphURL = "/static/data/companies_resource_fprox_edges.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/fprox/simrank")
def resource_fprox_simrank():
graphURL = "/static/data/companies_resource_fprox_simrank.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Simrank Score (Top 10 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/fprox/neighbor")
def resource_fprox_neighbor():
graphURL = "/static/data/companies_resource_fprox_neighbor.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/fprox/vector")
def resource_fprox_vector():
graphURL = "/static/data/companies_resource_fprox_vector.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Vector Similarity (Top 10 inputs & outputs, edge weight > 0.01)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/fprox/mean")
def resource_fprox_mean():
graphURL = "/static/data/companies_resource_fprox_mean.json"
main = "Company Functional Proximity, Resource Hierarchy - " \
"Mean Similarity (Top 10 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@companies.route("/companies/resource/supply/downstream")
def resource_supply_downstream():
graphURL = "/static/data/companies_resource_supply_downstream.json"
main = "Supply Chain Company Connections, Resource Hierarchy - " \
"Downstreamness Distance (Top 30 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/supply/markov")
def resource_supply_markov():
graphURL = "/static/data/companies_resource_supply_markov.json"
main = "Supply Chain Company Connections, Resource Hierarchy - " \
"Markov Distance (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/supply/maxflow")
def resource_supply_maxflow():
graphURL = "/static/data/companies_resource_supply_maxflow.json"
main = "Supply Chain Company Connections, Resource Hierarchy - " \
"Max Flow (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/supply/mean")
def resource_supply_mean():
graphURL = "/static/data/companies_resource_supply_mean.json"
main = "Supply Chain Company Connections, Resource Hierarchy - " \
"Mean Distance (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Competition #
################################################################################
@companies.route("/companies/resource/competition/connections")
def resource_competition_connections():
graphURL = "/static/data/companies_resource_competition_connections.json"
main = "Competition Company Connections, Resource Hierarchy - " \
"Connections (Top 5 Inputs & Outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/resource/competition/competitiveness")
def resource_competition_competitiveness():
graphURL = "/static/data/companies_resource_competition_competitiveness.json"
main = "Competition Company Connections, Resource Hierarchy - " \
"Competitiveness (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# #
# NAICS Hierarchy #
# #
################################################################################
@companies.route("/companies/naics/fprox/nodes")
def naics_fprox_nodes():
graphURL = "/static/data/companies_naics_fprox_nodes.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/fprox/edges")
def naics_fprox_edges():
graphURL = "/static/data/companies_naics_fprox_edges.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/fprox/simrank")
def naics_fprox_simrank():
graphURL = "/static/data/companies_naics_fprox_simrank.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Simrank Score (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/fprox/neighbor")
def naics_fprox_neighbor():
graphURL = "/static/data/companies_naics_fprox_neighbor.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/fprox/vector")
def naics_fprox_vector():
graphURL = "/static/data/companies_naics_fprox_vector.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Vector Similarity(Top 50 inputs & outputs, edge weight > 0.01)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/fprox/mean")
def naics_fprox_mean():
graphURL = "/static/data/companies_naics_fprox_mean.json"
main = "Company Functional Proximity, NAICS Hierarchy - " \
"Mean Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@companies.route("/companies/naics/supply/downstream")
def naics_supply_downstream():
graphURL = "/static/data/companies_naics_supply_downstream.json"
main = "Supply Chain Company Connections, NAICS Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/supply/markov")
def naics_supply_markov():
graphURL = "/static/data/companies_naics_supply_markov.json"
main = "Supply Chain Company Connections, NAICS Hierarchy - " \
"Markov Distance (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/supply/maxflow")
def naics_supply_maxflow():
graphURL = "/static/data/companies_naics_supply_maxflow.json"
main = "Supply Chain Company Connections, NAICS Hierarchy - " \
"Max Flow (Top 20 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/supply/mean")
def naics_supply_mean():
graphURL = "/static/data/companies_naics_supply_mean.json"
main = "Supply Chain Company Connections, NAICS Hierarchy - " \
"Mean Distance (Top 20 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Competition #
################################################################################
@companies.route("/companies/naics/competition/connections")
def naics_competition_connections():
graphURL = "/static/data/companies_naics_competition_connections.json"
main = "Competition Company Connections, NAICS Hierarchy - " \
"Connections (Top 5 Inputs & Outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/naics/competition/competitiveness")
def naics_competition_competitiveness():
graphURL = "/static/data/companies_naics_competition_competitiveness.json"
main = "Competition Company Connections, NAICS Hierarchy - " \
"Competitiveness (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# #
# Syntax Hierarchy #
# #
################################################################################
@companies.route("/companies/syntax/fprox/nodes")
def syntax_fprox_nodes():
graphURL = "/static/data/companies_syntax_fprox_nodes.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/fprox/edges")
def syntax_fprox_edges():
graphURL = "/static/data/companies_syntax_fprox_edges.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/fprox/simrank")
def syntax_fprox_simrank():
graphURL = "/static/data/companies_syntax_fprox_simrank.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Simrank Score (Top 5 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/fprox/neighbor")
def syntax_fprox_neighbor():
graphURL = "/static/data/companies_syntax_fprox_neighbor.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/fprox/vector")
def syntax_fprox_vector():
graphURL = "/static/data/companies_syntax_fprox_vector.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Vector Similarity(Top 100 inputs & outputs, edge weight > 0.01)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/fprox/mean")
def syntax_fprox_mean():
graphURL = "/static/data/companies_syntax_fprox_mean.json"
main = "Company Functional Proximity, Syntax Hierarchy - " \
"Mean Similarity (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@companies.route("/companies/syntax/supply/downstream")
def syntax_supply_downstream():
graphURL = "/static/data/companies_syntax_supply_downstream.json"
main = "Supply Chain Company Connections, Syntax Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/supply/markov")
def syntax_supply_markov():
graphURL = "/static/data/companies_syntax_supply_markov.json"
main = "Supply Chain Company Connections, Syntax Hierarchy - " \
"Markov Distance (Top 3 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/supply/maxflow")
def syntax_supply_maxflow():
graphURL = "/static/data/companies_syntax_supply_maxflow.json"
main = "Supply Chain Company Connections, Syntax Hierarchy - " \
"Max Flow (Top 50 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/supply/mean")
def syntax_supply_mean():
graphURL = "/static/data/companies_syntax_supply_mean.json"
main = "Supply Chain Company Connections, Syntax Hierarchy - " \
"Mean Distance (Top 20 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Competition #
################################################################################
@companies.route("/companies/syntax/competition/connections")
def syntax_competition_connections():
graphURL = "/static/data/companies_syntax_competition_connections.json"
main = "Competition Company Connections, Syntax Hierarchy - " \
"Connections (All)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
@companies.route("/companies/syntax/competition/competitiveness")
def syntax_competition_competitiveness():
graphURL = "/static/data/companies_syntax_competition_competitiveness.json"
main = "Competition Company Connections, Syntax Hierarchy - " \
"Competitiveness (Top 10 inputs & outputs)"
side, side_desc = companies_template()
return quick_render(graphURL, main, side, side_desc)
<file_sep>// Get the modal
var modal = document.getElementById('myModal');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
function stringTable(edges) {
var str = "";
for (var i = 0; i < edges.length; i++) {
str += "<tr onclick=\"switchModal('"+String(edges[i].key)+"')\">";
str += "<td>";
str += String(edges[i].key);
str += "</td>";
str += "<td>";
str += String(parseFloat(edges[i].weight).toFixed(2));
str += "</td>";
str += "</tr>";
}
return str;
}
function stringAssocTable(assocs) {
var str = "";
for (var i = 0; i < assocs.length; i++) {
str += "<tr>";
str += "<td>";
str += String(assocs[i][0]);
str += "</td>";
str += "<td>";
str += String(assocs[i][1]);
str += "</td>";
str += "</tr>";
}
return str;
}
function stringAssocHead(head) {
var str = "<tr>";
str += "<th>";
str += String(head[0]);
str += "</th>";
str += "<th>";
str += String(head[1])
str += "</th>";
str += "</tr>";
return str;
}
// functions for search and mouse hover to make the graph interactive
function mouseclick(d) {
document.getElementById('incoming').innerHTML = stringTable(inEdges[d.name]);
document.getElementById('outgoing').innerHTML = stringTable(outEdges[d.name]);
document.getElementById('assocHead').innerHTML = stringAssocHead(d.assocHead);
document.getElementById('associated').innerHTML = stringAssocTable(d.associated);
modal.style.display = "block";
document.getElementById('modalTitle').innerHTML = "Node Information for: "+String(d.key);
document.getElementById('descTitle').innerHTML = "Node Description for: "+String(d.key);
document.getElementById('node-desc').innerHTML = String(d.desc);
modalHighlight(d);
}
function switchModal(key) {
node
.filter(function(d) { return d.key === key; })
.each(function(d) { mouseclick(d); });
}
// modal graph drawing function (draws lines connected to given node)
function drawModalGraph() {
var modalNodes = modalCluster.nodes(packageHierarchy(masterData)),
modalLinks = packageGoesto(modalNodes);
modalLink = modalLink
.data(bundle(modalLinks))
.enter().append("path")
.each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
.attr("class", "modalLink")
.attr("d", line);
modalNode = modalNode
.data(modalNodes.filter(function(n) { return !n.children; }))
.enter().append("text")
.attr("class", "modalNode")
.attr("dy", ".31em")
.attr("id", function(d){ return 'name' + d.name; })
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 10) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
.style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.style("fill", "transparent")
.text(function(d) { return d.key; });
}
// functions for search and mouse hover to make the graph interactive
function modalHighlight(d) {
modalOff();
modalNode
.each(function(n) { n.target = n.source = false; });
modalLink
.classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
.classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
.filter(function(l) { return l.target === d || l.source === d; })
.each(function() { this.parentNode.appendChild(this); });
modalNode
.filter(function(n) { return n.target; })
.style("font-weight", "700")
.style("fill", "#d62728");
modalNode
.filter(function(n) { return n.source; })
.style("font-weight", "700")
.style("fill", "#2ca02c");
modalNode
.filter(function(n) { return d.name === n.name})
.style("font-weight", "700")
.style("fill", "#000");
}
function modalOff() {
modalLink
.classed("link--target", false)
.classed("link--source", false);
modalNode
.style("font-weight", "300")
.style("fill", "transparent");
}
// // Construct the package hierarchy from class names
// // Structure must be: grandparent.parent.child.grandchild.etc...
// function packageHierarchy(classes) {
// var map = {};
// function find(name, data) {
// var node = map[name], i;
// if (!node) {
// node = map[name] = data || {name: name, children: []};
// if (name.length) {
// node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
// node.parent.children.push(node);
// node.key = name.substring(i + 1);
// }
// }
// return node;
// }
// classes.forEach(function(d) {
// find(d.name, d);
// });
// return map[""];
// }
// // Return a list of outgoing edges for the given array of nodes.
// function packageGoesto(nodes) {
// var map = {},
// goesto = [];
// // Compute a map from name to node.
// nodes.forEach(function(d) {
// map[d.name] = d;
// });
// // Sort the input nodes to each node
// if (MAXIN < 0) {
// nodes.forEach(function(d) {
// pqs[d.name] = new FastPriorityQueue(function(a,b) {return a.weight > b.weight});
// });
// nodes.forEach(function(d) {
// if (d.goesto) d.goesto.forEach(function(i) {
// if(i[0] in pqs) {
// pqs[i[0]].add({ source: d.name, weight: i[1] });
// }
// });
// });
// nodes.forEach(function(d) {
// inWeights[d.name] = {}
// var pos = 0;
// while (! pqs[d.name].isEmpty()) {
// pos++;
// name = pqs[d.name].poll()['source'];
// inWeights[d.name][name] = pos;
// }
// if (pos > MAXIN) MAXIN = pos;
// });
// }
// // Sort the output nodes to each node
// if (MAXOUT < 0) {
// pqs = {}
// nodes.forEach(function(d) {
// if (!pqs[d.name]) {
// pqs[d.name] = new FastPriorityQueue(function(a,b) {return a.weight > b.weight});
// }
// if (d.goesto) d.goesto.forEach(function(i) {
// pqs[d.name].add({ sink: i[0], weight: i[1] });
// });
// });
// nodes.forEach(function(d) {
// outWeights[d.name] = {}
// var pos = 0;
// while (! pqs[d.name].isEmpty()) {
// pos++;
// name = pqs[d.name].poll()['sink'];
// outWeights[d.name][name] = pos;
// }
// if (pos > MAXOUT) MAXOUT = pos;
// });
// }
// // For each node, construct a link from the source to target node.
// nodes.forEach(function(d) {
// if (d.goesto) d.goesto.forEach(function(i) {
// if(i[0] in map) {
// if (i[1] < weightMin) return null;
// if (i[1] > weightMax) return null;
// if (inWeights[i[0]][d.name] > maxIn) return null;
// if (outWeights[d.name][i[0]] > maxOut) return null;
// goesto.push({ source: map[d.name], target: map[i[0]] });
// if (i[1] > MAXWEIGHT) MAXWEIGHT = i[1];
// }
// });
// });
// return goesto;
// }
// // redraw the graph
// function reDraw() {
// d3.selectAll(".link").remove();
// d3.selectAll(".node").remove();
// link = svg.append("g").selectAll(".link");
// link = svg.append("g").selectAll(".node");
// drawGraph();
// }
<file_sep>from flask import Blueprint
from views.admin import *
loci = Blueprint('loci', __name__)
def loci_template():
side = "Locus Information"
side_desc = "Hover over or search for a locus to see its name"
return side, side_desc
################################################################################
# #
# Activity Hierarchy #
# #
################################################################################
@loci.route("/loci/activity/connections")
def activity_connections():
graphURL = "/static/data/loci_activity_connections.json"
main = "Loci Functional Space, Activity Hierarchy - Connections (All)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/nodes")
def activity_fprox_nodes():
graphURL = "/static/data/loci_activity_fprox_nodes.json"
main = "Loci Functional Proximity, Activity Hierarchy - " \
"Node Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/edges")
def activity_fprox_edges():
graphURL = "/static/data/loci_activity_fprox_edges.json"
main = "Loci Functional Proximity, Activity Hierarchy - " \
"Edge Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/simrank")
def activity_fprox_simrank():
graphURL = "/static/data/loci_activity_fprox_simrank.json"
main = "Loci Functional Proximity, Activity Hierarchy " \
"- SimRank Similarity (Top 20 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/neighbor")
def activity_fprox_neighbor():
graphURL = "/static/data/loci_activity_fprox_neighbor.json"
main = "Loci Functional Proximity, Activity Hierarchy - " \
"Neighbor Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/vector")
def activity_fprox_vector():
graphURL = "/static/data/loci_activity_fprox_vector.json"
main = "Loci Functional Proximity, Activity Hierarchy - " \
"Vector Similarity (Top 5 inputs & outputs, edge weights > 0.02)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/fprox/mean")
def activity_fprox_mean():
graphURL = "/static/data/loci_activity_fprox_mean.json"
main = "Loci Functional Proximity, Activity Hierarchy - " \
"Mean Similarity (Top 10 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@loci.route("/loci/activity/supply/downstream")
def activity_supply_downstream():
graphURL = "/static/data/loci_activity_supply_downstream.json"
main = "Supply Chain Loci Connections, Activity Hierarchy - " \
"Downstreamness Distance (Top 100 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/supply/markov")
def activity_supply_markov():
graphURL = "/static/data/loci_activity_supply_markov.json"
main = "Supply Chain Loci Connections, Activity Hierarchy - " \
"Markovian Distance (Top 8 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/supply/maxflow")
def activity_supply_maxflow():
graphURL = "/static/data/loci_activity_supply_maxflow.json"
main = "Supply Chain Loci Connections, Activity Hierarchy - " \
"Max Flow (Top 5 inputs & outputs, edges weights > 0.0005)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/activity/supply/mean")
def activity_supply_mean():
graphURL = "/static/data/loci_activity_supply_mean.json"
main = "Supply Chain Loci Connections, Activity Hierarchy - " \
"Mean Distance (Top 50 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# #
# Resource Hierarchy #
# #
################################################################################
@loci.route("/loci/resource/connections")
def resource_connections():
graphURL = "/static/data/loci_resource_connections.json"
main = "Loci Functional Space, Resource Hierarchy - Connections (All)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/nodes")
def resource_fprox_nodes():
graphURL = "/static/data/loci_resource_fprox_nodes.json"
main = "Loci Functional Proximity, Resource Hierarchy - " \
"Node Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/edges")
def resource_fprox_edges():
graphURL = "/static/data/loci_resource_fprox_edges.json"
main = "Loci Functional Proximity, Resource Hierarchy - " \
"Edge Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/simrank")
def resource_fprox_simrank():
graphURL = "/static/data/loci_resource_fprox_simrank.json"
main = "Loci Functional Proximity, Resource Hierarchy " \
"- SimRank Similarity (Top 20 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/neighbor")
def resource_fprox_neighbor():
graphURL = "/static/data/loci_resource_fprox_neighbor.json"
main = "Loci Functional Proximity, Resource Hierarchy - " \
"Neighbor Similarity (Top 5 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/vector")
def resource_fprox_vector():
graphURL = "/static/data/loci_resource_fprox_vector.json"
main = "Loci Functional Proximity, Resource Hierarchy - " \
"Vector Similarity (Top 5 inputs & outputs, edge weights > 0.02)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/fprox/mean")
def resource_fprox_mean():
graphURL = "/static/data/loci_resource_fprox_mean.json"
main = "Loci Functional Proximity, Resource Hierarchy - " \
"Mean Similarity (Top 10 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@loci.route("/loci/resource/supply/downstream")
def resource_supply_downstream():
graphURL = "/static/data/loci_resource_supply_downstream.json"
main = "Supply Chain Loci Connections, Resource Hierarchy - " \
"Downstreamness Distance (Top 100 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/supply/markov")
def resource_supply_markov():
graphURL = "/static/data/loci_resource_supply_markov.json"
main = "Supply Chain Loci Connections, Resource Hierarchy - " \
"Markovian Distance (Top 8 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/supply/maxflow")
def resource_supply_maxflow():
graphURL = "/static/data/loci_resource_supply_maxflow.json"
main = "Supply Chain Loci Connections, Resource Hierarchy - " \
"Max Flow (Top 5 inputs & outputs, edges weights > 0.0005)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)
@loci.route("/loci/resource/supply/mean")
def resource_supply_mean():
graphURL = "/static/data/loci_resource_supply_mean.json"
main = "Supply Chain Loci Connections, Resource Hierarchy - " \
"Mean Distance (Top 50 inputs & outputs)"
side, side_desc = loci_template()
return quick_render(graphURL, main, side, side_desc)<file_sep>from app import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True)
time = db.Column(db.Integer, unique=False)
def __init__(self, username=None, time=None):
self.username = username
self.time = time
def __repr__(self):
return '<User %r>' % (self.username)
<file_sep>/******************************************************************************/
/* Comparators for sorting nodes */
/******************************************************************************/
function comparator(a, b) {
return d3.ascending(a.name, b.name);
}
function compareWeight(a, b) { return a.weight > b.weight; }
function compareWeightDes(a, b) { return b.weight - a.weight; }
/******************************************************************************/
/* Function for centering the main svg graph when it's drawn */
/******************************************************************************/
function svgTranslate () {
var x = window.getComputedStyle(document.getElementById('bundleWrapper')).getPropertyValue('width');
x = parseInt(x.substring(0,x.length-2)) / 2;
var y = window.getComputedStyle(document.getElementById('bundleWrapper')).getPropertyValue('height');
y = parseInt(y.substring(0,y.length-2)) / 2;
return [x,y];
}
/******************************************************************************/
/* Graph data variables */
/******************************************************************************/
// have sliders and search bar been initialized?
var isDrawn = false;
// for calculating the top weighted input and output nodes
var pqs = {},
inTop = {},
outTop = {},
inEdges = {},
outEdges = {};
// json object of all node/edge/name/parent/description data
var masterData;
/******************************************************************************/
/* Main graph layout */
/******************************************************************************/
// svg graph variables
var diameter = 800,
radius = diameter / 2,
innerRadius = radius - 100;
var cluster = d3.layout.cluster()
.size([360, innerRadius])
.sort(comparator)
.value(function(d) { return d.size; });
var bundle = d3.layout.bundle();
/******************************************************************************/
/* Modal graph layout */
/******************************************************************************/
// svg graph variables
var modalDiameter = 500,
modalRadius = modalDiameter / 2,
modalInnerRadius = modalRadius - 100;
var modalCluster = d3.layout.cluster()
.size([360, modalInnerRadius])
.sort(comparator)
.value(function(d) { return d.size; });
/******************************************************************************/
/* Drawing the main graph */
/******************************************************************************/
var line = d3.svg.line.radial()
.interpolate("bundle")
.tension(0.7)
.radius(function(d) { return d.y; })
.angle(function(d) { return d.x / 180 * Math.PI; });
var myZoom = d3.behavior.zoom()
.scaleExtent([.01, 100])
.on("zoom", zoom);
function zoom() {
svg.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
var svg = d3.select("#mainStage").append("svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("id", "bundleWrapper")
.on("dblclick.zoom", null)
.call(myZoom)
.append("g")
.attr("id", "bundleGraph");
myZoom.translate(svgTranslate());
svg = svg.attr("transform", "translate(" + svgTranslate() + ")");
var link = svg.append("g").selectAll(".link"),
node = svg.append("g").selectAll(".node");
/******************************************************************************/
/* Draw the modal graph */
/******************************************************************************/
var modalSvg = d3.select("#modalStage").append("svg")
.attr("width", modalDiameter)
.attr("height", modalDiameter)
.attr("id", "bundleWrapper")
.append("g")
.attr("id", "bundleGraph")
.attr("transform", "translate(" + modalRadius + "," + modalRadius + ")");
var modalLink = modalSvg.append("g").selectAll(".link"),
modalNode = modalSvg.append("g").selectAll(".node");
/******************************************************************************/
/* Drawing the main legend */
/******************************************************************************/
var legend = svg.append("g")
.attr("class", "legend")
.attr("x", radius-100)
.attr("y", -radius)
.attr("height", 100)
.attr("width", 100);
legend.append("rect")
.attr("x", radius-200)
.attr("y", 10-radius)
.attr("width", 10)
.attr("height", 10)
.style("fill", "#2ca02c");
legend.append("rect")
.attr("x", radius-200)
.attr("y", 30-radius)
.attr("width", 10)
.attr("height", 10)
.style("fill", "#d62728");
legend.append("text")
.attr("x", radius-180)
.attr("y", 20-radius)
.style("fill", "#2ca02c")
.text("Incoming");
legend.append("text")
.attr("x", radius-180)
.attr("y", 40-radius)
.style("fill", "#d62728")
.text("Outgoing");
/******************************************************************************/
/* Drawing the modal Legend */
/******************************************************************************/
var modalLegend = modalSvg.append("g")
.attr("class", "legend")
.attr("x", modalRadius-90)
.attr("y", -modalRadius)
.attr("height", 100)
.attr("width", 100);
modalLegend.append("rect")
.attr("x", modalRadius-90)
.attr("y", 10-modalRadius)
.attr("width", 10)
.attr("height", 10)
.style("fill", "#2ca02c");
modalLegend.append("rect")
.attr("x", modalRadius-90)
.attr("y", 30-modalRadius)
.attr("width", 10)
.attr("height", 10)
.style("fill", "#d62728");
modalLegend.append("text")
.attr("x", modalRadius-70)
.attr("y", 20-modalRadius)
.style("fill", "#2ca02c")
.text("Incoming");
modalLegend.append("text")
.attr("x", modalRadius-70)
.attr("y", 40-modalRadius)
.style("fill", "#d62728")
.text("Outgoing");
/******************************************************************************/
/* Options variables */
/******************************************************************************/
var fillToggle = document.getElementById('fillIn'),
fillnode = "transparent";
var edgeToggle = document.getElementById('toggleIn'),
hoverlink = false;
var nodeSlider = document.getElementById("nodeSlide"),
nodeInput = document.getElementById('nodeIn'),
fontsize = 8;
var edgeSlider = document.getElementById("edgeSlide"),
edgeInput = document.getElementById('edgeIn'),
edgewidth = 1;
var tensionSlider = document.getElementById("tension"),
tensionInput = document.getElementById('tensionIn');
var weightSlider = document.getElementById("weight"),
weightMinInput = document.getElementById('weightMinIn'),
weightMaxInput = document.getElementById('weightMaxIn'),
weightMin = 0,
weightMax = Number.POSITIVE_INFINITY,
MAXWEIGHT = -1;
var inSlider = document.getElementById("topIn"),
inInput = document.getElementById('inIn'),
maxIn = Number.POSITIVE_INFINITY,
MAXIN = -1;
var outSlider = document.getElementById("topOut"),
outInput = document.getElementById('outIn'),
maxOut = Number.POSITIVE_INFINITY,
MAXOUT = -1;
// for integer values in the sliders
var toInt = wNumb({ decimals: 0 });
<file_sep>/******************************************************************************/
/* load the json data asynchronously, and only once per page view */
/******************************************************************************/
d3.json(graphURL, function(error, flaredata) {
if (error) throw error;
masterData = flaredata;
// initializing the graph
d3.select(self.frameElement).style("height", diameter + "px");
drawGraph();
})
/******************************************************************************/
/* Main graph drawing function */
/******************************************************************************/
function drawGraph() {
var nodes = cluster.nodes(packageHierarchy(masterData)),
links = packageGoesto(nodes);
link = link
.data(bundle(links))
.enter().append("path")
.each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
.attr("class", "link")
.attr("d", line)
.style("stroke-width", String(edgewidth)+"px")
.on("mouseover", edgeovered)
.on("mouseout", edgeouted);
node = node
.data(nodes.filter(function(n) { return !n.children; }))
.enter().append("text")
.attr("class", "node")
.attr("dy", ".31em")
.attr("id", "node-text")
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + parseFloat(fontsize)) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
.style("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.style("font-size", String(fontsize)+"px")
.style("fill", fillnode)
.text(function(d) { return d.key; })
.on("mouseover", mouseovered)
.on("mouseout", mouseouted)
.on("click", mouseclick);
drawModalGraph();
if (!isDrawn) {
drawSliders();
drawSearch();
}
}
/******************************************************************************/
/* Functions for search and mouse hover to make the graph interactive */
/******************************************************************************/
function mouseovered(d) {
mouseouted(d);
if (hoverlink) { edgeouted(d); }
document.getElementById('selfName')
.innerHTML = String(d.brief).split(",").join("<br>");
node
.each(function(n) { n.target = n.source = false; });
link
.classed("link-off", true)
.classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
.classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
.filter(function(l) { return l.target === d || l.source === d; })
.each(function() { this.parentNode.appendChild(this); });
node
.filter(function(n) { return n.target; })
.style("font-weight", "700")
.style("fill", "#d62728");
node
.filter(function(n) { return n.source; })
.style("font-weight", "700")
.style("fill", "#2ca02c");
node
.filter(function(n) { return d.name === n.name})
.style("font-weight", "700")
.style("fill", "#000");
}
function mouseouted(d) {
link
.classed("link-off", false)
.classed("link--target", false)
.classed("link--source", false);
node
.style("font-weight", "300")
.style("fill", fillnode);
}
/******************************************************************************/
/* Functions for search and mouse hover to make the graph interactive */
/******************************************************************************/
function edgeovered(d) {
if (!hoverlink) return null;
edgeouted(d);
document.getElementById('selfName')
.innerHTML = "Source:\n"+String(d.source.key)+"<br>Sink:\n"+String(d.target.key);
node
.each(function(n) { n.target = n.source = false; });
link
.classed("link-on", function(l) { return (l.source === d.source && l.target === d.target); })
.classed("link-off", function(l) { return !(l.source === d.source && l.target === d.target); });
node
.filter(function(n) { return n.name === d.target.name; })
.style("font-weight", "700")
.style("fill", "#d62728");
node
.filter(function(n) { return n.name === d.source.name; })
.style("font-weight", "700")
.style("fill", "#2ca02c");
}
function edgeouted(d) {
link
.classed("link-off", false)
.classed("link-on", false);
node
.style("font-weight", "300")
.style("fill", fillnode);
}
/******************************************************************************/
/* Redraw the graph (asynchronous processes sometimes get buggy) */
/******************************************************************************/
function reDraw() {
d3.selectAll(".link").remove();
d3.selectAll(".node").remove();
d3.selectAll(".modalLink").remove();
d3.selectAll(".modalNode").remove();
link = svg.append("g").selectAll(".link");
node = svg.append("g").selectAll(".node");
modalLink = modalSvg.append("g").selectAll(".modalLink");
modalNode = modalSvg.append("g").selectAll(".modalNode");
drawGraph();
}
<file_sep>function getTimeRemaining(starttime, expire){
if (starttime < 0) {
var total = 0
}
else {
var total = expire - (Math.floor(new Date() / 1000) - starttime)
}
var seconds = total % 60;
var minutes = Math.floor(total/60) % 60;
var hours = Math.floor(total/(60*60)) % 24;
return {
'total': total,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, starttime, expire) {
var clock = document.getElementById(id);
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(starttime, expire);
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
<file_sep>/******************************************************************************/
/* jQuery for returning input data */
/******************************************************************************/
function isSearched(d) { return d.name === $("#search").getSelectedItemData().name }
/******************************************************************************/
/* draw the search bar */
/******************************************************************************/
function drawSearch() {
var options = {
url: graphURL,
placeholder: "Search",
getValue: function(d) { return d.name.substring(d.name.lastIndexOf(".")+1)+" : "+String(d.search).split(",").join(" ,"); },
list: {
showAnimation: {
type: "slide",
time: 150,
},
hideAnimation: {
type: "slide",
time: 150,
},
onSelectItemEvent: function() { node.filter(isSearched).each(function(d) { mouseovered(d); }); },
onChooseEvent: function() { node.filter(isSearched).each(function(d) { mouseclick(d); }); },
maxNumberOfElements: 10,
match: {
enabled: true
},
sort: {
enabled: true
}
},
theme: "round"
};
$("#search").easyAutocomplete(options);
}<file_sep>from flask import Blueprint
from views.admin import *
barcodes = Blueprint('barcodes', __name__)
def barcode_template():
side = "Barcode Information"
side_desc = "Hover over or search for a barcode or its work locus " \
" to see its information"
return side, side_desc
################################################################################
# #
# Activity Hierarchy #
# #
################################################################################
@barcodes.route("/barcodes/activity/fprox/nodes")
def activity_fprox_nodes():
graphURL = "/static/data/barcodes_activity_fprox_nodes.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/fprox/edges")
def activity_fprox_edges():
graphURL = "/static/data/barcodes_activity_fprox_edges.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/fprox/simrank")
def activity_fprox_simrank():
graphURL = "/static/data/barcodes_activity_fprox_simrank.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Simrank Score (Top 10 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/fprox/neighbor")
def activity_fprox_neighbor():
graphURL = "/static/data/barcodes_activity_fprox_neighbor.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/fprox/vector")
def activity_fprox_vector():
graphURL = "/static/data/barcodes_activity_fprox_vector.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Vector Similarity (Top 3 inputs & outputs, edge weight > 0.01)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/fprox/mean")
def activity_fprox_mean():
graphURL = "/static/data/barcodes_activity_fprox_mean.json"
main = "Barcode Functional Proximity, Activity Hierarchy - " \
"Mean Similarity (Top 5 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@barcodes.route("/barcodes/activity/supply/downstream")
def activity_supply_downstream():
graphURL = "/static/data/barcodes_activity_supply_downstream.json"
main = "Supply Chain Barcode Connections, Activity Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/supply/markov")
def activity_supply_markov():
graphURL = "/static/data/barcodes_activity_supply_markov.json"
main = "Supply Chain Barcode Connections, Activity Hierarchy - " \
"Markov Distance (Top 5 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/supply/maxflow")
def activity_supply_maxflow():
graphURL = "/static/data/barcodes_activity_supply_maxflow.json"
main = "Supply Chain Barcode Connections, Activity Hierarchy - " \
"Max Flow (Top 1 input & output, edge weight > 0.1)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/activity/supply/mean")
def activity_supply_mean():
graphURL = "/static/data/barcodes_activity_supply_mean.json"
main = "Supply Chain Barcode Connections, Activity Hierarchy - " \
"Mean Distance (Top 20 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# #
# Resource Hierarchy #
# #
################################################################################
@barcodes.route("/barcodes/resource/fprox/nodes")
def resource_fprox_nodes():
graphURL = "/static/data/barcodes_resource_fprox_nodes.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Node Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/fprox/edges")
def resource_fprox_edges():
graphURL = "/static/data/barcodes_resource_fprox_edges.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Edge Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/fprox/simrank")
def resource_fprox_simrank():
graphURL = "/static/data/barcodes_resource_fprox_simrank.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Simrank Score (Top 10 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/fprox/neighbor")
def resource_fprox_neighbor():
graphURL = "/static/data/barcodes_resource_fprox_neighbor.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Neighbor Similarity (Top 3 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/fprox/vector")
def resource_fprox_vector():
graphURL = "/static/data/barcodes_resource_fprox_vector.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Vector Similarity (Top 3 inputs & outputs, edge weight > 0.01)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/fprox/mean")
def resource_fprox_mean():
graphURL = "/static/data/barcodes_resource_fprox_mean.json"
main = "Barcode Functional Proximity, Resource Hierarchy - " \
"Mean Similarity (Top 5 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
################################################################################
# Supply #
################################################################################
@barcodes.route("/barcodes/resource/supply/downstream")
def resource_supply_downstream():
graphURL = "/static/data/barcodes_resource_supply_downstream.json"
main = "Supply Chain Barcode Connections, Resource Hierarchy - " \
"Downstreamness Distance (Top 50 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/supply/markov")
def resource_supply_markov():
graphURL = "/static/data/barcodes_resource_supply_markov.json"
main = "Supply Chain Barcode Connections, Resource Hierarchy - " \
"Markov Distance (Top 5 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/supply/maxflow")
def resource_supply_maxflow():
graphURL = "/static/data/barcodes_resource_supply_maxflow.json"
main = "Supply Chain Barcode Connections, Resource Hierarchy - " \
"Max Flow (Top 1 input & output, edge weight > 0.1)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
@barcodes.route("/barcodes/resource/supply/mean")
def resource_supply_mean():
graphURL = "/static/data/barcodes_resource_supply_mean.json"
main = "Supply Chain Barcode Connections, Resource Hierarchy - " \
"Mean Distance (Top 20 inputs & outputs)"
side, side_desc = barcode_template()
return quick_render(graphURL, main, side, side_desc)
<file_sep>from flask_assets import Bundle, Environment
bundles = {
'menu_css': Bundle(
'css/lib/bootstrap-responsive.min.css',
'css/lib/bootstrap.min.css',
'css/lib/keen-dashboards.css',
'css/menuStyle.css',
output='gen/menu.css'),
'menu_js': Bundle(
'js/lib/jquery.min.js',
'js/lib/bootstrap.min.js',
'js/timer.js',
output='gen/menu.js'),
'vis_css': Bundle(
'css/lib/easy-autocomplete.themes.css',
'css/lib/easy-autocomplete.min.css',
'css/lib/nouislider.min.css',
'css/lib/nouislider.tooltips.css',
'css/graphStyle.css',
'css/stageStyle.css',
'css/modalStyle.css',
output='gen/vis.css'),
'vis_head_js': Bundle(
'js/lib/jquery.easy-autocomplete.min.js',
'js/lib/nouislider.min.js',
'js/lib/wNumb.js',
'js/lib/FastPriorityQueue.js',
'js/lib/d3.min.js',
output='gen/vis_head.js'),
'vis_foot_js': Bundle(
'js/variables.js',
'js/mainGraph.js',
'js/packageGraph.js',
'js/options.js',
'js/search.js',
'js/modalGraph.js',
output='gen/vis_foot.js')
} | 4bdcb5278682ded3c9e6e245c324887d00621ea9 | [
"JavaScript",
"Python"
] | 14 | Python | ultrapowerpie/demoviz | 9b5c35246009887ba68cd63e815e37f5f7ae9289 | f37abd76f55e2c636125d7005ad1434039638e9d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.Mods;
using Prism.Mods.DefHandlers;
using Prism.Util;
namespace Prism.API.Defs
{
public class RecipeItems : Dictionary<ItemRef, int> { }
[Flags]
public enum RecipeLiquids
{
None = 0,
Water = 1,
Lava = 2,
Honey = 4
}
public class RecipeDef
{
public static IEnumerable<RecipeDef> Recipes
{
get
{
return Handler.RecipeDef.recipes;
}
}
public ModInfo Mod
{
get;
internal set;
}
public ItemRef CreateItem
{
get;
set;
}
public int CreateStack
{
get;
set;
}
//TODO: add ItemGroups and change ItemRef to an ItemRef | ItemGroup discriminated union
public IDictionary<ItemRef, int> RequiredItems
{
get;
set;
}
//TODO: add TileGroups and change it to another discriminated union
public TileRef[] RequiredTiles
{
get;
set;
}
public RecipeLiquids RequiredLiquids
{
get;
set;
}
public RecipeDef(
#region arguments
ItemRef createItem,
int stack = 1,
IDictionary<ItemRef, int> reqItems = null,
TileRef[] reqTiles = null,
RecipeLiquids reqLiquids = RecipeLiquids.None
#endregion
)
{
CreateItem = createItem;
CreateStack = stack;
RequiredItems = reqItems ?? new Dictionary<ItemRef, int>();
RequiredTiles = reqTiles ?? Empty<TileRef>.Array;
RequiredLiquids = reqLiquids;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Prism.Util
{
public static class LinqExt
{
public static bool IsEmpty <T>(this IEnumerable<T> coll)
{
foreach (var t in coll)
return false;
return true;
}
public static bool IsSingleton<T>(this IEnumerable<T> coll)
{
bool foundFirst = false;
foreach (var t in coll)
{
if (foundFirst)
return false;
foundFirst = true;
}
return foundFirst;
}
public static IEnumerable<T> Flatten <T>(this IEnumerable<IEnumerable<T>> coll)
{
return coll.DefaultIfEmpty(Empty<T>.Array).Aggregate((a, b) => a.SafeConcat(b));
}
public static IEnumerable<T> SafeConcat<T>(this IEnumerable<T> coll, IEnumerable<T> other)
{
if (coll == null && other == null)
return Empty<T>.Array;
if (coll == null)
return other;
if (other == null)
return coll;
return coll.Concat(other);
}
public static IEnumerable<TOut> SafeSelect<TIn, TOut>(this IEnumerable<TIn> coll, Func<TIn, TOut> fn)
{
if (fn == null)
throw new ArgumentNullException("fn");
if (coll == null)
yield break;
foreach (var i in coll)
yield return fn(i);
yield break;
}
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> dict)
{
var ret = new Dictionary<TKey, TValue>();
foreach (var kvp in dict)
ret.Add(kvp.Key, kvp.Value);
return ret;
}
public static bool All(this IEnumerable<bool> coll)
{
return coll.All(MiscExtensions.Identity);
}
public static bool Any(this IEnumerable<bool> coll)
{
return coll.Any(MiscExtensions.Identity);
}
public static T[] Subarray<T>(this T[] arr, int s, int l)
{
if (s == 0 && l == arr.Length)
return arr;
if (s < 0 || s + l >= arr.Length)
throw new ArgumentOutOfRangeException();
var ret = new T[l];
Array.Copy(arr, s, ret, 0, l);
return ret;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API;
using Prism.API.Audio;
using Prism.API.Behaviours;
using Prism.Mods.BHandlers;
using Terraria;
namespace Prism.Mods.Hooks
{
sealed class GameHooks : IOBHandler<GameBehaviour>
{
IEnumerable<Action> preUpdate, postUpdate, onUpdateKeyboard;
IEnumerable<Action<Ref<BgmEntry>>> updateMusic;
public override void Create()
{
behaviours = new List<GameBehaviour>(ModData.mods.Values.Select(m => m.gameBehaviour));
base.Create();
preUpdate = HookManager.CreateHooks<GameBehaviour, Action>(behaviours, "PreUpdate" );
postUpdate = HookManager.CreateHooks<GameBehaviour, Action>(behaviours, "PostUpdate" );
onUpdateKeyboard = HookManager.CreateHooks<GameBehaviour, Action>(behaviours, "OnUpdateKeyboard");
updateMusic = HookManager.CreateHooks<GameBehaviour, Action<Ref<BgmEntry>>>(behaviours, "UpdateMusic");
}
public override void Clear ()
{
base.Clear();
preUpdate = null;
postUpdate = null;
onUpdateKeyboard = null;
updateMusic = null;
}
public void PreUpdate ()
{
HookManager.Call(preUpdate );
}
public void PostUpdate()
{
HookManager.Call(postUpdate);
}
public void UpdateMusic(ref BgmEntry e)
{
var pe = new Ref<BgmEntry>(e);
HookManager.Call(updateMusic, pe);
e = pe.Value;
}
public void OnUpdateKeyboard()
{
HookManager.Call(onUpdateKeyboard);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Prism.Injector
{
public static class LinqExt
{
/// <summary>
/// Gets whether an <see cref="IEnumerable{T}"/> is in chronological order by supplying the adjacent items for each item.
/// </summary>
/// <typeparam name="T">Item type.</typeparam>
/// <param name="coll">This collection.</param>
/// <param name="getPrevious">
/// Passes an item in the collection and returns either the previous item or null to ignore the check.
/// <para/>Note: pass null for the function itself to skip it. However, if both the getPrevious and getNext functions are null, an <see cref="ArgumentException"/> will be thrown.
/// </param>
/// <param name="getNext">
/// Passes an item in the collection and returns either the next item or null to ignore the check.
/// <para/>Note: pass null for the function itself to skip it. However, if both the getPrevious and getNext functions are null, an <see cref="ArgumentException"/> will be thrown.
/// </param>
/// <returns>Whether the collection is chronological.</returns>
[DebuggerStepThrough]
public static bool Chronological<T>(this IEnumerable<T> coll, Func<T, T> getPrevious, Func<T, T> getNext)
{
var arr = coll.ToArray();
if (getPrevious == null && getNext == null)
throw new ArgumentException("At least one of the two adjacent item functions must be defined.");
for (int i = 0; i < arr.Length; i++)
{
var prev = getPrevious == null || i == 0 || ReferenceEquals(getPrevious(arr[i]), null) || getPrevious(arr[i]).Equals(arr[i - 1]);
var next = getNext == null || i == arr.Length - 1 || ReferenceEquals(getNext (arr[i]), null) || getNext (arr[i]).Equals(arr[i + 1]);
if (!(prev && next))
return false;
}
return true;
}
[DebuggerStepThrough]
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> coll)
{
return coll.DefaultIfEmpty(new T[0]).Aggregate((a, b) => a.SafeConcat(b));
}
[DebuggerStepThrough]
public static IEnumerable<T> SafeConcat<T>(this IEnumerable<T> coll, IEnumerable<T> other)
{
if (coll == null && other == null)
return new T[0];
if (coll == null) return other;
if (other == null) return coll ;
return coll.Concat(other);
}
static bool Equality<T>(T a, T b)
{
if (ReferenceEquals(a, null))
return ReferenceEquals(b, null);
if (ReferenceEquals(b, null))
return false;
if (a is IEquatable<T>)
return ((IEquatable<T>)a).Equals(b);
if (b is IEquatable<T>)
return ((IEquatable<T>)b).Equals(a);
return a.Equals(b);
}
[DebuggerStepThrough]
public static bool Equals<T>(this IList<T> a, IList<T> b)
{
if (a.Count != b.Count)
return false;
for (int i = 0; i < a.Count; i++)
if (!Equality(a[i], b[i]))
return false;
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.Mods.Hooks;
using Terraria;
namespace Prism.API.Behaviours
{
public abstract class TileBehaviour : EntityBehaviour<Tile>
{
[Hook]
public virtual void OnUpdate() { }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Terraria;
namespace Prism.Util
{
public static class MiscExtensions
{
public static string SafeToString(this object v, string defValue = null)
{
if (ReferenceEquals(v, null))
return defValue;
return v.ToString();
}
public static T Identity<T>(T t)
{
return t;
}
public static Ref<TOut> Bind<TIn, TOut>(this Ref<TIn> m, Func<TIn, TOut> map)
{
if (m == null)
return null;
if (ReferenceEquals(m.Value, null))
return new Ref<TOut>(default(TOut));
return new Ref<TOut>(map(m.Value));
}
public static Maybe<TOut> Bind<TIn, TOut>(this Maybe<TIn> m, Func<TIn, TOut> map)
{
if (m.HasValue)
return Maybe.Just(map(m.Value));
return Maybe<TOut>.Nothing;
}
public static Either<TOut1, TOut2> Bind<TIn1, TOut1, TIn2, TOut2>(this Either<TIn1, TIn2> m, Func<TIn1, TOut1> mapR, Func<TIn2, TOut2> mapL)
{
if (m.Kind == EitherKind.Right)
return Either.Right<TOut1, TOut2>(mapR(m.Right));
return Either.Left<TOut1, TOut2>(mapL(m.Left));
}
public static TOut? Bind<TIn, TOut>(this TIn? m, Func<TIn, TOut> map)
where TIn : struct
where TOut : struct
{
return m.HasValue ? map(m.Value) : default(TOut?);
}
public static Lazy<TOut> Bind<TIn, TOut>(this Lazy<TIn> m, Func<TIn, TOut> map)
{
return new Lazy<TOut>(() => map(m.Value));
}
public static KeyValuePair<TOutKey, TOutValue> Bind<TInKey, TOutKey, TInValue, TOutValue>(this KeyValuePair<TInKey, TInValue> m, Func<TInKey, TOutKey> mapK, Func<TInValue, TOutValue> mapV)
{
return new KeyValuePair<TOutKey, TOutValue>(mapK(m.Key), mapV(m.Value));
}
public static Tuple<TOut1, TOut2> Bind<TIn1, TOut1, TIn2, TOut2>(this Tuple<TIn1, TIn2> m, Func<TIn1, TOut1> map1, Func<TIn2, TOut2> map2)
{
return m == null ? null : Tuple.Create(map1(m.Item1), map2(m.Item2));
}
public static Tuple<TOut1, TOut2, TOut3> Bind<TIn1, TOut1, TIn2, TOut2, TIn3, TOut3>(this Tuple<TIn1, TIn2, TIn3> m, Func<TIn1, TOut1> map1, Func<TIn2, TOut2> map2, Func<TIn3, TOut3> map3)
{
return m == null ? null : Tuple.Create(map1(m.Item1), map2(m.Item2), map3(m.Item3));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace Prism.Injector.Patcher
{
public static class CecilHelperExtensions
{
/// <summary>
/// Gets the ldarg instruction of the specified index using the smallest value type it can (because we're targeting the Sega Genesis and need to save memory).
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
internal static Instruction GetLdargOf(this IList<ParameterDefinition> @params, ushort index, bool isInstance = true)
{
int offset = isInstance ? 1 : 0;
switch (index)
{
case 0:
return Instruction.Create(OpCodes.Ldarg_0);
case 1:
return Instruction.Create(OpCodes.Ldarg_1);
case 2:
return Instruction.Create(OpCodes.Ldarg_2);
case 3:
return Instruction.Create(OpCodes.Ldarg_3);
default:
if (index <= Byte.MaxValue)
return Instruction.Create(OpCodes.Ldarg_S, @params[index - offset]);
//Y U NO HAVE USHORT
return Instruction.Create(OpCodes.Ldarg, @params[index]);
}
}
static bool CodeEqIgnoreS(Code a, Code b)
{
if (a == b)
return true;
switch (a)
{
case Code.Beq:
case Code.Beq_S:
return b == Code.Beq || b == Code.Beq_S;
case Code.Bge:
case Code.Bge_S:
return b == Code.Bge || b == Code.Bge_S;
case Code.Ble:
case Code.Ble_S:
return b == Code.Ble || b == Code.Ble_S;
case Code.Bgt:
case Code.Bgt_S:
return b == Code.Bgt || b == Code.Bgt_S;
case Code.Blt:
case Code.Blt_S:
return b == Code.Blt || b == Code.Blt_S;
case Code.Bge_Un:
case Code.Bge_Un_S:
return b == Code.Bge_Un || b == Code.Bge_Un_S;
case Code.Ble_Un:
case Code.Ble_Un_S:
return b == Code.Ble_Un || b == Code.Ble_Un_S;
case Code.Bgt_Un:
case Code.Bgt_Un_S:
return b == Code.Bgt_Un || b == Code.Bgt_Un_S;
case Code.Blt_Un:
case Code.Blt_Un_S:
return b == Code.Blt_Un || b == Code.Blt_Un_S;
case Code.Bne_Un:
case Code.Bne_Un_S:
return b == Code.Bne_Un || b == Code.Bne_Un_S;
case Code.Brfalse:
case Code.Brfalse_S:
return b == Code.Brfalse || b == Code.Brfalse_S;
case Code.Brtrue:
case Code.Brtrue_S:
return b == Code.Brtrue || b == Code.Brtrue_S;
case Code.Br:
case Code.Br_S:
return b == Code.Br || b == Code.Br_S;
case Code.Ldarg:
case Code.Ldarg_S:
return b == Code.Ldarg || b == Code.Ldarg_S;
case Code.Ldarga:
case Code.Ldarga_S:
return b == Code.Ldarga || b == Code.Ldarga_S;
case Code.Ldc_I4:
case Code.Ldc_I4_S:
return b == Code.Ldc_I4 || b == Code.Ldc_I4_S;
case Code.Ldloc:
case Code.Ldloc_S:
return b == Code.Ldloc || b == Code.Ldloc_S;
case Code.Ldloca:
case Code.Ldloca_S:
return b == Code.Ldloca || b == Code.Ldloca_S;
case Code.Leave:
case Code.Leave_S:
return b == Code.Leave || b == Code.Leave_S;
case Code.Starg:
case Code.Starg_S:
return b == Code.Starg || b == Code.Starg_S;
case Code.Stloc:
case Code.Stloc_S:
return b == Code.Stloc || b == Code.Stloc_S;
}
return false;
}
public static TypeDefinition CreateDelegate(this CecilContext context, string @namespace, string name, TypeReference returnType, out MethodDefinition invoke, params TypeReference[] parameters)
{
var cResolver = context.Resolver;
var typeSys = context.PrimaryAssembly.MainModule.TypeSystem;
var delegateType = new TypeDefinition(@namespace, name, TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Sealed, cResolver.ReferenceOf(typeof(MulticastDelegate)));
var ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, typeSys.Void);
ctor.IsRuntime = true;
ctor.Parameters.Add(new ParameterDefinition("object", 0, typeSys.Object));
ctor.Parameters.Add(new ParameterDefinition("method", 0, typeSys.IntPtr));
delegateType.Methods.Add(ctor);
invoke = new MethodDefinition("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, returnType);
invoke.IsRuntime = true;
for (int i = 0; i < parameters.Length; i++)
invoke.Parameters.Add(new ParameterDefinition("arg" + i, 0, parameters[i]));
delegateType.Methods.Add(invoke);
var beginInvoke = new MethodDefinition("BeginInvoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, cResolver.ReferenceOf(typeof(IAsyncResult)));
beginInvoke.IsRuntime = true;
for (int i = 0; i < parameters.Length; i++)
beginInvoke.Parameters.Add(new ParameterDefinition("arg" + i, 0, parameters[i]));
beginInvoke.Parameters.Add(new ParameterDefinition("callback", 0, cResolver.ReferenceOf(typeof(AsyncCallback))));
beginInvoke.Parameters.Add(new ParameterDefinition("object", 0, typeSys.Object));
delegateType.Methods.Add(beginInvoke);
var endInvoke = new MethodDefinition("EndInvoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, typeSys.Void);
endInvoke.IsRuntime = true;
endInvoke.Parameters.Add(new ParameterDefinition("result", 0, cResolver.ReferenceOf(typeof(IAsyncResult))));
delegateType.Methods.Add(endInvoke);
context.PrimaryAssembly.MainModule.Types.Add(delegateType);
return delegateType;
}
public static Instruction[] FindInstrSeq(this MethodBody body, OpCode[] instrs)
{
return body.FindInstrSeq(instrs, instrs.Length);
}
public static Instruction[] FindInstrSeq(this MethodBody body, OpCode[] instrs, int amt)
{
Instruction[] result = new Instruction[amt];
for (int i = 0; i < result.Length; i++)
result[i] = i == 0 ? body.FindInstrSeqStart(instrs) : result[i - 1] != null ? result[i - 1].Next : null;
return result;
}
public static Instruction FindInstrSeqStart(this MethodBody body, OpCode[] instrs, int startIndex = 0)
{
for (int i = startIndex; i <= body.Instructions.Count - instrs.Length; i++)
{
for (int j = 0; j < instrs.Length; j++)
{
if (!CodeEqIgnoreS(body.Instructions[i + j].OpCode.Code, instrs[j].Code))
goto next_try;
}
return body.Instructions[i];
next_try:
;
}
return null;
}
public static void ReplaceInstructions(this ILProcessor p, IEnumerable<Instruction> orig, IEnumerable<Instruction> repl)
{
if (!orig.Chronological(null, i => i.Next) || !repl.Chronological(null, i => i.Next))
Console.Error.WriteLine("Error: Both sequences in CecilHelper.ReplaceInstructions(ILProcessor, IEnumerable<Instruction>, IEnumerable<Instruction>) must be chronological.");
Instruction firstOrig = orig.First();
foreach (var i in repl)
p.InsertBefore(firstOrig, i);
p.RemoveInstructions(orig);
}
public static Instruction RemoveInstructions(this ILProcessor p, IEnumerable<Instruction> instrs)
{
Instruction n = null;
foreach (var i in instrs)
{
n = i.Next;
p.Remove(i);
}
return n;
}
public static Instruction RemoveInstructions(this ILProcessor p, Instruction first, int count)
{
var cur = first;
for (int i = 0; i < count; i++)
{
if (cur == null)
break;
var n = cur.Next;
p.Remove(cur);
cur = n;
}
return cur;
}
// callee must have the same args as the calling method
// if the callee is an instance method, the object must be placed on the stack first
public static void EmitWrapperCall(this ILProcessor proc, MethodDefinition toCall, Instruction before = null)
{
//var caller = proc.Body.Method;
for (ushort i = 0; i < toCall.Parameters.Count /*+ (toCall.IsStatic ? 0 : 1)*/; i++)
if (before == null)
proc.Append(toCall.Parameters.GetLdargOf(i, !toCall.IsStatic/*false*/));
else
proc.InsertBefore(before, toCall.Parameters.GetLdargOf(i, !toCall.IsStatic/*false*/));
var c = toCall.IsVirtual ? OpCodes.Callvirt : OpCodes.Call;
if (before == null)
proc.Emit(c, toCall);
else
proc.InsertBefore(before, Instruction.Create(c, toCall));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using LitJson;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Prism.API.Behaviours;
using Prism.Mods;
using Prism.Mods.DefHandlers;
using Terraria;
namespace Prism.API.Defs
{
public partial class TileDef : EntityDef<TileBehaviour, Tile>
{
/* TODO:
* - Add TileAdj
* - Add TileMerge
* - Improve Tile Drop JSON read
*/
/// <summary>
/// Gets or sets the tile's texture function.
/// </summary>
public Func<Texture2D> GetTexture
{
get;
set;
}
/// <summary>
/// Gets or sets this tile's housing configuration.
/// </summary>
public TileHousingConfig HousingConfig
{
get;
set;
}
/// <summary>
/// Gets or sets this tile's mining configuration.
/// </summary>
public TileMineConfig MineConfig
{
get;
set;
}
/// <summary>
/// Gets or sets this tile's placement configuration.
/// </summary>
public TilePlaceConfig PlaceConfig
{
get;
set;
}
/// <summary>
/// Gets or sets this tile's lighting configuration.
/// </summary>
public TileLightingConfig LightingConfig
{
get;
set;
}
/// <summary>
/// Gets or sets this tile's lighting configuration.
/// </summary>
public TileFrameConfig FrameConfig
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile has collision.
/// </summary>
public bool Solid
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not the player can walk on this tile if it's non-solid. (such as tables, bookcases, etc.)
/// </summary>
public bool SolidTop
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile acts as a storage container
/// </summary>
public bool Chest
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should behave similarly to a rope.
/// </summary>
public bool Rope
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered part of the dungeon.
/// </summary>
public bool TileDungeon
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered a viable spawn point.
/// </summary>
public bool Spawn
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile is unaffected by explosions
/// </summary>
public bool ExplosionResistant
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile can be sloped
/// </summary>
public bool Slopable
{
get;
set;
}
/// <summary>
/// NeedsSummary
/// </summary>
public bool NoFail
{
get;
set;
}
/// <summary>
/// NeedsSummary
/// </summary>
/// <remarks>obsidianKill</remarks>
public bool ObsidianKill
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should behave similarly to a platform
/// </summary>
public bool Platform
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should behave similarly to a pile
/// </summary>
public bool Pile
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered bricks.
/// </summary>
public bool Brick
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered moss.
/// </summary>
public bool Moss
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered stone.
/// </summary>
public bool Stone
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not the tile should be considered grass frame-wise.
/// </summary>
public bool Grass
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered sand. (does not grant gravity to the tile)
/// </summary>
public bool TileSand
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile has a vanilla 'flame texture'. Almost all custom tiles will have this as false.
/// </summary>
public bool TileFlame
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile is considered a potion herb. Does nothing except change the default sound the tile makes.
/// </summary>
public bool AlchemyFlower
{
get;
set;
}
/// <summary>
/// The color the tile uses on the map.
/// </summary>
public Color MapColor
{
get;
set;
}
/// <summary>
/// The text used when the tile is hovered over.
/// </summary>
public string MapHoverText
{
get;
set;
}
public TileDef(string displayName, Func<TileBehaviour> newBehaviour = null, Func<Texture2D> getTexture = null)
: base(displayName, newBehaviour)
{
GetTexture = getTexture ?? (() => null);
}
public TileDef(string displayName, JsonData json, Func<TileBehaviour> newBehaviour = null, Func<Texture2D> getTexture = null)
: base(displayName, newBehaviour)
{
DisplayName = displayName;
GetTexture = getTexture ?? (() => null);
FrameConfig.TileWidth = json.Has("width") ? (int)json["width"] : 1;
FrameConfig.TileHeight = json.Has("height") ? (int)json["height"] : 1;
if (json.Has("size") && json["size"].IsArray && json["size"].Count >= 2 && json["size"][0].IsInt && json["size"][1].IsInt)
{
FrameConfig.TileWidth = (int)json["size"][0];
FrameConfig.TileHeight = (int)json["size"][1];
}
FrameConfig.FrameWidth = json.Has("frameWidth") ? (int)json["frameWidth"] : 16;
FrameConfig.FrameHeight = json.Has("frameHeight") ? (int)json["frameHeight"] : 16;
FrameConfig.DrawOffsetY = (int)json["drawOffsetY"];
Solid = (bool)json["solid"];
SolidTop = (bool)json["solidTop"];
FrameConfig.FrameImportant = (bool)json["frameImportant"];
PlaceConfig.Directional = (bool)json["directional"];
if (FrameConfig.FrameImportant)
PlaceConfig.PlacementFrame = new Point((int)json["placementFrameX"], (int)json["placementFrameY"]);
if (json.Has("placementConditions"))
{
switch (((string)json["placementConditions"]).ToLower())
{
case "air":
PlaceConfig.PlacementConditions = PlacementConditions.Air;
break;
case "wall":
PlaceConfig.PlacementConditions = PlacementConditions.Wall;
break;
case "placetouching":
PlaceConfig.PlacementConditions = PlacementConditions.PlaceTouching;
break;
case "placetouchingsolid":
PlaceConfig.PlacementConditions = PlacementConditions.PlaceTouchingSolid;
break;
case "side":
PlaceConfig.PlacementConditions = PlacementConditions.Side;
break;
case "flatground":
PlaceConfig.PlacementConditions = PlacementConditions.FlatGround;
break;
case "flatgroundsolid":
PlaceConfig.PlacementConditions = PlacementConditions.FlatGroundSolid;
break;
case "flatceiling":
PlaceConfig.PlacementConditions = PlacementConditions.FlatCeiling;
break;
case "flatceilingsolid":
PlaceConfig.PlacementConditions = PlacementConditions.FlatCeilingSolid;
break;
}
}
else if (FrameConfig.TileWidth == 1 && FrameConfig.TileHeight == 1)
PlaceConfig.PlacementConditions = PlacementConditions.PlaceTouchingSolid;
else
PlaceConfig.PlacementConditions = PlacementConditions.FlatGroundSolid;
PlaceConfig.CheckWalls = PlaceConfig.PlacementConditions == PlacementConditions.Wall;
// Only update checkWalls if JSON property exists
// so as to not overwrite assignment from PlacementConditions
// check above.
if (json.Has("checkWalls"))
PlaceConfig.CheckWalls = (bool)json["checkWalls"];
if (json.Has("placementOrigin") && json["placementOrigin"].IsArray && json["placementOrigin"].Count >= 2 && json["placementOrigin"][0].IsInt && json["placementOrigin"][1].IsInt)
{
var value = new Point((int)json["placementOrigin"][0], (int)json["placementOrigin"][1]);
if (value.X < 0)
value.X = 0;
if (value.Y < 0)
value.Y = 0;
if (value.X >= FrameConfig.TileWidth)
value.X = FrameConfig.TileWidth - 1;
if (value.Y >= FrameConfig.TileHeight)
value.Y = FrameConfig.TileHeight - 1;
PlaceConfig.PlacementOrigin = value;
}
FrameConfig.SheetYAligned = (bool)json["sheetYAligned"];
MineConfig.BreaksInstantly = (bool)json["breaksFast"];
MineConfig.BreaksByPick = (bool)json["breaksByPick"];
MineConfig.BreaksByAxe = (bool)json["breaksByAxe"];
MineConfig.BreaksByHammer = (bool)json["breaksByHammer"];
MineConfig.BreaksByCut = (bool)json["breaksByCut"];
MineConfig.BreaksByWater = (bool)json["breaksByWater"];
MineConfig.BreaksByLava = (bool)json["breaksByLava"];
ObsidianKill |= MineConfig.BreaksByLava;
MineConfig.MinPick = (int)json["minPick"];
MineConfig.MinAxe = (int)json["minAxe"];
MineConfig.MinHammer = (int)json["minHammer"];
MineConfig.RatePick = (float)json["ratePick"];
MineConfig.RateAxe = (float)json["rateAxe"];
MineConfig.RateHammer = (float)json["rateHammer"];
HousingConfig.IsTable = (bool)json["table"];
HousingConfig.IsChair = (bool)json["chair"];
HousingConfig.IsTorch = (bool)json["torch"];
HousingConfig.IsDoor = (bool)json["door"];
Chest = (bool)json["chest"];
Rope = (bool)json["rope"];
PlaceConfig.NoAttach = (bool)json["noAttach"];
TileDungeon = (bool)json["tileDungeon"];
Spawn = (bool)json["spawn"];
ExplosionResistant = (bool)json["explosionResistant"];
//TODO: AdjTile Resolver
Slopable = (bool)json["slopable"];
NoFail = (bool)json["noFail"];
ObsidianKill = (bool)json["obsidianKill"];
LightingConfig.BlocksLight = (bool)json["blocksLight"];
LightingConfig.BlocksSun = (bool)json["blocksSun"];
LightingConfig.Glows = (bool)json["glows"];
LightingConfig.Shines = (bool)json["shines"];
LightingConfig.ShineChance = (int)json["shineChance"];
FrameConfig.InitFrame = (int)json["frame"];
FrameConfig.MaxFrame = (int)json["frameMax"];
FrameConfig.FrameCounterMax = (int)json["frameCounterMax"];
LightingConfig.SpelunkerGlow = (bool)json["treasure"];
LightingConfig.DangersenseGlow = (bool)json["danger"];
Platform = (bool)json["platform"];
Pile = (bool)json["pile"];
Brick = (bool)json["brick"];
Moss = (bool)json["moss"];
Stone = (bool)json["stone"];
Grass = (bool)json["grass"];
PlaceConfig.MergesWithDirt = (bool)json["mergeDirt"];
FrameConfig.LargeFrames = (bool)json["largeFrames"];
TileSand = (bool)json["tileSand"];
TileFlame = (bool)json["tileFlame"];
AlchemyFlower = (bool)json["alchemyFlower"];
MineConfig.Sound = (int)json["sound"];
MineConfig.SoundGroup = (int)json["soundGroup"];
MineConfig.BreakDust = (int)json["dust"];
MapColor = json.Has("mapColor") && json["mapColor"].IsArray && json["mapColor"].Count >= 3 ?
new Color(((byte)((int)json["mapColor"][0])), ((byte)((int)json["mapColor"][1])), ((byte)((int)json["mapColor"][2])), ((json["mapColor"].Count <= 3) ? 255 : ((byte)((int)json["mapColor"][3])))) :
Color.Pink;
MapHoverText = json.Has("mapHoverText") ? (string)json["mapHoverText"] : DisplayName;
MineConfig.ItemDrop = json["drop"].IsInt ? new ItemRef((int)json["drop"]) : new ItemRef((string)json["drop"] /* mod name? */);
//TODO: Tile Merge Resolver
}
public static implicit operator TileRef(TileDef def)
{
return new TileRef(def.InternalName, def.Mod.InternalName);
}
public static explicit operator TileDef(TileRef @ref)
{
return @ref.Resolve();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API.Behaviours;
using Prism.Mods.Hooks;
using Terraria;
namespace Prism.Mods.BHandlers
{
public sealed class TileBHandler : EntityBHandler<TileBehaviour, Tile>
{
IEnumerable<Action> onUpdate;
public override void Create()
{
base.Create();
onUpdate = HookManager.CreateHooks<TileBehaviour, Action>(Behaviours, "OnUpdate");
}
public override void Clear ()
{
base.Clear ();
onUpdate = null;
}
public void OnUpdate()
{
HookManager.Call(onUpdate);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API.Audio;
using Prism.Mods.Hooks;
using Terraria;
namespace Prism.API.Behaviours
{
public abstract class GameBehaviour : IOBehaviour
{
/// <summary>
/// A hook called at the beginning of the game's Update method.
/// </summary>
[Hook]
public virtual void PreUpdate() { }
/// <summary>
/// A hook called at the end of the game's Update method.
/// </summary>
[Hook]
public virtual void PostUpdate() { }
/// <summary>
/// A hook called right after the game updates Main.keyState
/// </summary>
[Hook]
public virtual void OnUpdateKeyboard() { }
/// <summary>
/// A hook used to change the current music last-minute.
/// </summary>
/// <param name="current">The inner value can be changed.</param>
[Hook]
public virtual void UpdateMusic(Ref<BgmEntry> current) { }
#if DEV_BUILD
/// <summary>
/// Remember that this will only work on this dev build. Be sure to remove this override (or comment it out) and retarget to the release build before releasing the mod.
/// </summary>
[Hook]
public virtual void UpdateDebug() { }
#endif
}
}
<file_sep>using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Prism.API.Defs
{
public class TileFrameConfig
{
/// <summary>
/// The tile's per-tile frame width.
/// </summary>
public virtual int FrameWidth
{
get;
set;
}
/// <summary>
/// The tile's per-tile frame height.
/// </summary>
public virtual int FrameHeight
{
get;
set;
}
/// <summary>
/// The amount of tiles on the X axis this tile takes up.
/// </summary>
public virtual int TileWidth
{
get;
set;
}
/// <summary>
/// The amount of tiles on the Y axis this tile takes up.
/// </summary>
public virtual int TileHeight
{
get;
set;
}
/// <summary>
/// The draw offset of the tile on the Y axis. (Negative moves up, Positive moves down)
/// </summary>
public virtual int DrawOffsetY
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not to save the tile's frames.
/// </summary>
public virtual bool FrameImportant
{
get;
set;
}
/// <summary>
/// Gets or sets whether the tile's spritesheet has frames along the X or Y axis.
/// </summary>
public virtual bool SheetYAligned
{
get;
set;
}
/// <summary>
/// The start frame for the tile's animation.
/// </summary>
public virtual int InitFrame
{
get;
set;
}
/// <summary>
/// The maximum frame of the tile.
/// </summary>
public virtual int MaxFrame
{
get;
set;
}
/// <summary>
/// The maximum for the frame counter of the tile's animation.
/// </summary>
public virtual int FrameCounterMax
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile is considered as using large frames
/// </summary>
public virtual bool LargeFrames
{
get;
set;
}
}
public class TileLightingConfig
{
/// <summary>
/// Gets or sets whether or not this tile blocks light from passing through it.
/// </summary>
public virtual bool BlocksLight
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile blocks sunlight from passing through it.
/// </summary>
public virtual bool BlocksSun
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile glows in the dark. Make this true if this tile uses the hook ModifyLight.
/// </summary>
public virtual bool Glows
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile spawns sparkle dust if it is properly lit.
/// </summary>
public virtual bool Shines
{
get;
set;
}
/// <summary>
/// The chance of the sparkle. (Higher numbers == less chance)
/// </summary>
public virtual int ShineChance
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should glow if the player has Spelunker.
/// </summary>
public virtual bool SpelunkerGlow
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should glow if the player has Dangersense.
/// </summary>
public virtual bool DangersenseGlow
{
get;
set;
}
}
public class TileHousingConfig
{
/// <summary>
/// Gets or sets whether or not this tile should be considered a table. (Used in NPC Housing)
/// </summary>
public virtual bool IsTable
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered a chair. (Used in NPC Housing)
/// </summary>
public virtual bool IsChair
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered a torch. (Used in NPC Housing)
/// </summary>
public virtual bool IsTorch
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should be considered a door. (Used in NPC Housing)
/// </summary>
public virtual bool IsDoor
{
get;
set;
}
}
public class TileMineConfig
{
/// <summary>
/// The sound ID that this tile uses when it is killed.
/// </summary>
public virtual int Sound
{
get;
set;
}
/// <summary>
/// The soundGroup ID that this tile uses when it is killed.
/// </summary>
public virtual int SoundGroup
{
get;
set;
}
/// <summary>
/// The dust ID that this tile uses when it is mined or killed.
/// </summary>
public virtual int BreakDust
{
get;
set;
}
/// <summary>
/// The item this tile will drop when killed.
/// </summary>
public virtual ItemRef ItemDrop
{
get;
set;
}
/// <summary>
/// A multiplier for how fast the tile is mined by a pickaxe.
/// </summary>
public virtual float RatePick
{
get;
set;
}
/// <summary>
/// A multiplier for how fast the tile is mined by an axe.
/// </summary>
public virtual float RateAxe
{
get;
set;
}
/// <summary>
/// A multiplier for how fast the tile is mined by a hammer.
/// </summary>
public virtual float RateHammer
{
get;
set;
}
/// <summary>
/// The minimum pick value required to mine this tile.
/// </summary>
public virtual int MinPick
{
get;
set;
}
/// <summary>
/// The minimum axe value required to mine this tile.
/// </summary>
public virtual int MinAxe
{
get;
set;
}
/// <summary>
/// The minimum hammer value required to mine this tile.
/// </summary>
public virtual int MinHammer
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks immediately when hit.
/// </summary>
public virtual bool BreaksInstantly
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks from a pickaxe.
/// </summary>
public virtual bool BreaksByPick
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks from an axe.
/// </summary>
public virtual bool BreaksByAxe
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks from a hammer.
/// </summary>
public virtual bool BreaksByHammer
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks when hit by a melee weapon or projectile.
/// </summary>
public virtual bool BreaksByCut
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks when submerged in water or honey.
/// </summary>
public virtual bool BreaksByWater
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not a tile breaks when submerged in lava.
/// </summary>
public virtual bool BreaksByLava
{
get;
set;
}
}
public class TilePlaceConfig
{
/// <summary>
/// Gets or sets whether or not this tile should place the first or second frame based on player direction.
/// </summary>
public virtual bool Directional
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should check tile placement if walls behind it are broken.
/// </summary>
public virtual bool CheckWalls
{
get;
set;
}
/// <summary>
/// The specific X & Y frame of the tile to use when it is placed.
/// </summary>
public virtual Point PlacementFrame
{
get;
set;
}
/// <summary>
/// A preset condition used to determine if a tile can be placed or can stay in place.
/// </summary>
public virtual PlacementConditions PlacementConditions
{
get;
set;
}
/// <summary>
/// The tile within the tile that is considered the placement tile. (The tile the mouse is over when placing)
/// </summary>
public virtual Point PlacementOrigin
{
get;
set;
}
/// <summary>
/// Causes this tile to not be 'attachable' by other tiles. In other words, a tile that needs a placement condition checking this tile will always return false for this tile.
/// </summary>
public virtual bool NoAttach
{
get;
set;
}
/// <summary>
/// Gets or sets whether or not this tile should merge with dirt.
/// </summary>
public virtual bool MergesWithDirt
{
get;
set;
}
}
public enum PlacementConditions
{
Air,
FlatCeiling,
FlatCeilingSolid,
FlatGround,
FlatGroundSolid,
PlaceTouching,
PlaceTouchingSolid,
Side,
Wall
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using WfMsgBox = System.Windows.Forms.MessageBox;
namespace Prism
{
public static class MessageBox
{
public static void ShowError(string message)
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
case PlatformID.MacOSX:
try
{
WfMsgBox.Show(message, "Prism: Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch
{
if (Environment.OSVersion.Platform == PlatformID.MacOSX)
goto TRY_XMESSAGE;
}
break;
case PlatformID.Unix:
TRY_XMESSAGE:
bool tryConsole = false;
try
{
if (Process.Start("xmessage \"" + message.Replace('"', '\'') + "\"") == null)
tryConsole = true;
}
catch
{
tryConsole = true;
}
if (tryConsole)
try
{
Console.WriteLine(message);
}
catch (IOException) { }
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API.Behaviours;
using Prism.Mods.BHandlers;
using Terraria;
namespace Prism.API
{
public static class Extensions
{
static TWanted GetBehaviour<TBehaviour, TWanted>(IOBHandler<TBehaviour> handler)
where TBehaviour : IOBehaviour
where TWanted : TBehaviour
{
if (handler == null)
return null;
return (TWanted)handler.behaviours.FirstOrDefault(b => b is TWanted);
}
public static TBehaviour GetBuffBehaviour<TBehaviour>(this Player p, int index)
where TBehaviour : BuffBehaviour
{
if (p.P_BuffBHandler != null)
return GetBehaviour<BuffBehaviour, TBehaviour>(p.P_BuffBHandler[index] as BuffBHandler);
return null;
}
public static TBehaviour GetBuffBehaviour<TBehaviour>(this NPC n, int index)
where TBehaviour : BuffBehaviour
{
if (n.P_BuffBHandler != null)
return GetBehaviour<BuffBehaviour, TBehaviour>(n.P_BuffBHandler[index] as BuffBHandler);
return null;
}
public static TBehaviour GetBehaviour<TBehaviour>(this Item i )
where TBehaviour : ItemBehaviour
{
return GetBehaviour<ItemBehaviour, TBehaviour>(i.P_BHandler as ItemBHandler);
}
public static TBehaviour GetBehaviour<TBehaviour>(this Mount m )
where TBehaviour : MountBehaviour
{
var bh = m.P_BHandler as MountBHandler;
if (bh == null)
return null;
return (TBehaviour)bh.behaviours.FirstOrDefault(b => b is TBehaviour);
}
public static TBehaviour GetBehaviour<TBehaviour>(this NPC n )
where TBehaviour : NpcBehaviour
{
return GetBehaviour<NpcBehaviour, TBehaviour>(n.P_BHandler as NpcBHandler);
}
public static TBehaviour GetBehaviour<TBehaviour>(this Projectile pr)
where TBehaviour : ProjectileBehaviour
{
return GetBehaviour<ProjectileBehaviour, TBehaviour>(pr.P_BHandler as ProjBHandler);
}
public static TBehaviour GetBehaviour<TBehaviour>(this Player p )
where TBehaviour : PlayerBehaviour
{
return GetBehaviour<PlayerBehaviour, TBehaviour>(p.P_BHandler as PlayerBHandler);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Prism.API.Behaviours;
using Prism.API.Defs;
using Terraria;
using Terraria.ID;
using Terraria.Map;
namespace Prism.Mods.DefHandlers
{
//TODO: we might have to retink this, because tiles aren't quite like the other defs (except for RecipeDef, which is even more different and can be redone, too)
//TODO: fill arrays in Terraria.Map.MapHelper
sealed class TileDefHandler : EntityDefHandler<TileDef, TileBehaviour, Tile>
{
/*
Search done for any arrays created with tile count. There should be a lot more. Also the sets...:
Terraria\Main.cs(1005): public static bool[] tileLighted = new bool[419];
Terraria\Main.cs(1006): public static bool[] tileMergeDirt = new bool[419];
Terraria\Main.cs(1007): public static bool[] tileCut = new bool[419];
Terraria\Main.cs(1008): public static bool[] tileAlch = new bool[419];
Terraria\Main.cs(1009): public static int[] tileShine = new int[419];
Terraria\Main.cs(1010): public static bool[] tileShine2 = new bool[419];
Terraria\Main.cs(1015): public static bool[] tileStone = new bool[419];
Terraria\Main.cs(1016): public static bool[] tileAxe = new bool[419];
Terraria\Main.cs(1017): public static bool[] tileHammer = new bool[419];
Terraria\Main.cs(1018): public static bool[] tileWaterDeath = new bool[419];
Terraria\Main.cs(1019): public static bool[] tileLavaDeath = new bool[419];
Terraria\Main.cs(1020): public static bool[] tileTable = new bool[419];
Terraria\Main.cs(1021): public static bool[] tileBlockLight = new bool[419];
Terraria\Main.cs(1022): public static bool[] tileNoSunLight = new bool[419];
Terraria\Main.cs(1023): public static bool[] tileDungeon = new bool[419];
Terraria\Main.cs(1024): public static bool[] tileSpelunker = new bool[419];
Terraria\Main.cs(1025): public static bool[] tileSolidTop = new bool[419];
Terraria\Main.cs(1026): public static bool[] tileSolid = new bool[419];
Terraria\Main.cs(1027): public static bool[] tileBouncy = new bool[419];
Terraria\Main.cs(1028): public static short[] tileValue = new short[419];
Terraria\Main.cs(1029): public static byte[] tileLargeFrames = new byte[419];
Terraria\Main.cs(1031): public static bool[] tileRope = new bool[419];
Terraria\Main.cs(1032): public static bool[] tileBrick = new bool[419];
Terraria\Main.cs(1033): public static bool[] tileMoss = new bool[419];
Terraria\Main.cs(1034): public static bool[] tileNoAttach = new bool[419];
Terraria\Main.cs(1035): public static bool[] tileNoFail = new bool[419];
Terraria\Main.cs(1036): public static bool[] tileObsidianKill = new bool[419];
Terraria\Main.cs(1037): public static bool[] tileFrameImportant = new bool[419];
Terraria\Main.cs(1038): public static bool[] tilePile = new bool[419];
Terraria\Main.cs(1039): public static bool[] tileBlendAll = new bool[419];
Terraria\Main.cs(1040): public static short[] tileGlowMask = new short[419];
Terraria\Main.cs(1041): public static bool[] tileContainer = new bool[419];
Terraria\Main.cs(1042): public static bool[] tileSign = new bool[419];
Terraria\Main.cs(1043): public static bool[][] tileMerge = new bool[419][];
Terraria\Player.cs(580): public bool[] adjTile = new bool[419];
Terraria\Player.cs(581): public bool[] oldAdjTile = new bool[419];
Terraria\WorldGen.cs(567): public static int[] tileCounts = new int[419];
Terraria\WorldGen.cs(636): public static bool[] houseTile = new bool[419];
Terraria.Map\MapHelper.cs(118): Color[][] array = new Color[419][];
Terraria.Map\MapHelper.cs(953): MapHelper.tileOptionCounts = new int[419];
Terraria.Map\MapHelper.cs(982): MapHelper.tileLookup = new ushort[419];
*/
protected override Type IDContainerType
{
get
{
return typeof(TileID);
}
}
protected override void ExtendVanillaArrays(int amt = 1)
{
if (amt == 0)
return;
int newLen = amt > 0 ? Main.tileLighted.Length + amt : TileID.Count;
if (!Main.dedServ)
Array.Resize(ref Main.tileTexture, newLen);
Array.Resize(ref Main.tileLighted , newLen);
Array.Resize(ref Main.tileMergeDirt , newLen);
Array.Resize(ref Main.tileCut , newLen);
Array.Resize(ref Main.tileAlch , newLen);
Array.Resize(ref Main.tileShine , newLen);
Array.Resize(ref Main.tileShine2 , newLen);
Array.Resize(ref Main.tileStone , newLen);
Array.Resize(ref Main.tileAxe , newLen);
Array.Resize(ref Main.tileHammer , newLen);
Array.Resize(ref Main.tileWaterDeath , newLen);
Array.Resize(ref Main.tileLavaDeath , newLen);
Array.Resize(ref Main.tileTable , newLen);
Array.Resize(ref Main.tileBlockLight , newLen);
Array.Resize(ref Main.tileNoSunLight , newLen);
Array.Resize(ref Main.tileDungeon , newLen);
Array.Resize(ref Main.tileSpelunker , newLen);
Array.Resize(ref Main.tileSolidTop , newLen);
Array.Resize(ref Main.tileSolid , newLen);
Array.Resize(ref Main.tileBouncy , newLen);
Array.Resize(ref Main.tileValue , newLen);
Array.Resize(ref Main.tileLargeFrames , newLen);
Array.Resize(ref Main.tileRope , newLen);
Array.Resize(ref Main.tileBrick , newLen);
Array.Resize(ref Main.tileMoss , newLen);
Array.Resize(ref Main.tileNoAttach , newLen);
Array.Resize(ref Main.tileNoFail , newLen);
Array.Resize(ref Main.tileObsidianKill , newLen);
Array.Resize(ref Main.tileFrameImportant, newLen);
Array.Resize(ref Main.tilePile , newLen);
Array.Resize(ref Main.tileBlendAll , newLen);
Array.Resize(ref Main.tileGlowMask , newLen);
Array.Resize(ref Main.tileContainer , newLen);
Array.Resize(ref Main.tileSign , newLen);
Array.Resize(ref Main.tileMerge , newLen);
for (int i = 0; i < Main.tileMerge.Length; i++)
Array.Resize(ref Main.tileMerge[i], newLen);
}
protected override Tile GetVanillaEntityFromID(int id)
{
// Main.tile_ arrays must be used to get the properties
return new Tile()
{
type = (ushort)id
};
}
protected override TileDef NewDefFromVanilla(Tile tile)
{
return new TileDef(String.Empty, getTexture: () => Main.tileTexture[tile.type])
{
Type = tile.type,
NetID = tile.type
};
}
protected override string GetNameVanillaMethod(Tile tile)
{
return Lang.mapLegend[MapHelper.TileToLookup(tile.type, 0)] ?? String.Empty; //! might return empty string (if arr entry is null or empty)
}
protected override void CopyEntityToDef(Tile tile, TileDef def)
{
//def.Type = tile.type;
//def.HousingConfig.IsChair = null;
//def.HousingConfig.IsDoor = null;
//def.HousingConfig.IsTable = null;
//def.HousingConfig.IsTorch = null;
//def.PlaceConfig.CheckWalls = tile.;
//def.PlaceConfig.Directional = null;
//def.PlaceConfig.MergesWithDirt = null;
//def.PlaceConfig.NoAttach = null;
//def.PlaceConfig.PlacementConditions = null;
//def.PlaceConfig.PlacementFrame = null;
//def.PlaceConfig.PlacementOrigin = null;
//def.MineConfig.BreakDust = null;
//def.MineConfig.BreaksByAxe = null;
//def.MineConfig.BreaksByCut = null;
//def.MineConfig.BreaksByHammer = null;
//def.MineConfig.BreaksByLava = null;
//def.MineConfig.BreaksByPick = null;
//def.MineConfig.BreaksByWater = null;
//def.MineConfig.BreaksInstantly = null;
//def.MineConfig.ItemDrop = null;
//def.MineConfig.MinAxe = null;
//def.MineConfig.MinHammer = null;
//def.MineConfig.MinPick = null;
//def.MineConfig.RateAxe = null;
//def.MineConfig.RateHammer = null;
//def.MineConfig.RatePick = null;
//def.MineConfig.Sound = null;
//def.MineConfig.SoundGroup = null;
//def.LightingConfig.BlocksLight = null;
//def.LightingConfig.BlocksSun = null;
//def.LightingConfig.DangersenseGlow = null;
//def.LightingConfig.Glows = null;
//def.LightingConfig.ShineChance = null;
//def.LightingConfig.Shines = null;
//def.LightingConfig.SpelunkerGlow = null;
//def.FrameConfig.DrawOffsetY = null;
//def.FrameConfig.FrameCounterMax = null;
//def.FrameConfig.FrameHeight = null;
//def.FrameConfig.FrameImportant = null;
//def.FrameConfig.FrameWidth = null;
//def.FrameConfig.InitFrame = null;
//def.FrameConfig.LargeFrames = null;
//def.FrameConfig.MaxFrame = null;
//def.FrameConfig.SheetYAligned = null;
//def.FrameConfig.TileHeight = null;
//def.FrameConfig.TileWidth = null;
//def.AlchemyFlower = null;
//def.Brick = null;
//def.Chest = null;
//def.ExplosionResistant = null;
//def.Grass = null;
//def.MapColor = null;
//def.MapHoverText = null;
//def.Moss = null;
//def.NoFail = null;
//def.ObsidianKill = null;
//def.Pile = null;
//def.PlaceConfig = null;
//def.Platform = null;
//def.Rope = null;
//def.Slopable = null;
//def.Solid = null;
//def.SolidTop = null;
//def.Spawn = null;
//def.SpawnAt = null;
//def.Stone = null;
//def.TileDungeon = null;
//def.TileFlame = null;
//def.TileSand = null;
}
protected override void CopyDefToEntity(TileDef def, Tile tile)
{
tile.type = (ushort)def.Type;
}
protected override List<LoaderError> CheckTextures(TileDef def)
{
var ret = new List<LoaderError>();
if (def.GetTexture == null)
ret.Add(new LoaderError(def.Mod, "GetTexture of TileDef " + def + " is null."));
return ret;
}
protected override List<LoaderError> LoadTextures (TileDef def)
{
var ret = new List<LoaderError>();
var t = def.GetTexture();
if (t == null)
{
ret.Add(new LoaderError(def.Mod, "GetTexture return value is null for TileDef " + def + "."));
return ret;
}
Main.tileTexture[def.Type] = def.GetTexture();
Main.tileSetsLoaded[def.Type] = true;
return ret;
}
protected override int GetRegularType(Tile tile)
{
return tile.type;
}
protected override void CopySetProperties(TileDef def)
{
//TODO: finish this method
}
}
}
| 8321dfa9d69ff3385883daa3b38dc546a71c84b4 | [
"C#"
] | 14 | C# | Fruckert/Prism | bbe271655b71197ce6e2ade1da1815f8271b8cb7 | ba425326961722c74cfeae33fc058b65b7ae10d3 |
refs/heads/master | <repo_name>maheremad/Creating-A-Website-From-Preview-Html-Css-jQuery-Lv2<file_sep>/README.md
# Creating-A-Website-From-Preview-Html-Css-jQuery
Creating A Website From Preview [ Html, Css, jQuery ]
<file_sep>/scripts/index.js
$(function() {
// Add Class Active
$('.navbar .collapse ul li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
// Make The Slider Fill The Screen
let mySlider = $('.slider');
mySlider.height($(window).height());
$('.slider .overlay').height($(window).height());
$('.slider img').height($(window).height());
let carouselCaption = $('.carousel-caption');
$(window).resize(function() {
mySlider.height($(window).height());
$('.slider .overlay').height($(window).height());
$('.slider img').height($(window).height());
carouselCaption.css('padding-top', ($('.overlay').height() - carouselCaption.height()) / 2);
carouselCaption.css('padding-bottom', ($('.overlay').height() - carouselCaption.height()) / 2);
});
// Make The Carousel-Caption In The Center On Height
carouselCaption.css('padding-top', ($('.overlay').height() - carouselCaption.height()) / 2);
carouselCaption.css('padding-bottom', ($('.overlay').height() - carouselCaption.height()) / 2);
// Make The Name In Overlay In center
// $('.our-team .rightside div div .overlay p').css('padding-top', $('.our-team .rightside div div .overlay').height() / 2);
// Make Fade In
$('.our-team .rightside div div').hover(function() {
$(this).children('.overlay').fadeIn();
}, function() {
$(this).children('.overlay').fadeOut();
});
});
// Make Slider
$(function autoSlider() {
$('.whay-say .opp.active').each(function() {
if (!$(this).is(':last-of-type')) {
$(this).delay(3000).fadeOut('slow', function() {
$(this).removeClass('active').next('.opp').addClass('active').fadeIn();
autoSlider();
});
} else {
$(this).addClass('active').delay(3000).fadeIn('slow', function() {
$(this).removeClass('active').fadeOut('slow');
$('.whay-say .opp:eq(0)').addClass('active').fadeIn('slow');
autoSlider();
});
};
});
});
// Add Class Active To Buttons In Our Works
$('.our-works .mybuttons button').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
// Show The OverLay Images On Hover
$('.our-works .imgbox').hover(function() {
$(this).children('.overlay, .imgbox span').fadeIn();
}, function() {
$(this).children('.overlay, .imgbox span').fadeOut();
});
$('.our-works .gallery .works').hover(function() {
$(this).children('.overlay').fadeIn();
}, function() {
$(this).children('.overlay').fadeOut();
});
// Make Scrolled
$(document).ready(function() {
$('.navbar .navbar-nav li').click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).data('val')).offset().top
}, 600);
});
});
// Add Nice Padding When Hover On Links
$('.navbar .navbar-nav li').hover(function() {
$(this).animate({
paddingLeft: '5px'
}, 300)
}, function() {
$(this).animate({
paddingLeft: 0
}, 300)
}); | bcbdecff9e72c2ab861bdce6e302987488693e01 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | maheremad/Creating-A-Website-From-Preview-Html-Css-jQuery-Lv2 | e2e0fed057b0d1be078fe83d44ea6462eecd9e3c | 39a994ea0e115c877d67a895457e57c67d96a177 |
refs/heads/master | <file_sep>package com.sigtech.cctv;
import java.io.IOException;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class InternetManager extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... url) {
if(url.length <= 0)
return null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URI.create(url[0]));
try {
HttpResponse res = httpclient.execute(httppost);
res.getStatusLine();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return DataManager.getData(params[0]);
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
<file_sep>/****
* This is the Data Manager. It is where the most static data are located.
* */
package com.example.test2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class DataManager {
public static final String URL_UPLOAD = "http://malaysianvote.com/cservice/upload/";
public static String getData(String url) {
String line = null;
StringBuilder sb = new StringBuilder();
try {
URL urlCOnn = new URL(url);
InputStream is = urlCOnn.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static String postData(String url, List<NameValuePair> nameValuePairs) {
String resp = null;
StringBuilder sb = new StringBuilder();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
if (url == null)
url = "http://asfwan.dlinkddns.com/test/";
HttpPost httppost = new HttpPost(url);
try {
// Add your data - example
// nameValuePairs = new ArrayList<NameValuePair>(2);
// nameValuePairs.add(new BasicNameValuePair("test", "testdata"));
// setting namevaluepairs
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resp = reader.readLine()) != null) {
sb.append(resp);
Log.d("resp", resp);
}
resp = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
public static void showToast(Context ctxt, String txt) {
Toast.makeText(ctxt, txt, Toast.LENGTH_SHORT).show();
}
public static void showLongToast(Context ctxt, String txt) {
Toast.makeText(ctxt, txt, Toast.LENGTH_LONG).show();
}
public static String putData(String url, List<NameValuePair> nameValuePairs) {
String resp = null;
StringBuilder sb = new StringBuilder();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
if (url == null)
url = "http://asfwan.dlinkddns.com/test/";
HttpPut httpput = new HttpPut(url);
try {
// setting namevaluepairs
httpput.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpput);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resp = reader.readLine()) != null) {
sb.append(resp);
Log.d("resp", resp);
}
resp = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resp;
}
public static String deleteData(String url1) {
String line = "";
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(url1);
HttpURLConnection httpCon = (HttpURLConnection) url
.openConnection();
httpCon.setRequestMethod("DELETE");
InputStream is = httpCon.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>
//not used atm
package com.example.test2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class OptionActivity extends Activity implements OnClickListener {
Button b1, b2, b3, b4;
Spinner sp1;
EditText et1, et2, et3;
String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LOW_PROFILE);
setContentView(R.layout.option);
b1 = (Button) findViewById(R.id.bt1);
b2 = (Button) findViewById(R.id.bt2);
b3 = (Button) findViewById(R.id.bt3);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
sp1 = (Spinner) findViewById(R.id.spinner1);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.bt1){
url = et1.getText().toString();
MainActivity.url = url;
Toast.makeText(OptionActivity.this, url, Toast.LENGTH_SHORT).show();
}
if (id == R.id.bt2){
}
}
}
<file_sep>package com.example.test2;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class PageFragment extends Fragment implements OnClickListener {
Activity act;
static Context c;
boolean R1, R2, R3, RALL, S1, S2, S3 = false;
int index, num;
String url, url1, url2, url3, device;
String device_name[];
TextView tv;
ImageButton b, b2, b3, b4, b5, b6, b7;
Button bt1, bt2, bt3;
EditText et1, et2, et3;
Spinner s1, s2, sp1;
String pass = "<PASSWORD>";
ArrayAdapter<String> dataAdapter;
public static PageFragment newInstance(int index) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putInt("index", index);
pageFragment.setArguments(bundle);
return pageFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myfragment_layout, container,
false);
index = getArguments().getInt("index");
act = getActivity();
b = (ImageButton) view.findViewById(R.id.button1);
b2 = (ImageButton) view.findViewById(R.id.button2);
b3 = (ImageButton) view.findViewById(R.id.button3);
b4 = (ImageButton) view.findViewById(R.id.button4);
b5 = (ImageButton) view.findViewById(R.id.button5);
b6 = (ImageButton) view.findViewById(R.id.button7);
b7 = (ImageButton) view.findViewById(R.id.imagebutton2);
s1 = (Spinner) view.findViewById(R.id.spinner1);
s2 = (Spinner) view.findViewById(R.id.spinner2);
bt1 = (Button) view.findViewById(R.id.bt1);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> av, View v, int pos,
long arg3) {
url2 = (String) av.getItemAtPosition(pos);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
s2.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> av, View v, int pos,
long arg3) {
Resources res = getResources();
String[] funct = res.getStringArray(R.array.device);
url3 = funct[pos];
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
LayoutParams buttonParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
buttonParam.setMargins(0, 0, 0, 0);
// s1.setVisibility(View.GONE);
// s2.setLayoutParams(buttonParam);
if (index == 0) {
b.setImageResource(R.drawable.relay_off_170px);
b2.setImageResource(R.drawable.relay_off_170px);
b3.setImageResource(R.drawable.relay_off_170px);
b4.setImageResource(R.drawable.relay_alloff_170px);
b.setBackgroundColor(getResources().getColor(R.color.deepskyblue));
b2.setBackgroundColor(getResources().getColor(R.color.deepskyblue3));
b3.setBackgroundColor(getResources().getColor(R.color.deepskyblue3));
b7.setImageResource(R.drawable.sensor_icon);
Resources res = getResources();
device_name = res.getStringArray(R.array.function);
}
if (index == 1) {
b.setImageResource(R.drawable.lock_1_170px);
b2.setImageResource(R.drawable.siren_off_170px);
b3.setImageResource(R.drawable.light_off_170px);
b3.setLayoutParams(buttonParam);
b4.setVisibility(View.GONE);
b.setBackgroundColor(getResources().getColor(R.color.lblue));
b2.setBackgroundColor(getResources().getColor(R.color.purple));
b3.setBackgroundColor(getResources().getColor(R.color.soylentgreen));
b7.setImageResource(R.drawable.relay_icon);
RelativeLayout.LayoutParams rparam = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rparam.addRule(RelativeLayout.RIGHT_OF, 0);
b7.setLayoutParams(rparam);
RelativeLayout.LayoutParams rparam2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
rparam2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
b6.setLayoutParams(rparam2);
Resources res = getResources();
device_name = res.getStringArray(R.array.zone);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(act,
android.R.layout.simple_spinner_item, device_name);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(dataAdapter);
b.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
final int id = v.getId();
act = getActivity();
if (url1 == null || url1 == " ")
url1 = "192.168.1.29";
if (id == R.id.button1 && index == 0) {
if (!R1) {
b.setImageResource(R.drawable.relay_on_170px);
url = url1 + url2 + url3 + "_" + "auto=12";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b.setImageResource(R.drawable.relay_off_170px);
url = url1 + url2 + url3 + "_" + "auto=11";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
R1 = !R1;
}
if (id == R.id.button2 && index == 0) {
if (!R2) {
b2.setImageResource(R.drawable.relay_on_170px);
url = url1 + url2 + url3 + "_" + "auto=14";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b2.setImageResource(R.drawable.relay_off_170px);
url = url1 + url2 + url3 + "_" + "auto=13";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
R2 = !R2;
}
if (id == R.id.button3 && index == 0) {
if (!R3) {
b3.setImageResource(R.drawable.relay_on_170px);
url = url1 + url2 + url3 + "_" + "auto=16";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b3.setImageResource(R.drawable.relay_off_170px);
url = url1 + url2 + url3 + "_" + "auto=15";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
R3 = !R3;
}
if (id == R.id.button4 && index == 0) {
if (!RALL) {
b.setImageResource(R.drawable.relay_on_170px);
b2.setImageResource(R.drawable.relay_on_170px);
b3.setImageResource(R.drawable.relay_on_170px);
b4.setImageResource(R.drawable.relay_allon_170px);
url = url1 + url2 + url3 + "_" + "auto=18";
R1 = true;
R2 = true;
R3 = true;
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b.setImageResource(R.drawable.relay_off_170px);
b2.setImageResource(R.drawable.relay_off_170px);
b3.setImageResource(R.drawable.relay_off_170px);
b4.setImageResource(R.drawable.relay_alloff_170px);
url = url1 + url2 + url3 + "_" + "auto=17";
R1 = false;
R2 = false;
R3 = false;
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
RALL = !RALL;
}
if (R1 && R2 && R3) {
b4.setImageResource(R.drawable.relay_allon_170px);
RALL = true;
} else if ((!R1 && !R2 && !R3)) {
b4.setImageResource(R.drawable.relay_alloff_170px);
RALL = false;
}
if (id == R.id.button1 && index == 1) {
if (!S1) {
b.setImageResource(R.drawable.lock_2_170px);
url = url1 + url2 + url3 + "_" + "secure=22";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b.setImageResource(R.drawable.lock_1_170px);
url = url1 + url2 + url3 + "_" + "secure=21";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
S1 = !S1;
}
if (id == R.id.button2 && index == 1) {
if (!S2) {
b2.setImageResource(R.drawable.siren_on_170px);
url = url1 + url2 + url3 + "_" + "secure=24";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b2.setImageResource(R.drawable.siren_off_170px);
url = url1 + url2 + url3 + "_" + "secure=23";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
S2 = !S2;
}
if (id == R.id.button3 && index == 1) {
if (!S3) {
b3.setImageResource(R.drawable.light_on_170px);
url = url1 + url2 + url3 + "_" + "secure=26";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
} else {
b3.setImageResource(R.drawable.light_off_170px);
url = url1 + url2 + url3 + "_" + "secure=25";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
S3 = !S3;
}
if (id == R.id.button5 && index == 0) {
url = url1 + url2 + url3 + "_" + "auto=19";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
}
if (id == R.id.button5 && index == 1) {
url = url1 + url2 + url3 + "_" + "secure=27";
if (ConnectionChecker.checkConnection(act)) {
if (!url.contains("http"))
url = "http://" + url;
new InternetManager2().execute(url);
}
Animation animation = AnimationUtils.loadAnimation(getActivity(),
R.anim.rotate_around_center);
b5.startAnimation(animation);
}
if (id == R.id.button7) {
LayoutInflater inflater = getActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(act);
View view = inflater.inflate(R.layout.option, null);
builder.setTitle("Setting");
builder.setNegativeButton("back",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
PageFragment.this.onDetach();
}
});
tv = (TextView) view.findViewById(R.id.url1);
bt1 = (Button) view.findViewById(R.id.bt1);
bt2 = (Button) view.findViewById(R.id.bt2);
bt3 = (Button) view.findViewById(R.id.bt3);
et1 = (EditText) view.findViewById(R.id.editText1);
et2 = (EditText) view.findViewById(R.id.editText2);
et3 = (EditText) view.findViewById(R.id.editText3);
sp1 = (Spinner) view.findViewById(R.id.spinner1);
tv.setText("Current URL : " + url1);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
url1 = et1.getText().toString();
tv.setText("Current URL : " + url1);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> av, View v, int pos,
long arg3) {
num = pos;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// spinner setting, still buggy
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(act,
android.R.layout.simple_spinner_item, device_name);
sp1.setAdapter(dataAdapter);
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
device_name[num] = et2.getText().toString();
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(
act, android.R.layout.simple_spinner_item,
device_name);
sp1.setAdapter(dataAdapter2);
s2.setAdapter(dataAdapter2);
et2.setText("");
}
});
bt3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(act, url, Toast.LENGTH_SHORT).show();
}
});
builder.setView(view).show();
// startActivity(new Intent(act, OptionActivity.class));
}
Toast.makeText(act, url, Toast.LENGTH_SHORT).show();
}
} | bea36a75d96406510f6de07df84ab8408b60a07f | [
"Java"
] | 4 | Java | ahmad4zan/HomePanel | 523f2dc2ac547065c3306aa8c40ef90848975404 | 8ab3ca839d67073f3fa7160236cfe35c4829e28a |
refs/heads/master | <file_sep># c_programing_language
c程序设计语言(第2版)练习 20170825 07:00
<file_sep>#include <stdio.h> //包含标准输入输出库的信息
main(){ // main函数
printf("hello world\n\c\n\n"); // 双引号中的内容 -> 字符串(字符串常量) \n 换行符(转移字符序列) \c 输出普通字符
/* 注释
*/
int fahr, celsius;
int lower, upper, step;
lower = 100;
upper = 300;
step = 20;
fahr = lower;
while(fahr <= upper){
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr += step;
}
}
<file_sep>#include <stdio.h>
main(){
printf("℉ to ℃\n\n");
float fahr, celsius;
int lower, upper, step;
lower = 100;
upper = 300;
step = 20;
fahr = lower;
while(fahr <= upper){
celsius = 5 * (fahr-32) / 9;
printf("%3.0f %6.1f\n", fahr, celsius);
// %3.0f -> 待打印浮点数至少占3个字符宽,且不带小数点和小数部分 ;
// %6.1f -> 待打印浮点数至少占6个字符宽,且小数点后有1位数字 ;
fahr += step;
}
printf("\n\n\n\n\n\n");
printf("℃ to ℉\n");
fahr = lower;
while(fahr <= upper){
celsius = fahr * 9 / 5 + 32;
printf("%3.0f %6.1f\n", fahr, celsius);
fahr += step;
}
}
| 85a2bc95bf8e2e9d8c4e31e34a863675fe863a9d | [
"Markdown",
"C"
] | 3 | Markdown | gijonhoo/c_programing_language | 59d772a3a9b6e61118d283bb98aa9ca27a299f41 | 16a080049dcef966cc6add865b300730c564545a |
refs/heads/master | <repo_name>Fran6nd/ascii-drawer<file_sep>/src/edit_modes/line_mode.c
#include <curses.h>
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "position_list.h"
#include "ui.h"
#include "undo_redo.h"
position_list PATH;
static void on_key_event(edit_mode *em, int c)
{
position delta = move_cursor(c);
if (!delta.null)
{
if (PATH.size != 0)
{
position previous_pos = {.x = get_cursor_pos().x - delta.x, .y = get_cursor_pos().y - delta.y, .null = 0};
position p_min = pos_min(previous_pos, get_cursor_pos());
position p_max = pos_max(previous_pos, get_cursor_pos());
while (delta.x < 0)
{
delta.x++;
position tmp = get_cursor_pos();
tmp.x = tmp.x + delta.x;
while (pl_is_inside(&PATH, tmp) != -1)
{
pl_remove_last(&PATH);
}
pl_add(&PATH, tmp);
}
while (delta.y < 0)
{
delta.y++;
position tmp = get_cursor_pos();
tmp.y = tmp.y + delta.y;
while (pl_is_inside(&PATH, tmp) != -1)
{
pl_remove_last(&PATH);
}
pl_add(&PATH, tmp);
}
while (delta.x > 0)
{
delta.x--;
position tmp = get_cursor_pos();
tmp.x = tmp.x + delta.x;
while (pl_is_inside(&PATH, tmp) != -1)
{
pl_remove_last(&PATH);
}
pl_add(&PATH, tmp);
}
while (delta.y > 0)
{
delta.y--;
position tmp = get_cursor_pos();
tmp.y = tmp.y + delta.y;
while (pl_is_inside(&PATH, tmp) != -1)
{
pl_remove_last(&PATH);
}
pl_add(&PATH, tmp);
}
}
}
else if (c == ' ')
{
if (PATH.size != 0)
{
int i;
do_change(&CURRENT_FILE);
for (i = 0; i < PATH.size; i++)
{
chk_set_char_at(&CURRENT_FILE, PATH.list[i],
pl_get_arrow_char(&PATH, i));
}
pl_empty(&PATH);
PATH = pl_new();
}
else
{
pl_add(&PATH, get_cursor_pos());
}
}
}
static char *get_help(edit_mode *self)
{
return "You are in the LINE mode.\n"
"You can use [space] to select the first point\n"
"and then [space] again to select the second point\n"
"and draw the line!\n"
"\n"
"Press any key to continue.";
}
static void on_free(edit_mode *self) { pl_empty(&PATH); }
static character on_draw(edit_mode *self, position p, character c)
{
int i = pl_is_inside(&PATH, p);
if (i != -1)
{
c.c = pl_get_line_char(&PATH, i);
}
return c;
}
static void on_left_column_add(edit_mode *self)
{
int i = 0;
for (i = 0; i < PATH.size; i++)
{
PATH.list[i].x++;
}
if (PATH.size != 0)
pl_add(&PATH, get_cursor_pos());
}
static void on_top_line_add(edit_mode *self)
{
int i = 0;
for (i = 0; i < PATH.size; i++)
{
PATH.list[i].y++;
}
if (PATH.size != 0)
pl_add(&PATH, get_cursor_pos());
}
static int on_abort(edit_mode *self)
{
if (PATH.size != 0)
{
pl_empty(&PATH);
return 1;
}
return 0;
}
edit_mode line_mode()
{
edit_mode EDIT_MODE_RECT = {.name = "LINE",
.key = (int)'l',
.on_key_event = on_key_event,
.on_free = on_free,
.on_draw = on_draw,
.on_top_line_add = on_top_line_add,
.on_left_column_add = on_left_column_add,
.on_abort = on_abort,
.get_help = get_help,
.null = 0};
return EDIT_MODE_RECT;
}<file_sep>/src/edit_modes/plugin_mode.c
#include "edit_mode.h"
#include "ui.h"
#include "undo_redo.h"
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
static int l_set_char_at(lua_State *L) {
/* Keep only two firsts args. */
lua_settop(L, 2);
/* Let's check our args types. */
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checktype(L, 2, LUA_INT_TYPE);
/* Now we read table.x and table.y */
position p;
lua_getfield(L, 1, "x");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.x = lua_tointeger(L, -1);
lua_getfield(L, 1, "y");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.y = lua_tointeger(L, -1);
/* Now we read the int value ofthe char to draw. */
int c = lua_tointeger(L, 2);
/* Now let's pop p.x, p.y and the character from the stack. */
lua_pop(L, 3);
/* Now let's call the C func. */
chk_set_char_at(&CURRENT_FILE, p, c);
/* number of results */
return 0;
}
static int l_get_char_at(lua_State *L) {
lua_settop(L, 1);
luaL_checktype(L, 1, LUA_TTABLE);
position p;
lua_getfield(L, 1, "x");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.x = lua_tointeger(L, -1);
lua_getfield(L, 1, "y");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.y = lua_tointeger(L, -1);
/* Let's pop .x and .y from the stack. */
lua_pop(L, 2);
/* Let's push on the stack the returned value. */
lua_pushnumber(L, chk_get_char_at(&CURRENT_FILE, p));
return 1;
}
static int l_do_change(lua_State *L) {
do_change(&CURRENT_FILE);
return 0;
}
static int l_show_message(lua_State *L) {
lua_tostring(L, 1);
luaL_checktype(L, 1, LUA_TSTRING);
ui_show_text((char *)lua_tostring(L, 1));
return 0;
}
static int l_show_message_blocking(lua_State *L) {
lua_tostring(L, 1);
luaL_checktype(L, 1, LUA_TSTRING);
ui_show_text_info((char *)lua_tostring(L, 1));
return 0;
}
static int l_move_cursor(lua_State *L) {
luaL_checktype(L, 1, LUA_INT_TYPE);
position p = move_cursor(lua_tointeger(L, 1));
if (p.null)
return 0;
lua_newtable(L);
lua_pushinteger(L, p.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, p.y);
lua_setfield(L, -2, "y");
return 1;
}
static int l_get_cursor_pos(lua_State *L) {
lua_newtable(L);
lua_pushinteger(L, get_cursor_pos().x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, get_cursor_pos().y);
lua_setfield(L, -2, "y");
return 1;
}
static int l_set_cursor_pos(lua_State *L) {
/* Let's read the position given as argument. */
lua_settop(L, 1);
luaL_checktype(L, 1, LUA_TTABLE);
position p;
lua_getfield(L, 1, "x");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.x = lua_tointeger(L, -1);
lua_getfield(L, 1, "y");
luaL_checktype(L, -1, LUA_INT_TYPE);
p.y = lua_tointeger(L, -1);
/* Let's pop .x and .y from the stack. */
lua_pop(L, 2);
/* Let's calculate the new pos. */
position delta = {.x = get_cursor_pos().x - UP_LEFT_CORNER.x,
.y = get_cursor_pos().y - UP_LEFT_CORNER.y};
p.x -= delta.x;
p.y -= delta.y;
UP_LEFT_CORNER.x = p.x;
UP_LEFT_CORNER.y = p.y;
return 0;
}
static void bind(lua_State *L) {
/* Let's push all tools */
lua_pushcfunction(L, l_do_change);
lua_setglobal(L, "do_change");
lua_pushcfunction(L, l_set_char_at);
lua_setglobal(L, "set_char_at");
lua_pushcfunction(L, l_get_char_at);
lua_setglobal(L, "get_char_at");
lua_pushcfunction(L, l_move_cursor);
lua_setglobal(L, "move_cursor");
lua_pushcfunction(L, l_show_message);
lua_setglobal(L, "show_message");
lua_pushcfunction(L, l_show_message_blocking);
lua_setglobal(L, "show_message_blocking");
lua_pushcfunction(L, l_get_cursor_pos);
lua_setglobal(L, "get_cursor_pos");
lua_pushcfunction(L, l_set_cursor_pos);
lua_setglobal(L, "set_cursor_pos");
/* Let's push all colors. */
lua_pushinteger(L, COL_SELECTION);
lua_setglobal(L, "COL_SELECTION");
lua_pushinteger(L, COL_EMPTY);
lua_setglobal(L, "COL_EMPTY");
lua_pushinteger(L, COL_NORMAL);
lua_setglobal(L, "COL_NORMAL");
}
static void on_key_event(edit_mode *em, int c) {
lua_State *L = (lua_State *)em->data;
lua_getglobal(L, "on_key_event");
if (lua_isnil(L, 1)) {
lua_pop(L, 1);
} else {
if (lua_isfunction(L, 1)) {
lua_pushnumber(L, c);
if (lua_pcall(L, 1, 0, 0)
/* pops the function and 0 parameters, pushes 0 results */) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run on_key_event: %s\n",
lua_tostring(L, -1));
ui_show_text_info(buffer);
}
}
}
}
static char *get_help(edit_mode *em) {
lua_State *L = (lua_State *)em->data;
lua_getglobal(L, "get_help");
if (lua_isnil(L, 1)) {
lua_pop(L, 1);
} else {
if (lua_isfunction(L, 1)) {
if (lua_pcall(L, 0, 1, 0)) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run get_help: %s\n", lua_tostring(L, -1));
ui_show_text_info(buffer);
}
}
if (lua_isstring(L, 1)) {
char *output = (char *)lua_tostring(L, 1);
lua_pop(L, 1);
return output;
}
lua_pop(L, 1);
}
return "No help available.";
}
static void on_free(edit_mode *em) { lua_close((lua_State *)em->data); }
static character on_draw(edit_mode *em, position p, character c) {
lua_State *L = (lua_State *)em->data;
lua_getglobal(L, "on_draw");
if (lua_isnil(L, 1)) {
lua_pop(L, 1);
} else {
if (!lua_isnil(L, 1) && lua_isfunction(L, 1)) {
lua_newtable(L);
lua_pushinteger(L, p.x);
lua_setfield(L, -2, "x");
lua_pushinteger(L, p.y);
lua_setfield(L, -2, "y");
lua_newtable(L);
lua_pushinteger(L, c.c);
lua_setfield(L, -2, "character");
lua_pushinteger(L, c.color);
lua_setfield(L, -2, "color");
if (lua_pcall(L, 2, 1, 0)) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run [on_draw]: %s\n", lua_tostring(L, -1));
ui_show_text_info(buffer);
}
if (lua_istable(L, -1)) {
lua_getfield(L, -1, "character");
c.c = lua_tointeger(L, -1);
lua_pop(L, 1);
lua_getfield(L, -1, "color");
c.color = lua_tointeger(L, -1);
lua_pop(L, 1);
}
lua_pop(L, -1);
}
}
return c;
}
static void on_left_column_add(edit_mode *em) {
lua_State *L = (lua_State *)em->data;
lua_getglobal(L, "on_left_column_add");
if (lua_isnil(L, 1)) {
lua_pop(L, 1);
} else {
if (lua_pcall(L, 0, 0, 0)) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run [on_left_column_add]: %s\n",
lua_tostring(L, -1));
ui_show_text_info(buffer);
}
}
}
static void on_top_line_add(edit_mode *em) {
lua_State *l = (lua_State *)em->data;
lua_getglobal(l, "on_top_line_add");
if (lua_isnil(l, 1)) {
lua_pop(l, 1);
} else {
if (lua_pcall(l, 0, 0, 0)) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run [on_top_line_add]: %s\n",
lua_tostring(l, -1));
ui_show_text_info(buffer);
}
}
}
static int on_abort(edit_mode *em) { return 0; }
/* Function called from edit_mode.c for any LUA extension:
* It builds the struct edit_mode, load and bind the script.
*/
edit_mode plugin_mode(char *path) {
edit_mode EDIT_MODE_PLUGIN = {.on_key_event = on_key_event,
.on_free = on_free,
.on_draw = on_draw,
.on_left_column_add = on_left_column_add,
.on_top_line_add = on_top_line_add,
.on_abort = on_abort,
.get_help = get_help};
lua_State *L = luaL_newstate();
EDIT_MODE_PLUGIN.data = (void *)L;
int status = luaL_loadfile(L, path);
if (status) {
char buffer[500] = {0};
sprintf(buffer, "Couldn't load file: %s\n", lua_tostring(L, -1));
ui_show_text_info(buffer);
EDIT_MODE_PLUGIN.null = 1;
return EDIT_MODE_PLUGIN;
} else {
/* Loading all the std lib, disbling io and os for safety purpose. */
luaL_openlibs(L);
lua_pushnil(L);
lua_setglobal(L, "os");
lua_pushnil(L);
lua_setglobal(L, "io");
/* Ask Lua to run our little script */
int result = lua_pcall(L, 0, LUA_MULTRET, 0);
if (result) {
char buffer[500] = {0};
sprintf(buffer, "Failed to run script: %s\n", lua_tostring(L, -1));
ui_show_text_info(buffer);
EDIT_MODE_PLUGIN.null = 1;
return EDIT_MODE_PLUGIN;
} else {
bind(L);
lua_getglobal(L, "NAME");
if (lua_isnil(L, 1)) {
goto error;
} else {
EDIT_MODE_PLUGIN.name = (char *)lua_tostring(L, 1);
lua_pop(L, 1);
lua_getglobal(L, "KEY");
if (lua_isnil(L, 1)) {
goto error;
} else {
EDIT_MODE_PLUGIN.key = lua_tointeger(L, 1);
lua_pop(L, 1);
return EDIT_MODE_PLUGIN;
}
}
}
error:
lua_pop(L, 1);
EDIT_MODE_PLUGIN.null = 1;
EDIT_MODE_PLUGIN.on_free(&EDIT_MODE_PLUGIN);
char buf[100] = {0};
sprintf(buf, "Error:\nCannot load script:\n%s\nMissing NAME or KEY", path);
ui_show_text_info(buf);
return EDIT_MODE_PLUGIN;
}
}<file_sep>/src/main.c
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "chunk.h"
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "position_list.h"
#include "ui.h"
#include "undo_redo.h"
char *NAME = "Untitled.txt";
position UP_LEFT_CORNER = {0, 0};
chunk CURRENT_FILE;
edit_mode *EDIT_MODE;
edit_mode *PREVIOUS_EDIT_MODE;
position get_cursor_pos() {
position tmp = {UP_LEFT_CORNER.x + COLS / 2,
UP_LEFT_CORNER.y + (LINES - 2) / 2};
return tmp;
}
void clear_screen() {
int x;
for (x = 0; x < COLS; x++) {
int y;
for (y = 0; y < LINES; y++) {
move(y, x);
addch(' ');
}
}
}
int is_writable(char c) {
char *charset =
"azertyuiopqsdfghjklmwxcvbn?,.;/"
":§!\\`_-'+*#=()[]{}^$&1234567890AZERTYUIOPQSDFGHJKLMWXCVBN <>éèç&$@\"";
int i;
for (i = 0; i < strlen(charset); i++) {
if (charset[i] == c)
return 1;
}
return 0;
}
/* To know whether or not if a char is par of a diagram. */
int is_diag_char(char c) {
if (c == '|' || c == '+' || c == '-' || c == '<' || c == '>' || c == '^' ||
c == 'v') {
return 1;
}
return 0;
}
void draw_char(position p, char c, int col) {
attron(COLOR_PAIR(col));
move(p.y, p.x);
addch(c);
attroff(COLOR_PAIR(col));
}
void draw_file() {
int x;
for (x = 0; x < COLS; x++) {
int y;
for (y = 1; y < LINES; y++) {
position pos_on_screen = {x, y};
position p = {x, y - 2};
p.x += UP_LEFT_CORNER.x;
p.y += UP_LEFT_CORNER.y;
character c = {.c = chk_get_char_at(&CURRENT_FILE, p),
.color = COL_NORMAL};
if (c.c != 0) {
if (EDIT_MODE) {
if (EDIT_MODE->on_draw)
c = EDIT_MODE->on_draw(EDIT_MODE, p, c);
}
if (pos_on_screen.x == COLS / 2 && pos_on_screen.y == (LINES + 2) / 2) {
c.color = COL_CURSOR;
}
draw_char(pos_on_screen, c.c, c.color);
} else {
draw_char(pos_on_screen, ' ', COL_EMPTY);
}
}
}
}
void draw() {
draw_file();
position ui_zero = {0, 0};
position ui_max = {COLS - 1, LINES - 1};
ui_draw_rect(ui_zero, ui_max);
refresh();
move(0, 2);
addstr("TUI-DiagDrawer by Fran6nd (press [tab] to switch mode)");
}
position move_cursor(int c) {
const char *key_name = keyname(c);
position delta = UP_LEFT_CORNER;
int i;
if (strcmp(key_name, "KEY_UP") == 0) {
UP_LEFT_CORNER.y--;
} else if (strcmp(key_name, "KEY_DOWN") == 0) {
UP_LEFT_CORNER.y++;
} else if (strcmp(key_name, "KEY_RIGHT") == 0) {
UP_LEFT_CORNER.x++;
} else if (strcmp(key_name, "KEY_LEFT") == 0) {
UP_LEFT_CORNER.x--;
}
/* If ctrl key is pressed: we move faster. */
else if (strcmp(key_name, "kUP5") == 0) {
for (i = 1; i < 6; i++) {
UP_LEFT_CORNER.y--;
if (i != 1 && chk_get_char_at(&CURRENT_FILE, get_cursor_pos()) != ' ' &&
i < 6) {
UP_LEFT_CORNER.y++;
}
}
} else if (strcmp(key_name, "kDN5") == 0) {
for (i = 1; i < 6; i++) {
UP_LEFT_CORNER.y++;
if (i != 1 && chk_get_char_at(&CURRENT_FILE, get_cursor_pos()) != ' ' &&
i < 6) {
UP_LEFT_CORNER.y--;
}
}
} else if (strcmp(key_name, "kRIT5") == 0) {
for (i = 1; i < 6; i++) {
UP_LEFT_CORNER.x++;
if (i != 1 && chk_get_char_at(&CURRENT_FILE, get_cursor_pos()) != ' ' &&
i < 6) {
UP_LEFT_CORNER.x--;
}
}
} else if (strcmp(key_name, "kLFT5") == 0) {
for (i = 1; i < 6; i++) {
UP_LEFT_CORNER.x--;
if (i != 1 && chk_get_char_at(&CURRENT_FILE, get_cursor_pos()) != ' ' &&
i < 6) {
UP_LEFT_CORNER.x++;
}
}
} else {
delta.null = 1;
return delta;
}
delta.null = 0;
delta.x = delta.x - UP_LEFT_CORNER.x;
delta.y = delta.y - UP_LEFT_CORNER.y;
return delta;
}
int main(int argc, char *argv[]) {
initscr();
curs_set(0);
noecho();
start_color();
keypad(stdscr, TRUE);
register_modes();
EDIT_MODE = &modes[0];
PREVIOUS_EDIT_MODE = EDIT_MODE;
init_pair(COL_CURSOR, COLOR_WHITE, COLOR_RED);
init_pair(COL_NORMAL, COLOR_WHITE, COLOR_BLACK);
init_pair(COL_EMPTY, COLOR_BLACK, COLOR_BLUE);
init_pair(COL_SELECTION, COLOR_BLACK, COLOR_CYAN);
if (argc != 2)
CURRENT_FILE = chk_new(COLS - 2, LINES - 2);
else {
CURRENT_FILE = chk_new_from_file(argv[1]);
NAME = argv[1];
}
int looping = 1;
do_change(&CURRENT_FILE);
while (looping) {
while (get_cursor_pos().x < 0) {
chk_add_col_left(&CURRENT_FILE);
int i;
for (i = 0; i < edit_mode_counter; i++) {
if (modes[i].on_left_column_add != NULL) {
modes[i].on_left_column_add(&modes[i]);
}
}
UP_LEFT_CORNER.x++;
}
while (get_cursor_pos().y < 0) {
int i;
chk_add_line_up(&CURRENT_FILE);
for (i = 0; i < edit_mode_counter; i++) {
if (modes[i].on_top_line_add != NULL) {
modes[i].on_top_line_add(&modes[i]);
}
}
UP_LEFT_CORNER.y++;
}
while (get_cursor_pos().y >= CURRENT_FILE.lines) {
chk_add_line_down(&CURRENT_FILE);
}
while (get_cursor_pos().x >= CURRENT_FILE.cols) {
chk_add_col_right(&CURRENT_FILE);
}
draw();
int c = getch();
{
/* [tab] = MENU */
if (c == '\t') {
ui_show_text(get_menu());
PREVIOUS_EDIT_MODE = EDIT_MODE;
if (EDIT_MODE->on_abort)
EDIT_MODE->on_abort(EDIT_MODE);
EDIT_MODE = NULL;
do {
c = getch();
switch ((char)c) {
case 'q':
looping = 0;
break;
case 'w':
chk_save_to_file(&CURRENT_FILE, NAME);
break;
case 'x':
chk_save_to_file(&CURRENT_FILE, NAME);
looping = 0;
break;
case '\t':
EDIT_MODE = PREVIOUS_EDIT_MODE;
break;
case '\033':
getch();
getch();
break;
default:
EDIT_MODE = get_edit_mode(c);
break;
}
} while (EDIT_MODE == NULL && looping == 1);
}
/*[Ctrl] + [u] = UNDO */
else if (c == K_UNDO) {
/* If we are doing something, we abort it. */
int aborted = 0;
if (EDIT_MODE->on_abort) {
aborted = EDIT_MODE->on_abort(EDIT_MODE);
}
/* Else we undo the last change. */
if (!aborted) {
undo_change(&CURRENT_FILE);
}
}
/* [ctrl] + r = REDO */
else if (c == K_REDO) {
if (EDIT_MODE->on_abort) {
EDIT_MODE->on_abort(EDIT_MODE);
}
redo_change(&CURRENT_FILE);
}
/* [ctrl] + h = HELP */
else if (c == K_HELP) {
if (EDIT_MODE->get_help) {
ui_show_text_info(EDIT_MODE->get_help(EDIT_MODE));
}
}
else {
/* If no major key pressed, we now do things depending on selected mod.
*/
if (EDIT_MODE != NULL) {
if (EDIT_MODE->on_key_event != NULL)
EDIT_MODE->on_key_event(EDIT_MODE, c);
}
}
}
}
endwin();
chk_free(&CURRENT_FILE);
free_undo_redo();
edit_mode_free();
return 0;
}<file_sep>/src/edit_modes/put_mode.c
#include <curses.h>
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "ui.h"
#include "undo_redo.h"
static void on_key_event(edit_mode *self, int c) {
if (move_cursor(c).null) {
if (is_writable(c)) {
position tmp = get_cursor_pos();
chk_set_char_at(&CURRENT_FILE, tmp, c);
}
}
}
static char *get_help(edit_mode *self) {
return "You are in the PUT mode.\n"
"Press a key and it will fill the selected character.\n"
"\n"
"Press any key to continue.";
}
edit_mode put_mode() {
edit_mode EDIT_MODE_PUT = {.name = "PUT",
.key = (int)'p',
.on_key_event = on_key_event,
.get_help = get_help,
.null = 0};
return EDIT_MODE_PUT;
}<file_sep>/src/edit_mode.c
#include <curses.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "edit_mode.h"
#include "ui.h"
struct edit_mode *modes;
int edit_mode_counter;
char menu_buffer[10000] = {0};
/* Here we add an edit_mode after checking if there is no conflicts with the key
* used. */
void register_mode(edit_mode em) {
if (!em.null) {
int i;
for (i = 0; i < edit_mode_counter; i++) {
if (modes[i].key == em.key) {
/*
* We do not register the edit_mode if the key is already taken.
*
* It allows us to override built-ins edit_modes with LUA plugins.
*
*/
return;
}
}
if (edit_mode_counter == 0) {
modes = malloc(1 * sizeof(edit_mode));
modes[0] = em;
} else {
modes = (edit_mode *)realloc(modes,
sizeof(edit_mode) * (edit_mode_counter + 1));
modes[edit_mode_counter] = em;
}
edit_mode_counter++;
}
}
/* Here we register all edit modes that are gonna be availables. */
void register_modes() {
/* Let's register our Lua plugins. */
{
char *dir = "/.tui-diagdrawer";
char path[100] = {0};
strcpy(path, getenv("HOME"));
strcat(path, dir);
struct stat sb;
/* If the script folder is not existing, we create it. */
if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)) {
} else {
mkdir(path, 0777);
}
/*Let's iterate over LUA files.*/
DIR *folder;
struct dirent *entry;
int files = 0;
folder = opendir(path);
if (folder == NULL) {
ui_show_text_info("Error:\nCannot read ~/.tui-diagdrawer.");
} else {
while ((entry = readdir(folder))) {
files++;
if (strcmp("..", entry->d_name) != 0 &&
strcmp(".", entry->d_name) != 0) {
char filename[100] = {0};
strcpy(filename, path);
strcat(filename, "/");
strcat(filename, entry->d_name);
if (filename[strlen(filename) - 1] == 'a')
if (filename[strlen(filename) - 2] == 'u')
if (filename[strlen(filename) - 3] == 'l')
if (filename[strlen(filename) - 4] == '.')
register_mode(plugin_mode(filename));
}
}
closedir(folder);
}
}
/* Let's register all edit_modes. */
register_mode(rect_mode());
register_mode(put_mode());
register_mode(line_mode());
register_mode(arrow_mode());
register_mode(text_mode());
register_mode(select_mode());
/* Here we build the menu dynamically from registered edit modes. */
char *common_line = " [%c] to enter %s mode\n";
char mode_help[1000] = {0};
int i;
for (i = 0; i < edit_mode_counter; i++) {
char buf[1000];
memset(buf, 0, 1000);
strcpy(buf, common_line);
sprintf(buf, common_line, modes[i].key, modes[i].name);
strcat(mode_help, buf);
}
char *help = "Press [q] to exit\n"
" [w] to write to file\n"
" [x] to write to file and exit\n"
"%s"
" [Ctrl] + [r] to redo changes\n"
" [Ctrl] + [u] to undo changes\n"
" [Ctrl] + [h] to show help for the current mode";
memset(menu_buffer, 0, 10000);
sprintf(menu_buffer, help, mode_help);
}
char *get_menu() {
/* Return the string of the menu built from registered edit_modes. */
return menu_buffer;
}
/* Return if found the edit mode using the key given as parameter. */
edit_mode *get_edit_mode(int key) {
int i = 0;
for (; i < edit_mode_counter; i++) {
if (key == modes[i].key) {
return modes + i;
}
}
return NULL;
}
/* Called at when the app is closing... */
void edit_mode_free() {
int i;
for (i = 0; i < edit_mode_counter; i++) {
if (modes[i].on_free != NULL) {
modes[i].on_free(&modes[i]);
}
}
free(modes);
}<file_sep>/src/demo_plugin.lua
-- Any plugin need at least one NAME and one KEY.
NAME = "Demo Plugin"
KEY = string.byte("d")
-- The returned value is displayed on [ctrl] + [h].
function get_help()
return "I'm the demo plugin!"
end
-- A point we wanna store.
p = {}
p.x = 1
p.y = 1
-- When the user move upper than the beginning of the file,
-- we increment the position of all lines by 1 so we need
-- to do so if we want to keep p in position.
function on_top_line_add()
p.y = p.y + 1
end
-- Same here with on_left_column_add.
function on_left_column_add()
p.x = p.x + 1
end
function on_key_event(key)
if move_cursor(key) == nil then
--show_message_blocking("Ok! working! " .. get_cursor_pos().x .. " " .. get_cursor_pos().y .. " " .. (key or "(nil)"))
--local p = get_cursor_pos()
--p.y = p.y + 1
--set_cursor_pos(p)
show_message_blocking(get_char_at(get_cursor_pos()))
set_char_at(get_cursor_pos(), string.byte("x"))
p = get_cursor_pos()
-- Now we make a recovery point for the undo/redo system.
do_change()
end
end
-- If the position of the character beeing drawn is the one stored,
-- we draw it with the COL_SELECTION.
-- 4 colors are availables: COL_SELECTION COL_EMPTY COL_CURSOR COL_NORMAL 4.
function on_draw(pos, char)
if(pos.x == p.x and pos.y == p.y)then
char.color = COL_SELECTION
end
return char
end<file_sep>/include/position_list.h
#ifndef POSITION_LIST_H
#define POSITION_LIST_H
#include "position.h"
typedef struct position_list position_list;
struct position_list {
int size;
position *list;
};
position_list pl_new();
void pl_add(position_list *pl, position p);
void pl_empty(position_list *pl);
void pl_remove_last(position_list *pl);
position pl_get_last(position_list *pl);
int pl_is_inside(position_list *pl, position p);
char pl_get_line_char(position_list *pl, int index);
char pl_get_arrow_char(position_list *pl, int index);
#endif<file_sep>/src/ui.c
#include "ui.h"
#include "position.h"
#include <curses.h>
#include <string.h>
void ui_draw_rect(position p1, position p2) {
position min = pos_min(p1, p2);
position max = pos_max(p1, p2);
move(min.y, min.x);
hline(ACS_HLINE, max.x - min.x);
vline(ACS_VLINE, max.y - min.y);
addch(ACS_ULCORNER);
move(max.y, min.x);
hline(ACS_HLINE, max.x - min.x);
addch(ACS_LLCORNER);
move(min.y, max.x);
vline(ACS_VLINE, max.y - min.y);
addch(ACS_URCORNER);
move(max.y, max.x);
addch(ACS_LRCORNER);
}
void ui_draw_and_fill(position p1, position p2) {
int x;
int y;
position min = pos_min(p1, p2);
position max = pos_max(p1, p2);
for (x = min.x; x < max.x; x++) {
for (y = min.y; y < max.y; y++) {
move(y, x);
addch(' ');
}
}
ui_draw_rect(p1, p2);
}
int ui_ask_yes_no(char *question) { return 0; }
void ui_show_text(char *text) {
int lines = 0;
int max_line_len = 0;
int line_len = 0;
int i;
for (i = 0; i < strlen(text) + 1; i++) {
char c = text[i];
if (c == '\n')
lines++;
if (c == '\n' || c == '\0') {
if (line_len > max_line_len) {
max_line_len = line_len;
}
line_len = 0;
} else {
line_len++;
}
}
position p1 = {2, 2};
position p2 = {p1.x + max_line_len + 2, p1.y + lines + 2};
ui_draw_and_fill(p1, p2);
move(p1.y + 1, p1.x + 1);
lines = 0;
for (i = 0; i < strlen(text); i++) {
char c = text[i];
if (c == '\n') {
lines++;
move(p1.y + lines + 1, p1.x + 1);
} else {
addch(c);
}
}
}
/* #TODO: enable viewing strings bigger than the screen. */
void ui_show_text_info(char *text) {
ui_show_text(text);
getch();
}<file_sep>/src/edit_modes/select_mode.c
#include <curses.h>
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "ui.h"
#include "undo_redo.h"
position P1, P2;
chunk CLIPBOARD;
int is_in_rect(position r1, position r2, position p) {
position min = pos_min(r1, r2);
position max = pos_max(r1, r2);
if (p.x >= min.x && p.x <= max.x)
if (p.y <= max.y && p.y >= min.y)
return 1;
return 0;
}
static void on_key_event(edit_mode * self, int c) {
{
if (move_cursor(c).null == 1) {
if (P1.null || P2.null) {
if (c == 'p') {
do_change(&CURRENT_FILE);
chk_blit_chunk(&CURRENT_FILE, &CLIPBOARD, get_cursor_pos());
}
if (c == ' ') {
position tmp = get_cursor_pos();
if (P1.null) {
P1 = tmp;
} else if (P2.null) {
P2 = tmp;
} else {
P1.null = 1;
P2.null = 1;
}
}
} else if (!P2.null) {
position min = pos_min(P1, P2);
position max = pos_max(P1, P2);
int x;
int y;
if (c == K_HELP) {
ui_show_text_info(get_menu());
} else if (c == ' ') {
P2.null = 1;
P1.null = 1;
} else if (c == 'y') {
chk_free(&CLIPBOARD);
CLIPBOARD = chk_extract_chunk(&CURRENT_FILE, min, max);
P2.null = 1;
P1.null = 1;
} else if (c == 'd') {
chk_fill_chunk(&CURRENT_FILE, min, max, ' ');
} else if (c == 'c') {
chk_free(&CLIPBOARD);
CLIPBOARD = chk_extract_chunk(&CURRENT_FILE, min, max);
P2.null = 1;
P1.null = 1;
chk_fill_chunk(&CURRENT_FILE, min, max, ' ');
} else if (c == KEY_DC) {
do_change(&CURRENT_FILE);
position min = pos_min(P1, P2);
position max = pos_max(P1, P2);
int x;
int y;
for (x = min.x; x <= max.x; x++) {
for (y = min.y; y <= max.y; y++) {
position tmp = {x, y};
chk_set_char_at(&CURRENT_FILE, tmp, ' ');
}
}
}
/*
Here we enter into the fill mode.
Basically we replace all characters in the selection by the
specified one.
*/
else if (c == 'f') {
ui_show_text("You are in SELECT/FILL mode.\n"
"Type the character you wanna\n"
"set instead of the selection\n"
"or [ctrl] + [u] to abort.");
int abort = 0;
do {
c = getch();
if (c == K_UNDO || c == K_REDO) {
abort = 1;
break;
}
} while (!is_writable(c));
if (!abort) {
position min = pos_min(P1, P2);
position max = pos_max(P1, P2);
int x;
int y;
do_change(&CURRENT_FILE);
for (x = min.x; x <= max.x; x++) {
for (y = min.y; y <= max.y; y++) {
position tmp = {x, y};
chk_set_char_at(&CURRENT_FILE, tmp, c);
}
}
}
}
/*
Here we enter into the replace mode.
Basically we replace all characters in the selection that are not
spaces by the specified one.
*/
else if (c == 'r') {
ui_show_text("You are in SELECT/REPLACE mode.\n"
"Type the character you wanna\n"
"set instead of the characters\n"
"in the selection or press\n"
"[ctrl] + [u] to abort.");
int abort = 0;
do {
c = getch();
if (c == K_UNDO || c == K_REDO) {
abort = 1;
break;
}
} while (!is_writable(c));
if (!abort) {
position min = pos_min(P1, P2);
position max = pos_max(P1, P2);
int x;
int y;
do_change(&CURRENT_FILE);
for (x = min.x; x <= max.x; x++) {
for (y = min.y; y <= max.y; y++) {
position tmp = {x, y};
if (chk_get_char_at(&CURRENT_FILE, tmp) != ' ')
chk_set_char_at(&CURRENT_FILE, tmp, c);
}
}
}
} else {
position delta = move_cursor(c);
if (!delta.null) {
P1.y += delta.y;
P1.x += delta.x;
P2.y += delta.y;
P2.x += delta.x;
}
}
}
}
}
}
static void on_exit(edit_mode * self) {
P1.null = 1;
P2.null = 1;
}
static character on_draw(edit_mode * self, position p, character c) {
position tmp = P2.null == 0 ? P2 : get_cursor_pos();
if (P1.null != 1) {
if (is_in_rect(P1, tmp, p)) {
c.color = COL_SELECTION;
}
}
return c;
}
static void on_free(edit_mode * self) { chk_free(&CLIPBOARD); }
static void on_top_line_add(edit_mode * self) {
if (!P1.null) {
P1.y++;
}
if (!P2.null) {
P2.y++;
}
}
static void on_left_column_add(edit_mode * self) {
if (!P1.null) {
P1.x++;
}
if (!P2.null) {
P2.x++;
}
}
static int on_abort(edit_mode * self) {
if (!P1.null) {
P1.null = 1;
P2.null = 1;
return 1;
}
return 0;
}
static char *get_help(edit_mode * self) {
if (P1.null || P2.null) {
return "You are in the SELECT mode.\n"
"You have not two points selected.\n"
"Use [space] to select another one.\n"
"\n"
"Press any key to continue.";
} else {
return "You are in the SELECT mode.\n"
"You have selected an area (in blue).\n"
"Use [space] to select another one.\n"
"Use [c] to cut.\n"
"Use [y] to copy.\n"
"Use [p] to past.\n"
"Use [f] to fill.\n"
"Use [r] to replace.\n"
"\n"
"Press any key to continue.";
}
}
edit_mode select_mode() {
CLIPBOARD.null = 1;
edit_mode EDIT_MODE_RECT = {.name = "SELECT",
.key = (int)'s',
.on_key_event = on_key_event,
.on_exit = on_exit,
.on_draw = on_draw,
.on_free = on_free,
.on_abort = on_abort,
.get_help = get_help,
.null = 0};
return EDIT_MODE_RECT;
}<file_sep>/README.md
# A TUI software to draw basics ASCII diagrams.

## Introduction
A minimalist and lightweight ascii diagram editor working with ncurses.<br>
It features an easy to use interface for drawing rects, lines, arrows, text...<br>
and doing things such as copy-pasting, filling selection...<br>
It's written in C because first I like C, C is beautiful, C is simple,<br>
C's memmory management is challenging and it compiles fast.<br>
<br>
This project is not intended to be a good text editor but a good ascii diagram drawer.<br>
Even if I'm trying to improve the `TEXT` mode as much as possible :)<br>
The main purpose of this project is to help writing documentation for devs<br>
but it can also be used to draw a tui-videogame map!<br>
<br>
The project support LUA scripting (scripts are in `~/.tui-diagdrawer`)<br>
and if you run `make install` it will install a demo script.<br>
Be careful if you want to use plugins written by someone else!<br>
The sandbox is not done yet!<br>
## How to use
### How to setup
To install dependancies (ncurses and Lua):
* `sudo apt-get install libncurses5-dev libncursesw5-dev`
* `curl -R -O http://www.lua.org/ftp/lua-5.4.0.tar.gz`
* `tar zxf lua-5.4.0.tar.gz`
* `cd lua-5.4.0`
* `make`
* `make install`
To build the project:
* `git clone <EMAIL>:Fran6nd/tui-diagdrawer.git`
* `cd tui-diagdrawer`
* `make`
* `./tui-diagdrawer myfile`
To install:
* `sudo make install`
### Common operations
* `[tab]`: enter/exit the menu.
* `[ctrl] + [u]`: undo.
* `[ctrl] + [r]`: redo.
* `[arrow]`: move the cursor.
* `[ctrl] + [arrow]`: move the cursor faster.
## Contributing
Any contribution is appreciated to improve the software's capabilities/architecture<br>
In case af style changes, of course it's welcome but do not forget to explain why :)<br>
## TODO
* Multiple files editing.
* Finding words, chunk...
* Display strings bigger than screen in help viewport.
* Improve the text editor.
* Better sandbox for LUA scripts.
* Enable the user to change the name of the outpout file.
* Better Lua errors handling (avoid segfault if args not ok).
* Capability to override existing built-in edit modes.
# Here is what we can do:
```
| +-----------+
| |rects |-------+
| +-----------+ |
| |
| lines: |
| | | |
| | | |
| | |<---arrows----+
| +---+
|
| fill:
| **********
| **********
| **********
| **********
| copy past:
| ********** ********** **********
| ********** ********** **********
| ********** ********** **********
| ********** ********** **********
+-----------------------------------+
```
# And an example diagram I made for another project.
```
+-----B-West to A----+ +---A-East to B-------+
| | | |
| V | | | | V |
edge 0 <---| +---------+ |--->edge 0-------+ edge 0 <---| +---------+ |--->edge 0
edge ... <---|-| BRICK A |-|--->edge ... | edge ...<---|-| BRICK B |-|--->edge ...
edge n <---| +---------+ |--->edge n +------edge n <---| +---------+ |--->edge n
| | | |
| | | |
| | | |
| | | |
WEST SIDE EAST SIDE WEST SIDE EAST SIDE
```
<file_sep>/src/position_list.c
#include "position_list.h"
#include <stdlib.h>
position_list pl_new() {
position_list pl;
pl.size = 0;
return pl;
}
void pl_add(position_list *pl, position p) {
pl->size++;
if (pl->size == 1) {
pl->list = malloc(sizeof(position));
pl->list[0] = p;
} else {
pl->list = (position *)realloc(pl->list, pl->size * sizeof(position));
pl->list[pl->size - 1] = p;
}
}
/* Clear the content of a list. */
void pl_empty(position_list *pl) {
if (pl->size > 0) {
free(pl->list);
pl->size = 0;
}
}
/* Remove last position from a list. */
void pl_remove_last(position_list *pl) {
if (pl->size == 1) {
pl_empty(pl);
} else if (pl->size > 1) {
pl->size--;
pl->list = (position *)realloc(pl->list, pl->size * sizeof(position));
}
}
/* Check if the given position is inside or not.
* Return -1 if not.
* Else return index in list.
*/
int pl_is_inside(position_list *pl, position p) {
int i;
for (i = 0; i < pl->size; i++) {
position p1 = pl->list[i];
if (p.x == p1.x && p.y == p1.y) {
return i;
}
}
return -1;
}
/* Calculate which char should be displayed from the index of a list containing
* all line's points. */
char pl_get_line_char(position_list *pl, int i) {
char to_print = '#';
position current = pl->list[i];
if (pl->size == 1) {
to_print = '+';
} else if (i - 1 >= 0 && i + 1 < pl->size) {
position prev = pl->list[i - 1];
position next = pl->list[i + 1];
if (prev.x != next.x && prev.y != next.y) {
to_print = '+';
} else if (prev.x == next.x) {
to_print = '|';
} else {
to_print = '-';
}
} else if (i == 0) {
position next = pl->list[i + 1];
if (current.x == next.x) {
to_print = '|';
} else {
to_print = '-';
}
} else {
position prev = pl->list[i - 1];
if (current.x == prev.x) {
to_print = '|';
} else {
to_print = '-';
}
}
return to_print;
}
/* Calculate which char should be displayed from the index of a list containing
* all arrow's points. */
char pl_get_arrow_char(position_list *pl, int i) {
char to_print = '#';
position current = pl->list[i];
if (pl->size == 1) {
to_print = '+';
} else if (i - 1 >= 0 && i + 1 < pl->size) {
position prev = pl->list[i - 1];
position next = pl->list[i + 1];
if (prev.x != next.x && prev.y != next.y) {
to_print = '+';
} else if (prev.x == next.x) {
to_print = '|';
} else {
to_print = '-';
}
} else if (i == 0) {
position next = pl->list[i + 1];
if (current.x == next.x) {
to_print = '|';
} else {
to_print = '-';
}
} else {
position prev = pl->list[i - 1];
if (current.x == prev.x) {
if (current.y < prev.y) {
to_print = '^';
} else {
to_print = 'v';
}
} else {
if (prev.x < current.x) {
to_print = '>';
} else {
to_print = '<';
}
}
}
return to_print;
}
position pl_get_last(position_list *pl) { return pl->list[pl->size - 1]; }
<file_sep>/src/edit_modes/rect_mode.c
#include <curses.h>
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "ui.h"
#include "undo_redo.h"
position P1, P2;
static void on_key_event(edit_mode *self, int c) {
if (move_cursor(c).null) {
if (c == (int)' ') {
position tmp = get_cursor_pos();
if (P1.null) {
P1 = tmp;
} else {
do_change(&CURRENT_FILE);
position down_left = pos_min(P1, tmp);
position up_right = pos_max(P1, tmp);
position up_left = {down_left.x, up_right.y};
position down_right = {up_right.x, down_left.y};
chk_set_char_at(&CURRENT_FILE, down_left, '+');
chk_set_char_at(&CURRENT_FILE, up_right, '+');
chk_set_char_at(&CURRENT_FILE, down_right, '+');
chk_set_char_at(&CURRENT_FILE, up_left, '+');
int x;
for (x = down_left.x + 1; x < down_right.x; x++) {
position tmp1 = {x, up_right.y};
chk_set_char_at(&CURRENT_FILE, tmp1, '-');
}
for (x = down_left.x + 1; x < down_right.x; x++) {
position tmp1 = {x, down_right.y};
chk_set_char_at(&CURRENT_FILE, tmp1, '-');
}
int y;
for (y = down_left.y + 1; y < up_left.y; y++) {
position tmp1 = {up_left.x, y};
chk_set_char_at(&CURRENT_FILE, tmp1, '|');
}
for (y = down_left.y + 1; y < up_left.y; y++) {
position tmp1 = {up_right.x, y};
chk_set_char_at(&CURRENT_FILE, tmp1, '|');
}
P1.null = 1;
}
}
}
}
static void on_exit(edit_mode *self) {
P1.null = 1;
P2.null = 1;
}
static int is_on_rect_corner(position r1, position r2, position p) {
position down_left = pos_min(r1, r2);
position up_right = pos_max(r1, r2);
position up_left = {down_left.x, up_right.y};
position down_right = {up_right.x, down_left.y};
if (p.x == down_left.x && p.y == down_left.y)
return 1;
if (p.x == up_right.x && p.y == up_right.y)
return 1;
if (p.x == up_left.x && p.y == up_left.y)
return 1;
if (p.x == down_right.x && p.y == down_right.y)
return 1;
return 0;
}
static int is_on_rect_border(position r1, position r2, position p) {
position min = pos_min(r1, r2);
position max = pos_max(r1, r2);
if (p.x > min.x && p.x < max.x)
if (p.y == max.y || p.y == min.y)
return 1;
if (p.y > min.y && p.y < max.y)
if (p.x == max.x || p.x == min.x)
return 1;
return 0;
}
static character on_draw(edit_mode *self, position p, character c) {
if (P1.null == 0) {
if (is_on_rect_corner(P1, get_cursor_pos(), p)) {
c.c = '+';
} else if (is_on_rect_border(P1, get_cursor_pos(), p)) {
if (p.y == P1.y || p.y == get_cursor_pos().y) {
c.c = '-';
}
if (p.x == P1.x || p.x == get_cursor_pos().x) {
c.c = '|';
}
}
}
return c;
}
static void on_top_line_add(edit_mode *self) {
if (!P1.null) {
P1.y++;
}
}
static void on_left_column_add(edit_mode *self) {
if (!P1.null) {
P1.x++;
}
}
static int on_abort(edit_mode *self) {
if (!P1.null) {
P1.null = 1;
P2.null = 1;
return 1;
}
return 0;
}
static char *get_help(edit_mode *self) {
return "You are in the RECT mode.\n"
"You can draw any rect by using [space] to select the "
"first point\n"
"and [space] again to select the second one.\n"
"\n"
"Press any key to continue.";
}
edit_mode rect_mode() {
P1.null = 1;
P2.null = 1;
edit_mode EDIT_MODE_RECT = {.name = "RECT",
.key = 114,
.on_key_event = on_key_event,
.on_exit = on_exit,
.on_draw = on_draw,
.on_top_line_add = on_top_line_add,
.on_left_column_add = on_left_column_add,
.on_abort = on_abort,
.get_help = get_help,
.null = 0};
return EDIT_MODE_RECT;
}<file_sep>/src/chunk.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "chunk.h"
chunk chk_new(int x, int y) {
fflush(stdout);
chunk f;
f.lines = y;
f.cols = x;
f.chunk = malloc(f.lines * sizeof(char *));
int i;
for (i = 0; i < f.lines; i++) {
f.chunk[i] = malloc(sizeof(char) * (f.cols + 1));
memset(f.chunk[i], ' ', f.cols);
f.chunk[i][f.cols] = 0;
}
f.null = 0;
return f;
}
chunk chk_extract_chunk(chunk *input, position p1, position p2) {
p2.x++;
p2.y++;
position min = pos_min(p1, p2);
position max = pos_max(p1, p2);
chunk output = chk_new(max.x - min.x, max.y - min.y);
int x;
int y;
for (x = min.x; x < max.x; x++) {
for (y = min.y; y < max.y; y++) {
position in_input = {x, y, 0};
position in_output = {x - min.x, y - min.y, 0};
chk_set_char_at(&output, in_output, chk_get_char_at(input, in_input));
}
}
return output;
}
chunk chk_copy_chunk(chunk *input) {
chunk output;
if (input->null) {
output.null = 1;
return output;
}
output = chk_new(input->cols, input->lines);
int x;
int y;
for (x = 0; x < input->cols; x++) {
for (y = 0; y < input->lines; y++) {
position tmp = {x, y, 0};
chk_set_char_at(&output, tmp, chk_get_char_at(input, tmp));
}
}
return output;
}
void chk_fill_chunk(chunk *input, position p1, position p2, char c) {
p2.x++;
p2.y++;
position min = pos_min(p1, p2);
position max = pos_max(p1, p2);
int x;
int y;
for (x = min.x; x < max.x; x++) {
for (y = min.y; y < max.y; y++) {
position tmp = {x, y};
chk_set_char_at(input, tmp, c);
}
}
}
void chk_blit_chunk(chunk *main, chunk *clipboard, position p) {
if (!main->null) {
int x;
int y;
for (x = 0; x < clipboard->cols; x++) {
for (y = 0; y < clipboard->lines; y++) {
position pos_in_main = {x + p.x, y + p.y};
position pos_in_clipboard = {x, y};
chk_set_char_at(main, pos_in_main,
chk_get_char_at(clipboard, pos_in_clipboard));
}
}
}
}
chunk chk_new_from_file(char *chk) {
int lines = 0;
int col = 0;
int max_col = 0;
// Open the file
FILE *fp = fopen(chk, "r");
// Check if file exists
if (fp == NULL) {
return chk_new(10, 10);
}
// Extract characters from file and store in character c
char c;
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
{
lines = lines + 1;
col = 0;
} else {
col++;
if (col > max_col) {
max_col = col;
}
}
rewind(fp);
chunk output = chk_new(max_col + 1, lines + 1);
int y = 0;
int x = 0;
for (c = getc(fp); c != EOF; c = getc(fp))
if (c == '\n') // Increment count if this character is newline
{
y++;
;
x = 0;
} else {
x++;
position tmp = {x, y};
chk_set_char_at(&output, tmp, c);
}
fclose(fp);
return output;
}
void chk_save_to_file(chunk *chk, char *f) {
int y;
int x;
/* Find empty columns on left. */
int global_left_indent = 0;
for (x = 0; x < chk->cols; x++) {
int spaces_only = 1;
for (y = 0; y < chk->lines; y++) {
position tmp = {x, y};
if (chk->chunk[y][x] != ' ') {
spaces_only = 0;
break;
}
}
if (spaces_only == 1) {
global_left_indent++;
} else {
break;
}
}
/* Find number of empty lines at the end of the file. */
int empty_lines_at_eof = 0;
for (y = chk->lines - 1; y >= 0; y--) {
char *line = chk->chunk[y];
int i;
int empty = 1;
for (i = 0; i < strlen(line); i++) {
if (line[i] != ' ') {
empty = 0;
}
}
if (empty) {
empty_lines_at_eof++;
} else {
y = -1;
}
}
/* Find number of empty lines at the beginnng of the file. */
int empty_lines_at_bof = 0;
for (y = 0; y < chk->lines; y++) {
char *line = chk->chunk[y];
int i;
int empty = 1;
for (i = 0; i < strlen(line); i++) {
if (line[i] != ' ') {
empty = 0;
}
}
if (empty) {
empty_lines_at_bof++;
} else {
y = chk->lines;
}
}
/* Now write the file. */
FILE *fOut = fopen(f, "w");
for (y = empty_lines_at_bof; y < chk->lines - empty_lines_at_eof; y++) {
char *line = chk->chunk[y];
char *tmp = malloc((sizeof(char)) * (strlen(line) + 1));
memcpy(tmp, line, strlen(line) + 1);
int i;
for (i = strlen(line) - 1; i >= 0; i--) {
if (tmp[i] == ' ') {
tmp[i] = 0;
} else {
i = -1;
}
}
for (i = global_left_indent; i < strlen(tmp); i++) {
fputc(tmp[i], fOut);
}
fputs("\n", fOut);
free(tmp);
}
fclose(fOut);
}
void chk_free(chunk *chk) {
if (!chk->null) {
int i;
for (i = 0; i < chk->lines; i++) {
free(chk->chunk[i]);
}
free(chk->chunk);
chk->lines = -1;
chk->null = 1;
}
}
char chk_get_char_at(chunk *chk, position p) {
if (p.y < chk->lines && p.y >= 0) {
if (p.x < strlen(chk->chunk[p.y]) && p.x >= 0) {
return chk->chunk[p.y][p.x];
}
}
return 0;
}
void chk_set_char_at(chunk *chk, position p, char c) {
while (p.y < 0) {
p.y++;
chk_add_line_up(chk);
}
while (p.y >= chk->lines) {
chk_add_line_down(chk);
}
while (p.x < 0) {
p.x++;
chk_add_col_left(chk);
}
while (p.x >= chk->cols) {
chk_add_col_right(chk);
}
chk->chunk[p.y][p.x] = c;
}
void chk_add_line_down(chunk *chk) {
chk->lines++;
chk->chunk = (char **)realloc(chk->chunk, chk->lines * sizeof(char *));
chk->chunk[chk->lines - 1] = malloc(sizeof(char) * chk->cols + 1);
memset(chk->chunk[chk->lines - 1], ' ', chk->cols);
chk->chunk[chk->lines - 1][chk->cols] = 0;
}
void chk_add_line_up(chunk *chk) {
chk_add_line_down(chk);
int y;
for (y = chk->lines - 2; y >= 0; y--) {
memcpy(chk->chunk[y + 1], chk->chunk[y], strlen(chk->chunk[y]));
}
memset(chk->chunk[0], ' ', strlen(chk->chunk[0]));
}
void chk_add_col_right(chunk *chk) {
chk->cols++;
int y;
for (y = 0; y < chk->lines; y++) {
chk->chunk[y] =
(char *)realloc(chk->chunk[y], sizeof(char) * chk->cols + 1);
chk->chunk[y][chk->cols] = 0;
chk->chunk[y][chk->cols - 1] = ' ';
}
}
void chk_add_col_left(chunk *chk) {
chk_add_col_right(chk);
int y;
for (y = 0; y < chk->lines; y++) {
int x;
for (x = chk->cols - 2; x >= 0; x--) {
chk->chunk[y][x + 1] = chk->chunk[y][x];
}
chk->chunk[y][0] = ' ';
}
}<file_sep>/include/edit_mode.h
#ifndef EDIT_MODE_H
#define EDIT_MODE_H
#include "chunk.h"
#include "main.h"
typedef struct edit_mode edit_mode;
struct edit_mode {
/* The name of the edit_mode. */
char *name;
/* The key used to access the edit_mode. */
int key;
/* Function used to manage events. */
void (*on_key_event)(edit_mode *, int);
/* Function used to hook character drawing. */
character (*on_draw)(edit_mode *, position, character);
/* Function used to get the help to display on [ctrl] + [h]. */
char *(*get_help)(edit_mode *);
/* These two functions are called when we move all characters to left or down
* by adding a line on top or a column on the left side.
* They are used to tell the edit_mode that everything moved. */
void (*on_top_line_add)(edit_mode *);
void (*on_left_column_add)(edit_mode *);
/* Called when exiting the current mode. */
void (*on_exit)(edit_mode *);
/* Called when the app is closing. */
void (*on_free)(edit_mode *);
/* Used to abort the current task.
* Return 1 if a task has been aborted, else 0. */
int (*on_abort)(edit_mode *);
/* Used to store a custom data into the edit_mode struct sucj as a lua script.
*/
void *data;
/* Used to knowif NULL1 */
int null;
};
extern struct edit_mode *modes;
extern int edit_mode_counter;
void register_modes();
char *get_menu();
edit_mode *get_edit_mode(int key);
void edit_mode_free();
/* Functions returning all natives edit modes. */
edit_mode put_mode();
edit_mode rect_mode();
edit_mode arrow_mode();
edit_mode line_mode();
edit_mode text_mode();
edit_mode select_mode();
edit_mode plugin_mode(char *);
#endif<file_sep>/include/ui.h
#ifndef UI_H
#define UI_H
#include "position.h"
void ui_draw_rect(position p1, position p2);
int ui_ask_yes_no(char *question);
void ui_show_text(char *text);
void ui_show_text_info(char *text);
#endif<file_sep>/src/show_keyname.c
#include <curses.h>
#include <stdio.h>
/*
* Basic program to display pressed key's name.
*/
int main() {
initscr();
noecho();
keypad(stdscr, 1);
while (1) {
const int c = getch();
const char *name = keyname(c);
printw("key: %s code: %d |", name, c);
if (c == 'q')
break;
}
endwin();
}<file_sep>/include/position.h
#ifndef POSITION_H
#define POSITION_H
typedef struct position position;
struct position {
int x, y, null;
};
position pos_min(position p1, position p2);
position pos_max(position p1, position p2);
#endif<file_sep>/include/chunk.h
#ifndef AD_FILE_H
#define AD_FILE_H
#include "position.h"
/*
* A chunk is a square of text.
* This is how we manage everything here.
* They are used to load text from a file,
* to extract a chunk from another...
*/
typedef struct chunk chunk;
struct chunk {
char **chunk;
int lines;
int cols;
int null;
};
chunk chk_new(int x, int y);
chunk chk_new_from_file(char *f);
void chk_save_to_file(chunk *file, char *f);
void chk_free(chunk *f);
char chk_get_char_at(chunk *f, position);
void chk_set_char_at(chunk *f, position, char c);
chunk chk_extract_chunk(chunk *f, position p1, position p2);
chunk chk_copy_chunk(chunk *input);
void chk_fill_chunk(chunk *input, position p1, position p2, char c);
void chk_blit_chunk(chunk *background, chunk *clipboard, position p);
void chk_add_line_down(chunk *f);
void chk_add_line_up(chunk *f);
void chk_add_col_right(chunk *f);
void chk_add_col_left(chunk *f);
#endif<file_sep>/src/position.c
#include "position.h"
#define max(a, b) (a >= b ? a : b)
#define min(a, b) (a <= b ? a : b)
position pos_min(position p1, position p2) {
position output = {min(p1.x, p2.x), min(p1.y, p2.y)};
return output;
}
position pos_max(position p1, position p2) {
position output = {max(p1.x, p2.x), max(p1.y, p2.y)};
return output;
}<file_sep>/src/undo_redo.c
#include "chunk.h"
/*
* This file is intended to allow performing undo/redo operations.
* This is maybe the most sensitive part of the software because of the risk of
* memmory leaks. Feel free to improve it :)
*/
chunk history[10];
int index;
int can_redo = 0;
void init_undo_redo() {
int i;
for (i = 0; i < 10; i++) {
history[i].null = 1;
}
}
void do_change(chunk *chk) {
can_redo = 0;
if (index == 10) {
/* We free the first chunk */
chk_free(&history[0]);
int i;
for (i = 0; i < 9; i++) {
/* Moving reference for high index to low. */
history[i] = history[i + 1];
}
index = 9;
/* The last cell is containing same pointers as the previous one.
* So we set it to null to do not free the previous one.
*/
history[index].null = 1;
}
/* If the chunk is not empty we free it. */
if (!history[index].null) {
chk_free(&history[index]);
}
history[index] = chk_copy_chunk(chk);
index++;
}
void undo_change(chunk *chk) {
if (index == 10)
index--;
if (index > 0) {
index--;
can_redo++;
chk_free(chk);
*chk = chk_copy_chunk(&history[index]);
}
}
void redo_change(chunk *chk) {
if (can_redo > 0) {
chk_free(chk);
can_redo--;
index++;
*chk = chk_copy_chunk(&history[index]);
}
}
void free_undo_redo() {
int i;
for (i = 0; i < 10; i++) {
if (!history[i].null)
chk_free(&history[i]);
}
}<file_sep>/src/edit_modes/text_mode.c
#include <curses.h>
#include "edit_mode.h"
#include "main.h"
#include "position.h"
#include "ui.h"
#include "undo_redo.h"
static void on_key_event(edit_mode *self, int c) {
if (move_cursor(c).null) {
/* Erasing. */
if (c == 127 || c == KEY_BACKSPACE) {
position tmp = get_cursor_pos();
position position_of_char_to_remove = get_cursor_pos();
position_of_char_to_remove.x--;
char chr_to_replace =
chk_get_char_at(&CURRENT_FILE, position_of_char_to_remove);
if (chr_to_replace != '+' && chr_to_replace != '|' &&
chr_to_replace != '^' && chr_to_replace != 'v' &&
chr_to_replace != '>') {
int x;
char buffer[CURRENT_FILE.cols];
int buffer_index = 0;
for (x = tmp.x; x < CURRENT_FILE.cols; x++) {
position tmp1 = {x, tmp.y};
char ch = chk_get_char_at(&CURRENT_FILE, tmp1);
if (ch != '+' && ch != '|' && ch != '^' && ch != 'v' && ch != '>') {
buffer[buffer_index] = ch;
buffer_index++;
} else {
break;
}
}
int i;
for (i = buffer_index - 1; i >= 0; i--) {
position tmp1 = {tmp.x + i - 1, tmp.y};
chk_set_char_at(&CURRENT_FILE, tmp1, buffer[i]);
}
position tmp1 = {tmp.x + buffer_index - 1, tmp.y};
chk_set_char_at(&CURRENT_FILE, tmp1, ' ');
UP_LEFT_CORNER.x--;
}
}
/* Deleting. */
else if (c == KEY_DC) {
position tmp = get_cursor_pos();
position position_of_char_to_remove = get_cursor_pos();
char chr_to_replace =
chk_get_char_at(&CURRENT_FILE, position_of_char_to_remove);
if (!is_diag_char(chr_to_replace)) {
int x;
char buffer[CURRENT_FILE.cols];
int buffer_index = 0;
for (x = tmp.x; x < CURRENT_FILE.cols; x++) {
position tmp1 = {x, tmp.y};
char ch = chk_get_char_at(&CURRENT_FILE, tmp1);
if (!is_diag_char(ch)) {
buffer[buffer_index] = ch;
buffer_index++;
} else {
break;
}
}
int i;
for (i = buffer_index - 1; i > 0; i--) {
position tmp1 = {tmp.x + i - 1, tmp.y};
chk_set_char_at(&CURRENT_FILE, tmp1, buffer[i]);
}
position tmp1 = {tmp.x + buffer_index - 1, tmp.y};
chk_set_char_at(&CURRENT_FILE, tmp1, ' ');
}
}
/* New line. */
else if (c == K_ENTER) {
/* Let's find a [tab] or more than 2 [spaces] to find the
* indentation. */
char current_key = -1;
char previous_key = chk_get_char_at(&CURRENT_FILE, get_cursor_pos());
int starting_x = UP_LEFT_CORNER.x;
for (; get_cursor_pos().x >= -1; UP_LEFT_CORNER.x--) {
previous_key = current_key;
current_key = chk_get_char_at(&CURRENT_FILE, get_cursor_pos());
if (previous_key == ' ' && current_key == ' ') {
if (UP_LEFT_CORNER.x != starting_x - 1) {
/* We compensate the 2 spaces found. */
UP_LEFT_CORNER.x += 2;
do_change(&CURRENT_FILE);
} else
/* The line is empty. */
UP_LEFT_CORNER.x++;
break;
} else if ((is_diag_char(current_key)) &&
UP_LEFT_CORNER.x != starting_x) {
/* We compensate the character found. */
UP_LEFT_CORNER.x += 1;
do_change(&CURRENT_FILE);
break;
}
}
UP_LEFT_CORNER.y++;
/* Now if we are on a rect border or en arrow we skip it. */
int loop = 1;
while (loop) {
current_key = chk_get_char_at(&CURRENT_FILE, get_cursor_pos());
if (is_diag_char(current_key)) {
UP_LEFT_CORNER.x++;
} else {
loop = 0;
}
}
} else if (is_writable(c)) {
position tmp = get_cursor_pos();
char chr_to_replace = chk_get_char_at(&CURRENT_FILE, tmp);
if (!is_diag_char(chr_to_replace)) {
chk_set_char_at(&CURRENT_FILE, tmp, c);
UP_LEFT_CORNER.x++;
}
}
}
}
static char *get_help(edit_mode *self) {
return "You are in the TEXT mode.\n"
"Just enter any text here.\n"
"\n"
"Press any key to continue.";
}
edit_mode text_mode() {
edit_mode ed = {.name = "TEXT",
.key = (int)'t',
.on_key_event = on_key_event,
.get_help = get_help,
.null = 0};
return ed;
}<file_sep>/include/undo_redo.h
#ifndef UNDO_REDO_H
#define UNDO_REDO_H
#include "chunk.h"
/*
* This file is intended to allow performing undo/redo operations.
* This is maybe the most sensitive part of the software because of the risk of
* memmory leaks. Feel free to improve it :)
*/
void init_undo_redo();
void do_change(chunk *chk);
void undo_change(chunk *chk);
void redo_change(chunk *chk);
void free_undo_redo();
#endif<file_sep>/include/main.h
#ifndef MAIN_H
#define MAIN_H
#include "position.h"
#include "chunk.h"
#define COL_SELECTION 1
#define COL_EMPTY 2
#define COL_CURSOR 3
#define COL_NORMAL 4
#define MODE_NONE 0
#define MODE_SELECT 1
#define MODE_PUT 2
#define MODE_TEXT 3
#define MODE_RECT 4
#define MODE_LINE 5
#define MODE_ARROW 6
/* [Ctrl] + h for help. */
#define K_HELP 8
/* [Ctrl] + u for undo. */
#define K_UNDO 21
/* [Ctrl] + r for redo. */
#define K_REDO 18
/* [return] / [enter] */
#define K_ENTER 10
typedef struct character {
char c;
int color;
} character;
position get_cursor_pos();
position move_cursor();
int is_writable(char);
int is_diag_char(char);
extern chunk CURRENT_FILE;
extern position UP_LEFT_CORNER;
#endif<file_sep>/Makefile
.DEFAULT_GOAL := tui-diagdrawer
show_keyname.o: src/show_keyname.c
gcc -g -O -c src/show_keyname.c -std=c99 -o show_keyname.o -Incurses
show_keyname: show_keyname.o
gcc -g -g show_keyname.o -Iinclude -lncurses -o show_keyname
ui.o: src/ui.c
gcc -g -O -c src/ui.c -std=c99 -o ui.o -Iinclude
undo_redo.o: src/undo_redo.c
gcc -g -O -c src/undo_redo.c -std=c99 -o undo_redo.o -Iinclude
position.o: src/position.c
gcc -g -O -c src/position.c -std=c99 -o position.o -Iinclude
position_list.o: src/position_list.c
gcc -g -O -c src/position_list.c -std=c99 -o position_list.o -Iinclude
chunk.o: src/chunk.c position.o position_list.o
gcc -g -O -c src/chunk.c -std=c99 -o chunk.o -Iinclude
edit_mode.o: src/edit_mode.c
gcc -g -O -c src/edit_mode.c -std=c99 -o edit_mode.o -Iinclude
gcc -g -O -c src/edit_modes/rect_mode.c -std=c99 -o rect_mode.o -Iinclude
gcc -g -O -c src/edit_modes/put_mode.c -std=c99 -o put_mode.o -Iinclude
gcc -g -O -c src/edit_modes/line_mode.c -std=c99 -o line_mode.o -Iinclude
gcc -g -O -c src/edit_modes/arrow_mode.c -std=c99 -o arrow_mode.o -Iinclude
gcc -g -O -c src/edit_modes/text_mode.c -std=c99 -o text_mode.o -Iinclude
gcc -g -O -c src/edit_modes/select_mode.c -std=c99 -o select_mode.o -Iinclude
gcc -g -O -c src/edit_modes/plugin_mode.c -std=c99 -Iinclude -o plugin_mode.o
main.o: chunk.o
gcc -g -D _DEFAULT_SOURCE -O -c src/main.c -std=c99 -o main.o -Iinclude -lncurses
tui-diagdrawer: main.o position.o ui.o undo_redo.o position_list.o chunk.o edit_mode.o
gcc -g main.o edit_mode.o rect_mode.o put_mode.o line_mode.o arrow_mode.o text_mode.o select_mode.o plugin_mode.o undo_redo.o chunk.o position.o position_list.o ui.o -Iinclude -lncurses -llua -lm -ldl -o tui-diagdrawer
all:tui-diagdrawer show_keyname
clean:
rm -f *.o
rm -f tui-diagdrawer
rm -f show_keyname
rebuild: clean all
#PREFIX is environment variable, but if it is not set, then set default value
ifeq ($(PREFIX),)
PREFIX := /usr
endif
install: tui-diagdrawer
sudo cp tui-diagdrawer /usr/local/bin
mkdir -p ~/.tui-diagdrawer
cp src/demo_plugin.lua ~/.tui-diagdrawer
uninstall:
sudo rm /usr/local/bin/tui-diagdrawer
rm -rf ~/.tui-diagdrawer
| 248707a62ba08f31b168aa5054626e51a3161fae | [
"Markdown",
"C",
"Makefile",
"Lua"
] | 24 | C | Fran6nd/ascii-drawer | 16ce944a6255a3242778779986a1e07b74f90116 | 5dc627db550f7c5f3267ae02c4efe1a264c85226 |
refs/heads/master | <file_sep># TWEB-TE2
## TWEB - Github API Demo
by <NAME>
## Links
[**Heroku**](https://tweb-te2-dagostino.herokuapp.com/)
## Intro
I decided to use the GitHub API, mainly because it was the only API name I recognized out of the list (and I preferred to work with something I was more familiar with, if possible), and I didn't really have any ideas as to how to illustrate CORS well.
## Setting up
I originally decided to use the `angular` generator, despite never having used it before, since it seemed to be the simplest base for an AngularJS application. After over an hour of errors all over the Heroku logs, I went back to the `Express` generator, which I'd used for a previous exercise and felt a *little* more comfortable with. Once I had the example page pushed to Heroku and working, I started on the code proper.
## Libraries used
* Node.js with the [Express framework](http://expressjs.com/)
* [AngularJS](https://angularjs.org/)
* [Chart.js](http://www.chartjs.org/), with [angular-chart.js](http://jtblin.github.io/angular-chart.js/) for Angular compatibility
* [Bootstrap](http://getbootstrap.com/) for templates
* [Jade](http://jade-lang.com/) template engine instead of pure HTML
* [GitHub API](https://developer.github.com/v3/), with the [github wrapper](https://github.com/michael/github)
## Features
* Pages were written in Jade instead of HTML, and the layout was therefore converted (and adapted) from an HTML Bootstrap theme.
* Uses of Angular:
* `ng-show` to only show some of the components once they have a reason to be there
* `ng-if` to wait until the correct data has been fetched before displaying it (using `ng-show` instead of this with chart.js leads to strange glitches)
* `ng-model` to handle input and fetching of data without refreshing the page
* Custom controller to fetch user and repo data from GitHub and format it for use with jade
* No reloading!
* Displays fun statistics about a user's repos!
## Overview
Opening the heroku app leads to a simple landing page asking for a username:
[](images/landing.png)
After having entered one, the page displays this user's most forked, watched, recently updated, and issue-prone public repositories. Since we use a wrapper for the GitHub API, the calls are very simple:
```
var github = new Github({
token: "<KEY>",
auth: "oauth"
});
```
We create an instance of our wrapper by using a personal access token, then use that to obtain user information, from the username we retrieved via Angular:
```
var user = github.getUser();
user.show(username, function(err, user) { ... });
user.userRepos(username, function(err, repos) { ... });
```
The statistics on the repositories are then done via simple array manipulations involving maps:
```
var max_fork_val = Math.max.apply(Math, repos.map(function(r){return r.forks_count}));
var max_fork_obj = repos.find(function(o){return o.forks_count == max_fork_val});
```
[](images/repo_best_of.png)
In order not to leave behind the less *special* repositories, the page also displays a neat little chart to let the viewer get an idea of the repositories' sizes compared to each other, again using maps:
[](images/repo_sizes.png)
## Difficulties
* **Making anything work on heroku**
I know in theory how it works, but in practice getting a successful deployment takes several commits and lots of swearing. In practice it also means pushing the components folder when I *really* shouldn't.
* **GitHub's spelling**
I spent over half an hour trying to figure out why the GitHub API wrapper was not working, before I realized that the object they use is in fact spelled "Github" and not "GitHub". Which is *wrong*.
* **Chart.js and ng-show**
As it turns out, using `angular-chart.js` with `ng-show` leads to a strange yet amusing glitch where the canvas containing the chart would fail to erase the previous chart if two usernames were entered back-to-back without refreshing the page. This would cause flickering and visual glitches while hovering over the chart, as the canvas would try to apply the hover functions of both charts at the same time.
## Known Issues
* Not an issue so much as a... *wrong* implementation, but due to issues with getting heroku to tell me where it hid the npm components files (after downloading and installing them successfully from [`package.json`](package.json), I went for the subtle solution of pushing the entire components folder to the repository. So, *technically*, it works fine, but it's incorrect.
## Conclusion
I'm fairly happy with the result given how little time I ended up being able to use to work on this (which, even after factoring in sacrificed sleep hours, was *not that much*), which I guess is a good sign, since I had relatively little trouble with the Angular side of things.
<file_sep>var app = angular.module("twebApp", ['chart.js']);
app.controller("GitHubController", function($scope) {
$scope.title = "Please enter a username below";
var github = new Github({
// this is an old token, kept as example. heroku uses a new one
token: "1<PASSWORD>",
auth: "oauth"
});
$scope.on_user = function(username) {
$scope.show = false
$scope.error = false
$scope.title = "Viewing the statistics of user " + username
var user = github.getUser();
user.show(username, function(err, user) {
if (err) {
$scope.error = "Error retrieving GitHub user"
return;
}
$scope.user = user
});
user.userRepos(username, function(err, repos) {
if (err) {
$scope.error = "Error retrieving GitHub repo"
return;
}
$scope.max_fork = {}
var max_fork_val = Math.max.apply(Math, repos.map(function(r){return r.forks_count}));
if (max_fork_val == 0) {
$scope.max_fork.text = "None of your repos have been forked!"
$scope.max_fork.url = ""
$scope.max_fork.url_text = ""
} else {
var max_fork_obj = repos.find(function(o){return o.forks_count == max_fork_val});
$scope.max_fork.text = max_fork_obj.name + " - " + max_fork_val + " forks"
$scope.max_fork.url = max_fork_obj.html_url
$scope.max_fork.url_text = "Go to " + max_fork_obj.name
}
$scope.max_watch = {}
var max_watch_val = Math.max.apply(Math, repos.map(function(r){return r.watchers_count}));
if (max_watch_val == 0) {
$scope.max_watch.text = "None of your repos have any watchers!"
$scope.max_watch.url = ""
$scope.max_watch.url_text = ""
} else {
var max_watch_obj = repos.find(function(o){return o.watchers_count == max_watch_val});
$scope.max_watch.text = max_watch_obj.name + " - " + max_watch_val + " watchers"
$scope.max_watch.url = max_watch_obj.html_url
$scope.max_watch.url_text = "Go to " + max_watch_obj.name
}
$scope.most_recent = {}
var most_recent_val = Math.max.apply(Math, repos.map(function(r){
return new Date(r.updated_at)
}));
var most_recent_obj = repos.find(function(o){
return new Date(o.updated_at).getTime() == new Date(most_recent_val).getTime()
});
$scope.most_recent.text = most_recent_obj.name + " - updated " + most_recent_obj.updated_at
$scope.most_recent.url = most_recent_obj.html_url
$scope.most_recent.url_text = "Go to " + most_recent_obj.name
$scope.max_issues = {}
var max_issues_val = Math.max.apply(Math, repos.map(function(r){return r.open_issues_count}));
if (max_issues_val == 0) {
$scope.max_issues.text = "None of your repos have any issues! Congrats!"
$scope.max_issues.url = ""
$scope.max_issues.url_text = ""
} else {
var max_issues_obj = repos.find(function(o){return o.open_issues_count == max_issues_val});
$scope.max_issues.text = max_issues_obj.name + " - " + max_issues_val + " open issues"
$scope.max_issues.url = max_issues_obj.html_url
$scope.max_issues.url_text = "Go to " + max_issues_obj.name
}
$scope.data = {}
$scope.data.sizes = repos.map(function(r){return r.size});
$scope.data.labels = repos.map(function(r){return r.name});
$scope.show = true;
$scope.$apply();
});
}
}); | 0874e286ee0f8ea5a5ae588beafba13870a6b63f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | paranoodle/TWEB-TE2 | 5f071bdbe5b1b00f4c47aa1de71f16c12e536cf9 | 589542eee566001bb54a63010a0296e385a82918 |
refs/heads/master | <repo_name>JamesBarciz/DS30-OOP-Sprint-Review<file_sep>/sprint_review/tests/conftest.py
import pytest
from ..review import BaseCharacter, Mage
@pytest.fixture()
def template_character():
return BaseCharacter('Rico')
@pytest.fixture()
def mage_character():
return Mage('Merlin')
<file_sep>/sprint_review/tests/test_review_other.py
from ..review import BaseCharacter, Mage
b0 = BaseCharacter('Rico')
m0 = Mage('Merlin')
def test_temp_level_one():
assert b0.level == 1
def test_temp_level_is_int():
assert isinstance(b0.level, int)
def test_mage_health_and_resource():
assert hasattr(m0, 'health')
assert hasattr(m0, 'mana')
def test_mage_greater_stats():
assert b0.intel < m0.intel
assert b0.stam < m0.stam
def test_level_up():
assert b0.level < b0.level_up().level
assert m0.level < m0.level_up().level
<file_sep>/sprint_review/review.py
class BaseCharacter:
"""This is the BaseCharacter model"""
def __init__(self, name):
self.name = name
self.intel = 3
self.stam = 3
self.strn = 3
self.agi = 3
self.level = 1
def level_up(self, increment=1):
"""
Levels up a character by a factor of `increment`
:param increment: (int) - the number of levels to level up - default: 1
"""
if increment < 1:
raise Exception('Parameter "increment" must be an integer greater than or equal to 1.')
dict_items = vars(self)
stat_increase = 3 * increment
for k, v in list(dict_items.items()):
if type(v) == int and k != 'level':
dict_items[k] += stat_increase
elif k == 'level':
dict_items[k] += increment
self.__dict__.update(dict_items)
if __name__ == '__main__':
print(f'{self.name} has reached level {self.level}!')
print(f'Intellect has increased by {stat_increase} to {self.intel}')
print(f'Stamina has increased by {stat_increase} to {self.stam}')
print(f'Strength has increased by {stat_increase} to {self.strn}')
print(f'Agility has increased by {stat_increase} to {self.agi}')
else:
return self
class Mage(BaseCharacter):
"""A class that inherits from BaseCharacter."""
def __init__(self, name):
super().__init__(name)
self.intel += 2
self.stam += 2
self.health = 50 + (self.stam * 5)
self.mana = 80 + (self.intel * 5)
def display_stats(self):
"""Displays character name as well as health/resource in block text."""
print(f'{self.name}\'s stats')
print(f'Total Health: {self.health}')
print(f'Total Mana: {self.mana}')
if __name__ == '__main__':
m0 = Mage('Merlin')
print('~~~~~~~~~~~~~~~~~~~')
m0.display_stats()
print('~~~~~~~~~~~~~~~~~~~')
print('Testing Level up with default')
m0.level_up()
print('~~~~~~~~~~~~~~~~~~~')
print('Testing Level up with value of 5')
m0.level_up(increment=5)
| e2743c097b2bf0a2865e94496a1635ec416b0242 | [
"Python"
] | 3 | Python | JamesBarciz/DS30-OOP-Sprint-Review | d494d94a95a57019f6078b0cf58eb1e335d6d95b | 39d51b4c18d8a65c000d2ac559408303c9e56117 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
// import ReactDOM from 'react-dom';
class Display extends Component {
state = {
}
render() {
const { firstName, lastName, email, phoneNumber, notes } = this.props;
return (
<React.Fragment>
<div className= "container bg-light displayBox sm-2">
<span className="l-3">
{firstName} {lastName}
</span>
<span> | { email }</span>
<span> | { phoneNumber }</span>
<span className= "overflow-hidden"> | notes: { notes }</span>
</div>
</React.Fragment>
);
}
}
export default Display;
<file_sep>import React, { Component } from 'react';
class ContactForm extends Component {
state = {
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
notes: '',
}
handleChange = (e) =>{
this.setState ({
[e.target.name] : e.target.value
})
}
onSubmit = (e)=> {
e.preventDefault();
this.props.onSubmit(this.state);
this.setState({
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
notes: '',
})
}
render() {
return (
<div className= "contact-form container text-center bg-light rounded">
<form className= "form-group " onSubmit={e=>this.onSubmit(e)}>
<label>first name:</label>
<input name="firstName" type="text" onChange={e=> this.handleChange(e)} value= { this.state.firstName } />
<br/>
<label > last name:</label>
<input name="lastName" onChange={e=> this.handleChange(e)} value= {this.state.lastName}/>
<br/>
<label htmlFor="email" >email:</label>
<input name="email" type="email" onChange={e=> this.handleChange(e)} value= {this.state.email}/>
<br/>
<label htmlFor="phone-number" >phone number:</label>
<input name="phoneNumber" type="text" onChange={e=> this.handleChange(e)} value={this.state.phoneNumber}/>
<br/>
<label htmlFor="notes" >notes:</label>
<input name="notes" type="text" onChange={e=> this.handleChange(e)} value= {this.state.notes}/>
<br/>
<input type="submit" value="add" />
</form>
</div>
);
}
}
export default ContactForm; | 0a597bc39c51f9a9ffac12e39d08a442bfbb3765 | [
"JavaScript"
] | 2 | JavaScript | Jmccaskey813/database | 4ba7ce0743376bfb0bc6cd45e0783b0b8440a229 | 8060b1ca8ebfe770e6063fe99680dbf5ac60df65 |
refs/heads/master | <file_sep>class Author
include Mongoid::Document
field :name
field :_id, type: String, default: ->{ name }
has_many :articles
end
<file_sep>class CommentsController < ApplicationController
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(article_params)
redirect_to @article, :notice => "Comment created!"
end
def article_params
params.require(:comment).permit(:content , :name)
end
end
| b8c6cc18f378703816ffe0717a0d8a988f4f299a | [
"Ruby"
] | 2 | Ruby | PawelMietelski/mongo-blog | 8850f88d9a9d5f5273a7765ebe9519c1fc13f584 | b8541ae7e4ce68c51b67c825d16238d2f7a67855 |
refs/heads/master | <file_sep>from Body import Body
from DragModel import DragModel as dm
import scipy as sp
import fluids as fl
class Integrator:
def __init__(self,planet,body, time_step):
self.body = body
self.planet = planet
self.time = 0
self.time_step = time_step
def updateTime(self):
self.time += self.time_step
def setTimeStep(self,dt):
self.time_step = dt
def calculateDrag(self):
drag_model = dm(self.body)
rho = drag_model.getAtmopshericDensity()
BC = self.body.getBallisticCoefficient()
v = self.body.getVelocity()
m = self.body.getMass()
cDa = m/BC
F_d = 0.5 * rho * v**2 * cDa
return F_d
def addDrag(self):
drag_force = self.calculateDrag()
self.body.addForce(drag_force)
def addForce(self,force):
self.body.addForce(force)
def calculate2Pertrubation(self):
J2 = 0.00108263
mu = self.body.getMu()
r = self.body.getRadius()
re = 6378*1000
pos = self.body.getPosition()
a_x = -mu/(r**3)*pos[0]-(3*mu)/(2*r**5)*R**2*J2*\
(1-5*(pos[2]/r)**2)*pos[0]
a_y = -mu/(r**3)*pos[1]-(3*mu)/(2*r**5)*R**2*J2*\
(1-5*(pos[2]/r)**2)*pos[1]
a_z = -mu/(r**3)*pos[3]-(3*mu)/(2*r**5)*R**2*J2*\
(1-5*(pos[2]/r)**2)*pos[3]
force = self.body.getMass() * [a_x,a_y,a_z]
return force
def addJ2Pertrubation(self):
force = self.calculate2Pertrubation()
self.addForce(force)
<file_sep>
import numpy as np
# Create drag model for earth
class EarthModel:
SELF_RADIUS = 6378 * 1000
SCALE_HEIGHT = 8570
SEA_DENSITY = 1.225
def getAtmosphericDensity(r):
h = r - cls.EARTH_RADIUS
rho = cls.SEA_DENSITY * np.exp(-cls.SCALE_HEIGHT/h)
return rho
<file_sep># Define the neccesary information for a body in orbit
import numpy as np
from numpy import linalg as LA
from Orbit import Orbit as orb
class Body():
# initalize body in orbit with instantenous classic orbit elements at any time
# include orbit
def __init__(self,r,v,f,mu,mass,BC):
self.position = r
self.velocity = v
self.force = f
self.mass = mass
self.ballisticCoefficent = BC
self.mu = mu
# def __init__(self, e, a, i, RAAN, w, f,mu):
self.orbit = orb(.5,100,45,45,0.2,1000)
## Getters and Setters for Force
def setForce(self,force):
self.force = force
def getForce(self):
return self.force
def addForce(self,force):
self.force = [sum(x) for x in zip(self.force, force)]
def getMu(self):
return self.mu
## ACCESS POSITIONS
def getRadiusVector(self):
return self.position
def getVelocityVector(self):
return self.velcoity
def getRadius(self):
return LA.norm(self.position)
def getVelocity(self):
return LA.norm(self.velocity)
def getAngularMomentumVector(self):
h = np.cross(self.position,self.velocity)
def getNodeVector(self):
h = self.getAngularMomentumVector()
n = np.cross([0,0,1], h)
return n
def getEccentricityVector(self):
n = self.getNodeVector()
v = self.getVelocity()
r = getRadius()
e = (v**2/self.mu - 1/r) * self.position - (np.dot(self.position,self.velocity)/self.mu) * self.velocity
return e
## METHODS TO UPDATE ORBIT
def getEccentricity(self):
e = self.getEccentricityVector()
return LA.norm(e)
def getInclination(self):
h = self.getAngularMomentumVector()
i = np.arccos(h[2]/LA.norm(h))
return np.rad2deg(i)
def getTrueAnomaly(self):
r = self.getRadius()
v = self.getVelocity()
e = self.getEccentricityVector()
f = 0
if np.dot(r,v) >= 0:
f = np.arccos(np.dot(e,r)/(LA.norm(e)*LA.norm(r)))
else:
f = 2*np.pi-np.arccos(np.dot(e,r)/(LA.norm(e)*LA.norm(r)))
return f
def getRAAN(self):
n = self.getNodeVector()
RAAN = 0
if n[1] >= 0:
RAAN = np.arccos(n[0]/LA.norm(n))
else:
RAAN = 2*np.pi-np.arccos(n[0]/LA.norm(n))
return np.rad2deg(RAAN)
def getArgPeriapsis(self):
n = self.getNodeVector()
e = self.getEccentricityVector()
w = 0
if e[2] >= 0:
w = np.arccos(np.dot(n,e)/(LA.norm(n)*LA.norm(e)))
else:
w = 2*pi-np.arccos(np.dot(n,e)/(LA.norm(n)*LA.norm(e)))
return w
def getSemiMajorAxis(self):
v = LA.norm(self.velocity)
r = LA.norm(self.position)
a = (2/r - v**2/self.mu)**-1
return a
def updateOrbit(self):
e = self.getEccentricity()
a = self.getSemiMajorAxis()
i = self.getInclination()
w = self.getArgPeriapsis()
f = self.getTrueAnomaly()
RAAN = self.getRAAN()
# def __init__(self, e, a, i, RAAN, w, f,mu):
self.orbit.setSemiMajorAxis(a)
self.orbit.setEccentricity(e)
self.orbit.setInclination(i)
self.orbit.setRAAN(RAAN)
self.orbit.setArgPeriapsis(w)
self.orbit.setTrueAnomaly(f)
.....................................
## DRAG CALC METHODS
def getBallisticCoefficient(self):
return self.ballisticCoefficent
def getMass(self):
return self.mass
<file_sep>import numpy as np
class Orbit():
def __init__(self, e, a, i, RAAN, w, f,mu):
self.a = a
self.e = e
self.i = np.deg2rad(i)
self.RAAN = RAAN
self.w = w
self.f = f
self.mu = mu
def getCartesianState(self):
r = self.a * \
(1 - self.e**2)/(1 + self.e \
* np.cos(self.f))
E = np.arccos((1 - r / self.a)/self.a)
p_r = r * [np.cos(self.f),np.sin(f),0]
one_term = np.sqrt(self.mu * self.a) / r
p_v = one_term * [-np.sin(E),np.sqrt(1 - self.e**2) * np.cos(E),0]
r_x = p_r[0]*(np.cos(self.w)*np.cos(self.RAAN)-\
np.sin(self.w)*np.cos(self.i)*np.sin(self.RAAN)) -\
p_r[1]*(np.sin(self.w)*np.cos(self.RAAN)+\
np.cos(self.w)*np.cos(self.i)*np.sin(self.RAAN))
r_y = p_r[0]*(np.cos(self.w)*np.sin(self.RAAN)+\
np.sin(self.w)*np.cos(self.i)*np.cos(self.RAAN)) +\
p_r[1]*(np.cos(self.w)*np.cos(self.i)*np.cos(self.RAAN) -\
np.sin(self.w)*np.sin(self.RAAN))
r_z = p_r[0]*(np.sin(self.w)*np.sin(self.i)) + \
p_r[1]*(np.cos(self.w)*np.sin(self.i))
radius = [r_x,r_y,r_z]
v_x = p_v[0]*(np.cos(self.w)*np.cos(self.RAAN) -\
np.sin(self.w)*np.cos(self.i)*np.sin(self.RAAN)) -\
p_v[1]*(np.sin(self.w)*np.cos(self.RAAN) +\
np.cos(self.w)*np.cos(self.i)*np.sin(self.RAAN))
v_y = p_v[0]*(np.cos(self.w)*np.sin(self.RAAN)+\
np.sin(self.w)*np.cos(self.i)*np.cos(self.RAAN)) +\
p_v[1]*(np.cos(self.w)*np.cos(self.i)*np.cos(self.RAAN) -\
np.sin(self.w)*np.sin(self.RAAN))
v_z = p_v[0]*(np.sin(self.w)*np.sin(self.i)) +\
p_v[1]*(np.cos(self.w)*np.sin(self.i))
velocity = [v_x,v_y,_v_z]
state = {'position':radius,'velcoity':velcoity}
return state
# Getter Setters
##
def getSemiMajorAxis(self):
return self.semi_major
def getEccentricity(self):
return self.eccentricity
def getInclination(self):
return np.rad2deg(self.inclination)
def getRAAN(self):
return self.RAAN
def getArgPeriapsis(self):
return self.periapsis
def getTrueAnomaly(self):
return self.true_anomaly
def setSemiMajorAxis(self, a):
self.semi_major = a
def setEccentricity(self,e):
self.eccentricity = e
def setInclination(self,i):
self.inclination = np.deg2rad(i)
def setRAAN(self,Ra):
self.RAAN = Ra
def setArgPeriapsis(self,w):
self.periapsis = w
def setTrueAnomaly(self,f):
self.true_anomaly = f
| 4be84c4062d16137c4dae98dc4b09e36ef221477 | [
"Python"
] | 4 | Python | kaustubh-vinchure/Orbital-Simulation | 20ef4f5fccb5b745b69a3534e51084879c4b41eb | 056e4e44a91758f8dd0a93e43c4109572408b469 |
refs/heads/master | <repo_name>evinces/calculator-2<file_sep>/list-arithmetic.py
"""Math functions for calculator."""
def add(num_list):
"""Return the sum of the two inputs."""
result = 0
for num in num_list:
result += num
return result
def subtract(num_list):
"""Return the second number subtracted from the first."""
result = 0
for num in num_list:
result -= num
return result
def multiply(num_list):
"""Multiply the two inputs together."""
result = 1
for num in num_list:
result *= num
return result
def divide(num_list):
"""Divide the first input by the second and return the result."""
result = num_list[0]
for i in range(1, len(num_list)):
result /= num_list[i]
return result
def square(num1):
"""Return the square of the input."""
# Needs only one argument
return num1 * num1
def cube(num1):
"""Return the cube of the input."""
# Needs only one argument
return num1 * num1 * num1
def power(num1, num2):
"""Raise num1 to the power of num and return the value."""
return num1 ** num2 # ** = exponent operator
def mod(num1, num2):
"""Return the remainder of num / num2."""
return num1 % num2
<file_sep>/calculator.py
"""A prefix-notation calculator.
Using the arithmetic.py file from Calculator Part 1, create the
calculator program yourself in this file.
"""
from arithmetic import *
# from list-arithmetic import *
# Your code goes here
def my_reduce(function, iterable):
result = iterable[0]
for i in range(1, len(iterable)):
result = function(result, iterable[i])
return result
while True:
user_input = raw_input("> ")
if user_input[0] == "q":
break
else:
tokens = user_input.split(" ")
try:
for i in range(1, len(tokens)):
tokens[i] = float(tokens[i])
except ValueError:
print "Please enter an operator followed by numbers."
continue
try:
if tokens[0] == "+":
print my_reduce(lambda x, y: add(x, y), tokens[1:])
elif tokens[0] == "-":
print my_reduce(lambda x, y: subtract(x, y), tokens[1:])
elif tokens[0] == "*":
print my_reduce(lambda x, y: multiply(x, y), tokens[1:])
elif tokens[0] == "/":
print my_reduce(lambda x, y: divide(x, y), tokens[1:])
elif tokens[0] == "square":
print square(tokens[1])
elif tokens[0] == "cube":
print cube(tokens[1])
elif tokens[0] == "pow":
print my_reduce(lambda x, y: power(x, y), tokens[1:])
elif tokens[0] == "mod":
print my_reduce(lambda x, y: mod(x, y), tokens[1:])
else:
print "Invalid command: Please try again."
except IndexError:
print "Invalid number of arguments."
| 4526eda43aa40e018603e5a04ae745b3b486b5df | [
"Python"
] | 2 | Python | evinces/calculator-2 | 44cfea12d31842dd3e5774873fe3e91c6b78198b | cd915763d031737d4c3faa1cb99a4fd9ed10f313 |
refs/heads/master | <repo_name>bbsyaya/Hiphop<file_sep>/Hiphop/views.py
from Base.decorator import require_get_params, Error
from Base.response import response, error_response
from Init.fileread import match
@require_get_params(['phrase', 'phrase_len', 'min_max_match'])
def match_phrase(request):
phrase = request.GET['phrase']
try:
phrase_len = int(request.GET['phrase_len'])
except:
phrase_len = 0
try:
min_max_match = int(request.GET['min_max_match'])
except:
min_max_match = 0
phonetics = phrase.split(' ')
o_phrase = list()
for phonetic in phonetics:
if phonetic[-1] in '01234':
t = phonetic[-1]
p = phonetic[:-1]
else:
t = ''
p = phonetic
o_phrase.append(dict(t=t, p=p))
o_phrase.reverse()
rtn = match(o_phrase, phrase_len=phrase_len, min_max_match=min_max_match)
if rtn.error is not Error.OK:
return error_response(rtn.error, append_msg=rtn.body)
return response(body=rtn.body)
<file_sep>/Base/decorator.py
import base64
from functools import wraps
from django.views.decorators import http
from Base.common import load_session, deprint
from Base.response import *
require_post = http.require_POST
require_get = http.require_GET
def require_get_params(r_params):
"""
需要获取的参数是否在request.GET中存在
"""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
for require_param in r_params:
if require_param not in request.GET:
return error_response(Error.REQUIRE_PARAM, append_msg=require_param)
return func(request, *args, **kwargs)
return wrapper
return decorator
def require_params(r_params, decode=True):
"""
需要获取的参数是否在request.POST中存在
"""
def decorator(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
for r_param in r_params:
if r_param in request.POST:
if decode:
x = request.POST[r_param]
c = base64.decodebytes(bytes(x, encoding='utf8')).decode()
request.POST[r_param] = c
else:
return error_response(Error.REQUIRE_PARAM, append_msg=r_param)
return func(request, *args, **kwargs)
return wrapper
return decorator
def require_json(func):
@wraps(func)
def wrapper(request, *args, **kwargs):
if request.body:
try:
request.POST = json.loads(request.body.decode())
except:
pass
return func(request, *args, **kwargs)
else:
return error_response(Error.REQUIRE_JSON)
return wrapper
def logging(func):
@wraps(func)
def wrapper(*args, **kwargs):
deprint('BGN -- ', func.__name__)
rtn = func(*args, **kwargs)
deprint('END --', func.__name__)
return rtn
return wrapper
def decorator_generator(verify_func, error_id):
"""
装饰器生成器
"""
def decorator(func):
def wrapper(request, *args, **kwargs):
if verify_func(request):
return func(request, *args, **kwargs)
return error_response(error_id)
return wrapper
return decorator
def require_login_func(request):
return load_session(request, 'user', once_delete=False) is not None
require_login = decorator_generator(require_login_func, Error.REQUIRE_LOGIN)
<file_sep>/Base/common.py
# from User.models import User
def deprint(*args):
from Hiphop.settings import DEBUG
if DEBUG:
print(*args)
def save_session(request, key, value):
request.session["saved_" + key] = value
def load_session(request, key, once_delete=True):
value = request.session.get("saved_" + key)
if value is None:
return None
if once_delete:
del request.session["saved_" + key]
return value
def login_to_session(request, o_user):
"""
更新登录数据并添加到session
:param request: HTTP请求
:param o_user: 用户
:return:
"""
try:
request.session.cycle_key()
except:
pass
save_session(request, 'user', o_user.pk)
return None
# def get_user_from_session(request):
# try:
# user_id = load_session(request, 'user', once_delete=False)
# return User.objects.get(pk=user_id)
# except:
# pass
# return None
| 930df7a1a91b47a7ed3e1337373f3756da813496 | [
"Python"
] | 3 | Python | bbsyaya/Hiphop | af103ac1a039d85b3b6d7c36ecaf83a7daf00815 | c8ed12d37c465ee0bbc45eb6d2a100ab293757f5 |
refs/heads/development | <file_sep>namespace TodoStore {
interface State {
todoList: Todo[];
}
interface Todo {
id: string;
checked: boolean;
done: boolean;
task: string;
atStart: number;
atEnd: number;
memo: string;
}
interface CreateTodoAction extends AnyAction {
type: typeof import("../../stores/todo").CREATE_TODO;
todo: Todo;
}
interface DeleteTodoAction extends AnyAction {
type: typeof import("../../stores/todo").DELETE_TODO;
index: number;
}
interface UpdateTodoAction extends AnyAction {
type: typeof import("../../stores/todo").UPDATE_TODO;
todo: Todo;
}
interface ActionCreators {
createTodo: (todo: Todo) => void;
deleteTodo: (index: number) => void;
updateTodo: (todo: Todo) => void;
}
export type TodoActions =
| CreateTodoAction
| DeleteTodoAction
| UpdateTodoAction;
}
<file_sep>interface State {
todo: TodoStore.State;
command: CommandStore.State;
}
<file_sep>export const loadState = (): null | TodoStore.State => {
try {
const serializedState = localStorage.getItem("state");
if (serializedState === null) {
return null;
}
return JSON.parse(serializedState);
} catch {
return null;
}
};
export const saveState = (state: TodoStore.State): void | false => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem("state", serializedState);
} catch {
return false;
}
};
<file_sep>import { createStore, Reducer } from "redux";
export const initialCommandState: CommandStore.State = {
command: null,
};
export const SET_COMMAND = "SET_COMMAND";
export const RESET_COMMAND = "RESET_COMMAND";
export const reducer: Reducer<
CommandStore.State,
CommandStore.CommandActions
> = (state = initialCommandState, action) => {
switch (action.type) {
case SET_COMMAND: {
const command = action.command;
return {
...state,
command,
};
}
case RESET_COMMAND: {
return {
...state,
command: null,
};
}
default: {
return state;
}
}
};
export const actionCreators = {
setCommand(command: CommandStore.Command): CommandStore.SetCommandAction {
return {
type: SET_COMMAND,
command,
};
},
resetCommand(): CommandStore.ResetCommandAction {
return {
type: RESET_COMMAND,
};
},
};
export default createStore(reducer);
<file_sep>---
name: 'Improvement Suggestions'
about: 'Improvement suggestions for web apps are here'
labels: improvement
---
## Details of Improvement
- as concise as possible
## Screenshot
<!-- If it's a bug, attach a screenshot of the developer tool console -->
## Expected behavior
- as concise as possible
## Environment
- OS
- macOS / Windows / Linux / iOS / Android
- Browser
- Chrome / Safari / Firefox / Edge / Internet Explorer
<file_sep>import { createStore, Reducer } from "redux";
import { loadState } from "../../utils/localStorage";
export const initialTodoState: TodoStore.State = loadState()
? {
todoList: loadState()!.todoList,
}
: {
todoList: [],
};
export const CREATE_TODO = "CREATE_TODO";
export const DELETE_TODO = "DELETE_TODO";
export const UPDATE_TODO = "UPDATE_TODO";
export const reducer: Reducer<TodoStore.State, TodoStore.TodoActions> = (
state = initialTodoState,
action
) => {
switch (action.type) {
case CREATE_TODO: {
const todoList = state.todoList;
todoList.push(action.todo);
return {
...state,
todoList,
};
}
case DELETE_TODO: {
const todoList = state.todoList;
todoList.splice(action.index, 1);
return {
...state,
todoList,
};
}
case UPDATE_TODO: {
const todoList = state.todoList;
const index = todoList.findIndex((todo) => todo.id === action.todo.id);
todoList[index] = action.todo;
return {
...state,
todoList,
};
}
default: {
return state;
}
}
};
export const actionCreators = {
createTodo(todo: TodoStore.Todo): TodoStore.CreateTodoAction {
return {
type: CREATE_TODO,
todo,
};
},
updateTodo(todo: TodoStore.Todo): TodoStore.UpdateTodoAction {
return {
type: UPDATE_TODO,
todo,
};
},
deleteTodo(index: number): TodoStore.DeleteTodoAction {
return {
type: DELETE_TODO,
index,
};
},
};
export default createStore(reducer);
<file_sep>import { combineReducers, createStore } from "redux";
import { reducer as commandReducer } from "./command";
import { reducer as todoReducer } from "./todo";
export default createStore(
combineReducers({
todo: todoReducer,
command: commandReducer,
})
);
<file_sep>namespace CommandStore {
interface State {
command: Command | null;
}
export type Command = "add" | "delete";
interface SetCommandAction extends AnyAction {
type: typeof import("../../stores/command").SET_COMMAND;
command: Command;
}
interface ResetCommandAction extends AnyAction {
type: typeof import("../../stores/command").RESET_COMMAND;
}
interface ActionCreators {
setCommand: (command: Command) => void;
resetCommand: () => void;
}
export type CommandActions = SetCommandAction | ResetCommandAction;
}
<file_sep>---
name: 'Bug Report'
about: 'Bug report for web apps are here'
labels: bug
---
## The Problem
- as concise as possible
## Screenshot
<!-- If it's a bug, attach a screenshot of the developer tool console -->
## Expected Behavior
- as concise as possible
## Steps to Reproduce
1. xxx
2. xxx
3. xxx
## Environment
- OS
- macOS / Windows / Linux / iOS / Android
- Browser
- Chrome / Safari / Firefox / Edge / Internet Explorer
<file_sep>import { makeStyles } from "@material-ui/core";
export const ListItemStyles = makeStyles({
current: {
backgroundColor: "#eee",
},
});
export const ListWrapStyles = makeStyles({
default: {
position: "relative",
},
});
export const ListStyles = makeStyles({
default: {
position: "absolute",
top: 0,
left: 0,
zIndex: 2,
width: "100%",
backgroundColor: "#fff",
border: "1px solid #cccccc",
borderTop: "none",
},
});
| 36b4db8207386eb3f6a28590a23bee5072ac939a | [
"Markdown",
"TypeScript"
] | 10 | TypeScript | kzhrk/ctodo | a09899aba09a08632d8cfa3e4fbe68df0ed072a8 | cac3857ef7d6cff8f2465539c5ebbfee871660eb |
refs/heads/main | <file_sep>starting mod for food expansion series, contains shared items used by all the mods
Requires Lost Core : Located here
Minecraft Version 1.12.2<file_sep>package com.lo93.foodexpansion.core.init.items;
import com.lo93.locore.LoCoreMain;
import com.lo93.locore.items.ItemBasic;
import net.minecraft.creativetab.CreativeTabs;
public class ModItems {
public static final ItemBasic TOOL_MORTARPESTAL = (ItemBasic) new ItemBasic("tool_mortarpestal").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic TOOL_KNIFE = (ItemBasic) new ItemBasic("tool_knife").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic ITEM_WHOLEFLOUR = (ItemBasic) new ItemBasic("item_wholeflour").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic ITEM_WHEATGRAIN = (ItemBasic) new ItemBasic("item_wheatgrain").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic TOOL_BAKINGTRAY = (ItemBasic) new ItemBasic("tool_bakingtray").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic ITEM_DOUGHBALLBASIC = (ItemBasic) new ItemBasic("item_doughballbasic").setCreativeTab(LoCoreMain.LOCORECREATIVETAB);
public static final ItemBasic TOOL_LOAFPAN = new ItemBasic("tool_loafpan");
}
| f330372bc036911fb10549b6f7a40624be7acbba | [
"Java",
"Text"
] | 2 | Text | lostjarred/MCFoodExCore | eb146ae361db826e4e489deee1e682a3977c209b | 18d3f968ec83c65dbfc256c70afa6ba101012be3 |
refs/heads/master | <file_sep>import { useState } from "react";
import "./SearchBar.scss";
const SearchBar = () => {
const [searchBarValue, setSearchBarValue] = useState("");
return (
<div className="searchBarContainer">
<input
type="text"
placeholder="Search for products, brands and categories..."
value={searchBarValue}
onChange={({ target }) => {
setSearchBarValue(target.value);
}}
/>
<div className="searchBarContainer__icon">
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
<title>search</title>
<path d="M9.516 14.016q1.875 0 3.188-1.313t1.313-3.188-1.313-3.188-3.188-1.313-3.188 1.313-1.313 3.188 1.313 3.188 3.188 1.313zM15.516 14.016l4.969 4.969-1.5 1.5-4.969-4.969v-0.797l-0.281-0.281q-1.781 1.547-4.219 1.547-2.719 0-4.617-1.875t-1.898-4.594 1.898-4.617 4.617-1.898 4.594 1.898 1.875 4.617q0 0.984-0.469 2.227t-1.078 1.992l0.281 0.281h0.797z"></path>
</svg>
</div>
</div>
);
};
export default SearchBar;
<file_sep>import "./BestSelling.scss";
const BestSelling = () => {
return (
<div className="bestSellingContainer">
<div className="bestSelling__header">Best Selling Products</div>
<div className="bestSelling__grid">
<div className="bestSelling__grid__item--1">
<h1 className="percentageTag">23% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/K/E/1_1521560987.jpg"
alt="<NAME>"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
<NAME> - 70c...
</h1>
<h2 className="bestSelling__grid__item--price">
₦6,200
<span className="bestSelling__grid__item--price--striked">
₦8,140
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦1,940
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">8% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/R/N/_1624899995.jpg"
alt="Tecno Spark 7"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Tecno Spark 7(pr651h)+ A3 A...
</h1>
<h2 className="bestSelling__grid__item--price">
₦49,200
<span className="bestSelling__grid__item--price--striked">
₦53,700
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦4,500
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">46% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/A/E/170618_1592630980.jpg"
alt="Superlife Stc30"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">Superlife Stc30</h1>
<h2 className="bestSelling__grid__item--price">
₦14,000
<span className="bestSelling__grid__item--price--striked">
₦26,000
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦12,000
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">45% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/F/J/81303_1625949316.jpg"
alt="Duracell Aa Battery"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Duracell Aa Battery - Set O...
</h1>
<h2 className="bestSelling__grid__item--price">
₦1,100
<span className="bestSelling__grid__item--price--striked">
₦2,000
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦900
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">9% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/P/L/118566_1562167803.jpg"
alt="Hennessy VS Cognac "
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Hennessy VS Cognac - 70cl ...
</h1>
<h2 className="bestSelling__grid__item--price">
₦16,335
<span className="bestSelling__grid__item--price--striked">
₦18,000
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦1,665
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">3% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/F/T/118566_1623532062.jpg"
alt="Infinix Note 10"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Infinix Note 10 (x693), Eme...
</h1>
<h2 className="bestSelling__grid__item--price">
₦77,000
<span className="bestSelling__grid__item--price--striked">
₦79,600
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦2,600
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">35% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/U/V/56095_1618768554.jpg"
alt="40,000mah Power Bank"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
40,000mah Power Bank With T...
</h1>
<h2 className="bestSelling__grid__item--price">
₦3,880
<span className="bestSelling__grid__item--price--striked">
₦6,000
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦2,120
</h4>
</div>
</div>
<div className="bestSelling__grid__item--8">
<h1 className="percentageTag">11% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/O/Q/_1617955315.jpg"
alt="Knorr Seasoning Cubes"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Knorr Seasoning Cubes Twin ...
</h1>
<h2 className="bestSelling__grid__item--price">
₦1,150
<span className="bestSelling__grid__item--price--striked">
₦1,300
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦150
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">5% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/I/F/_1613724537.jpg"
alt="Tecno Camon 15"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Tecno Camon 15 Air grey + A...
</h1>
<h2 className="bestSelling__grid__item--price">
₦62,460
<span className="bestSelling__grid__item--price--striked">
₦65,960
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦3,500
</h4>
</div>
</div>
<div className="bestSelling__grid__item">
<h1 className="percentageTag">6% OFF</h1>
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/H/A/118566_1620823035.jpg"
alt="Infinix Hot 10T"
/>
<div className="bestSelling__grid__item--details">
<h1 className="bestSelling__grid__item--name">
Infinix Hot 10T OCEAN- 64gb...
</h1>
<h2 className="bestSelling__grid__item--price">
₦64,000
<span className="bestSelling__grid__item--price--striked">
₦68,300
</span>
</h2>
<h4 className="bestSelling__grid__item--price--saved">
You save ₦4,300
</h4>
</div>
</div>
</div>
</div>
);
};
export default BestSelling;
<file_sep>import { useEffect, useState } from "react";
import "./App.scss";
import About from "./components/About/About";
import BestSelling from "./components/BestSelling/BestSelling";
import Brands from "./components/Brands/Brands";
import BtmPopup from "./components/BtmPopup/BtmPopup";
import CarouselGrid from "./components/CarouselGrid/CarouselGrid";
import Footer from "./components/Footer/Footer";
import Header from "./components/Header/Header";
import MidAdvert from "./components/MidAdvert/MidAdvert";
import Recommended from "./components/Recommended/Recommended";
import TodaysDeal from "./components/TodaysDeal/TodaysDeal";
import Variety from "./components/Variety/Variety";
function App() {
const [isBtmPopupVisible, setIsBtmPopupVisible] = useState(false);
useEffect(() => {
setIsBtmPopupVisible(true);
}, []);
return (
<div className="container">
<Header />
<CarouselGrid />
<Recommended />
<BestSelling />
<TodaysDeal />
<MidAdvert />
<Variety />
<Brands />
<About />
<Footer />
{isBtmPopupVisible && (
<BtmPopup setIsBtmPopupVisible={setIsBtmPopupVisible} />
)}
</div>
);
}
export default App;
<file_sep>import "./AdvertBar.scss";
const AdvertBar = ({ setIsAdvertBarVisible }) => {
return (
<div>
<img
className="advertBar"
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626062627/contentservice/web%20xxl.gif_BkcQJrKpu.gif"
alt="advert gif"
/>
<svg
className="closeAdvertBar"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
onClick={() => setIsAdvertBarVisible(false)}
>
<title>close-solid</title>
<path d="M2.93 17.070c-1.884-1.821-3.053-4.37-3.053-7.193 0-5.523 4.477-10 10-10 2.823 0 5.372 1.169 7.19 3.050l0.003 0.003c1.737 1.796 2.807 4.247 2.807 6.947 0 5.523-4.477 10-10 10-2.7 0-5.151-1.070-6.95-2.81l0.003 0.003zM11.4 10l2.83-2.83-1.41-1.41-2.82 2.83-2.83-2.83-1.41 1.41 2.83 2.83-2.83 2.83 1.41 1.41 2.83-2.83 2.83 2.83 1.41-1.41-2.83-2.83z"></path>
</svg>
</div>
);
};
export default AdvertBar;
<file_sep>import "./BtmPopup.scss";
const BtmPopup = ({ setIsBtmPopupVisible }) => {
return (
<div className="btmPopup">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1627296471/contentservice/prime2.gif_BkkkQG3Ad.gif"
alt=""
/>
<svg
className="closeBtmPopup"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
onClick={() => setIsBtmPopupVisible(false)}
>
<title>close-solid</title>
<path d="M2.93 17.070c-1.884-1.821-3.053-4.37-3.053-7.193 0-5.523 4.477-10 10-10 2.823 0 5.372 1.169 7.19 3.050l0.003 0.003c1.737 1.796 2.807 4.247 2.807 6.947 0 5.523-4.477 10-10 10-2.7 0-5.151-1.070-6.95-2.81l0.003 0.003zM11.4 10l2.83-2.83-1.41-1.41-2.82 2.83-2.83-2.83-1.41 1.41 2.83 2.83-2.83 2.83 1.41 1.41 2.83-2.83 2.83 2.83 1.41-1.41-2.83-2.83z"></path>
</svg>
</div>
);
};
export default BtmPopup;
<file_sep>import "./Recommended.scss";
const Recommended = () => {
return (
<div className="recommendedContainer">
<div className="recommendedMain">
<div className="recommendedMain__heading">
<h1 className="recommendedMain__title">Recommended for you</h1>
<p className="recommendedMain__link">See All Items</p>
</div>
<hr className="horizontalLine" />
<div className="recommendedMain__itemContainer">
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/H/X/57212_1613815526.jpg"
alt="McAfee Total Protection 2021"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
McAfee Total Protection 2021 1 D...
</h1>
<h2 className="recommendedMain__item--price">₦6,000 </h2>
</div>
</div>
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/M/E/118566_1578404432.jpg"
alt="Polystar 32-inch Led Tv"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
Polystar 32-inch Led Tv - Pv-hd3...
</h1>
<h2 className="recommendedMain__item--price">
₦69,120
<span className="recommendedMain__item--price--striked">
₦73,290
</span>
</h2>
<h4 className="recommendedMain__item--price--saved">
You save ₦4,170
</h4>
</div>
</div>
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/Y/P/_1617104186.jpg"
alt="Vivo Y20 Nebula Blue"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
Vivo Y20 Nebula Blue - 3gb Ram, ...
</h1>
<h2 className="recommendedMain__item--price">
₦73,615
<span className="recommendedMain__item--price--striked">
₦76,500
</span>
</h2>
<h4 className="recommendedMain__item--price--saved">
You save ₦2,885
</h4>
</div>
</div>
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/C/J/118566_1612452596.jpg"
alt="Nokia Grey 3.4"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
Nokia Grey 3.4 - 6.39" Hd+4gb
</h1>
<h2 className="recommendedMain__item--price">
₦56,750
<span className="recommendedMain__item--price--striked">
₦58,000
</span>
</h2>
<h4 className="recommendedMain__item--price--saved">
You save ₦1,250
</h4>
</div>
</div>
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/T/C/118566_1620808982.jpg"
alt="Lenovo Ideapad L3"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
Lenovo Ideapad L3 151ML05, Intel...
</h1>
<h2 className="recommendedMain__item--price">
₦229,999
<span className="recommendedMain__item--price--striked">
₦300,000
</span>
</h2>
<h4 className="recommendedMain__item--price--saved">
You save ₦70,001
</h4>
</div>
</div>
<div className="recommendedMain__item">
<img
src="https://www-konga-com-res.cloudinary.com/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/media/catalog/product/I/Q/118566_1615976339.jpg"
alt="Dell Vostro 3500"
className="recommendedMain__item--img"
/>
<div className="recommendedMain__item--details">
<h1 className="recommendedMain__item--name">
Dell Vostro 3500, 11th Gen, Inte...
</h1>
<h2 className="recommendedMain__item--price">
₦199,999
<span className="recommendedMain__item--price--striked">
₦208,500
</span>
</h2>
<h4 className="recommendedMain__item--price--saved">
You save ₦8,501
</h4>
</div>
</div>
</div>
</div>
<div className="recommendedSub">
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012718/contentservice/groceries.png_BJi7huuaO.png"
alt="Groceries"
/>
</div>
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012728/contentservice/kitchenn%20needs.png_BylHh_d6u.png"
alt="Kitchen Needs"
/>
</div>
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012731/contentservice/video%20games.png_SyzHhO_ad.png"
alt="Video Games"
/>
</div>
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012727/contentservice/agric.png_S1aE3u_Td.png"
alt="Fertilizers ,seeds and more"
/>
</div>
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012736/contentservice/hometheatres.png_rkQHn_uad.png"
alt="Home Theatres"
/>
</div>
<div className="recommendedSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012728/contentservice/furntures.png_Hkerhudp_.png"
alt="Furniture"
/>
</div>
</div>
</div>
);
};
export default Recommended;
<file_sep>import "./Variety.scss";
const Variety = () => {
return (
<div className="varietyContainer">
<div className="variety__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012741/contentservice/computing.png_HJXHnOup_.png"
alt="Computer Accessories"
/>
<div className="variety__item--details">
<h1>XXL Savings on All Tech Accessories</h1>
<h4>Up to 60% off</h4>
<h2>
SHOP NOW
<span>
<svg
height="17"
viewBox="0 0 10 17"
width="10"
aria-label="chevron-next"
name="chevron-next"
>
<path d="M.462 2.588a1.496 1.496 0 0 1 0-2.16c.603-.58 1.567-.569 2.135.013L9.54 7.127c.297.285.461.68.461 1.08 0 .41-.163.793-.46 1.08l-6.944 6.686a1.543 1.543 0 0 1-2.135 0 1.496 1.496 0 0 1 0-2.16l5.834-5.618L.462 2.588zm.726-.728a.479.479 0 0 0 .02.02l-.02-.02z"></path>
</svg>
</span>
</h2>
</div>
</div>
<div className="variety__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012718/contentservice/fitness.png_r1TQ3OdTd.png"
alt="Dumbbells, mats and jump ropes"
/>
<div className="variety__item--details">
<h1>Fitness Equipments at XXL Discounts</h1>
<h4>Up to 60% off Any Item You Want</h4>
<h2>
SHOP NOW{" "}
<span>
<svg
height="17"
viewBox="0 0 10 17"
width="10"
aria-label="chevron-next"
name="chevron-next"
>
<path d="M.462 2.588a1.496 1.496 0 0 1 0-2.16c.603-.58 1.567-.569 2.135.013L9.54 7.127c.297.285.461.68.461 1.08 0 .41-.163.793-.46 1.08l-6.944 6.686a1.543 1.543 0 0 1-2.135 0 1.496 1.496 0 0 1 0-2.16l5.834-5.618L.462 2.588zm.726-.728a.479.479 0 0 0 .02.02l-.02-.02z"></path>
</svg>
</span>
</h2>
</div>
</div>
<div className="variety__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012706/contentservice/kids.png_By9Q3udTu.png"
alt="Kid Wears and Accessories"
/>
<div className="variety__item--details">
<h1>XXL Discounts Off Baby Accessories</h1>
<h4>Save Up to 60%</h4>
<h2>
SHOP NOW
<span>
<svg
height="17"
viewBox="0 0 10 17"
width="10"
aria-label="chevron-next"
name="chevron-next"
>
<path d="M.462 2.588a1.496 1.496 0 0 1 0-2.16c.603-.58 1.567-.569 2.135.013L9.54 7.127c.297.285.461.68.461 1.08 0 .41-.163.793-.46 1.08l-6.944 6.686a1.543 1.543 0 0 1-2.135 0 1.496 1.496 0 0 1 0-2.16l5.834-5.618L.462 2.588zm.726-.728a.479.479 0 0 0 .02.02l-.02-.02z"></path>
</svg>
</span>
</h2>
</div>
</div>
<div className="variety__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012725/contentservice/tv.png_Bk2Vhd_pO.png"
alt="QLED,OLED & LED TVs"
/>
<div className="variety__item--details">
<h1>XXL Savings off QLED,OLED & LED TVs</h1>
<h4>Up to 60% off</h4>
<h2>
SHOP NOW
<span>
<svg
height="17"
viewBox="0 0 10 17"
width="10"
aria-label="chevron-next"
name="chevron-next"
>
<path d="M.462 2.588a1.496 1.496 0 0 1 0-2.16c.603-.58 1.567-.569 2.135.013L9.54 7.127c.297.285.461.68.461 1.08 0 .41-.163.793-.46 1.08l-6.944 6.686a1.543 1.543 0 0 1-2.135 0 1.496 1.496 0 0 1 0-2.16l5.834-5.618L.462 2.588zm.726-.728a.479.479 0 0 0 .02.02l-.02-.02z"></path>
</svg>
</span>
</h2>
</div>
</div>
</div>
);
};
export default Variety;
<file_sep>import { useEffect, useState } from "react";
import AdvertBar from "./AdvertBar/AdvertBar";
import SearchBar from "./SearchBar/SearchBar";
import "./Header.scss";
const Header = () => {
const [isAdvertBarVisible, setIsAdvertBarVisible] = useState(false);
useEffect(() => {
setIsAdvertBarVisible(true);
}, []);
return (
<div className="headerContainer">
{isAdvertBarVisible && (
<AdvertBar setIsAdvertBarVisible={setIsAdvertBarVisible} />
)}
<div className="header__options">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/k_travels2.png"
alt="travel"
/>
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/konga_pay.png"
alt="KongaPay"
/>
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/new_konga_drinks.png"
alt="drinks"
/>
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/konga_health.png"
alt="KongaHealth"
/>
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/k_express2.png"
alt="logistics"
/>
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/assets/images/homepage/new_konga_groceries.png"
alt="groceries"
/>
</div>
<div className="header__mainNav">
<img
className="header__mainNav--img"
src="https://www.konga.com/_next/static/images/62f8a0d88e07573b4d46735aa24f3f04.png"
alt="logo"
/>
<p className="header__mainNav--text">Store Locator</p>
<p className="header__mainNav--text">Sell on Konga</p>
<SearchBar />
<p className="header__mainNav--text">Help</p>
<p className="header__mainNav--text">Login / Signup</p>
<button className="header__mainNav--btn">
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
<title>local_grocery_store</title>
<path d="M17.016 18q0.797 0 1.383 0.609t0.586 1.406-0.586 1.383-1.383 0.586-1.406-0.586-0.609-1.383 0.609-1.406 1.406-0.609zM0.984 2.016h3.281l0.938 1.969h14.813q0.422 0 0.703 0.305t0.281 0.727q0 0.047-0.141 0.469l-3.563 6.469q-0.563 1.031-1.734 1.031h-7.453l-0.891 1.641-0.047 0.141q0 0.234 0.234 0.234h11.578v2.016h-12q-0.797 0-1.383-0.609t-0.586-1.406q0-0.469 0.234-0.938l1.359-2.484-3.609-7.594h-2.016v-1.969zM6.984 18q0.797 0 1.406 0.609t0.609 1.406-0.609 1.383-1.406 0.586-1.383-0.586-0.586-1.383 0.586-1.406 1.383-0.609z"></path>
</svg>
My Cart <span>0</span>
</button>
</div>
<div className="header__subNav">
<ul>
<li className="header__subNav--item--1">
All Categories
<svg
version="1.1"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
>
<title>dehaze</title>
<path d="M2.016 5.484h19.969v2.016h-19.969v-2.016zM2.016 10.5h19.969v2.016h-19.969v-2.016zM2.016 15.516h19.969v1.969h-19.969v-1.969z"></path>
</svg>
</li>
<li>Computers and Accessories</li>
<li>Phones and Tablets</li>
<li>Electronics</li>
<li>Konga Fashion</li>
<li>Home and Kitchen</li>
<li>Baby, Kids and Toys</li>
<li>Other Categories</li>
</ul>
</div>
</div>
);
};
export default Header;
<file_sep>import "./MidAdvert.scss";
const MidAdvert = () => {
return (
<div className="midAdvertContainer">
<div className="midAdvertMain">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1627046765/contentservice/5k%20web.png_By4dQSuC_.png"
alt="Eid Advert 1"
/>
</div>
<div className="midAdvertSub">
<div className="midAdvertSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012718/contentservice/2%20bottom%20a_.png_BkBN3OOTd.png"
alt="Eid Advert 2"
/>
</div>
<div className="midAdvertSub__item">
<img
src="https://www-konga-com-res.cloudinary.com/image/upload/w_auto,f_auto,fl_lossy,dpr_auto,q_auto/v1626012730/contentservice/2%20bottom%20b.png_Hygrh__Td.png"
alt="Eid Advert 3"
/>
</div>
</div>
</div>
);
};
export default MidAdvert;
<file_sep>import "./About.scss";
const About = () => {
return (
<div className="aboutContainer">
<h1 className="aboutTitle">
Online Shopping on Konga.com – Nigeria’s Largest Online Mall
</h1>
<p className="aboutDisclaimer">
This site is a clone and was created for learning purposes.
</p>
<p className="aboutText">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum quos
maiores labore odio aliquam impedit cum provident nostrum quidem, odit
dolorum perspiciatis qui placeat natus ducimus saepe, vero omnis error
fugit, laboriosam voluptate exercitationem accusantium sequi
perferendis! Explicabo ea incidunt voluptatem quibusdam. Doloribus,
repellat ea? Ex ipsa eaque dolor soluta inventore optio. Voluptatum sit
maxime et molestias omnis aliquam cupiditate nesciunt iure minima
molestiae. Nisi adipisci odit perspiciatis voluptatem vero incidunt
architecto sint aperiam, laudantium autem culpa distinctio illo quasi
modi maiores debitis ipsa numquam natus hic dolor aliquid nihil. Lorem
ipsum dolor sit amet consectetur adipisicing elit. Earum quos maiores
labore odio aliquam impedit cum provident nostrum quidem, odit dolorum
perspiciatis qui placeat natus ducimus saepe, vero omnis error fugit,
laboriosam voluptate exercitationem accusantium sequi perferendis!
Explicabo ea incidunt voluptatem quibusdam. Doloribus, repellat ea? Ex
ipsa eaque dolor soluta inventore optio. Voluptatum sit maxime et
molestias omnis aliquam cupiditate nesciunt iure minima molestiae. Nisi
adipisci odit perspiciatis voluptatem vero incidunt architecto sint
aperiam, laudantium autem culpa distinctio illo quasi modi maiores
debitis ipsa numquam natus hic dolor aliquid nihil.
</p>
</div>
);
};
export default About;
| d5ce65c4b3faece545a4230da70556fbc5edc8ed | [
"JavaScript"
] | 10 | JavaScript | akindoju/konga-clone | 81bad1f1c59d978cf520596695e892d6d84495b6 | a2c7705d155c7f98956131562d3fece79e484d88 |
refs/heads/master | <file_sep>ANSIBLE_GALAXY=$(shell which ansible-galaxy)
install:
$(ANSIBLE_GALAXY) install -r requirements.yml -p roles --force
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network "forwarded_port", guest: 22, host: 2223
# influxdb
config.vm.network "forwarded_port", guest: 8083, host: 8083
config.vm.network "forwarded_port", guest: 8086, host: 8086
config.vm.network "forwarded_port", guest: 8090, host: 8090
config.vm.network "forwarded_port", guest: 8099, host: 8099
# consul
config.vm.network "forwarded_port", guest: 8600, host: 8600
config.vm.network "forwarded_port", guest: 3000, host: 3000
config.vm.network "private_network", ip: "192.168.33.20"
# config.vm.network "public_network"
# config.vm.synced_folder "../data", "/vagrant_data"
# config.vm.provider "virtualbox" do |vb|
# vb.gui = true
# vb.memory = "1024"
# end
# Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
# such as FTP and Heroku are also available. See the documentation at
# https://docs.vagrantup.com/v2/push/atlas.html for more information.
# config.push.define "atlas" do |push|
# push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
# end
config.vm.hostname = 'vagrant.local'
config.vm.provision :ansible do |ansible|
ansible.playbook = 'site.yml'
ansible.sudo = true
# ansible.inventory_path = 'inventory/vagrant-inventory'
ansible.host_key_checking = false
end
end
| 61b7230e667f666990e6f9f4c35b962c793e8a4a | [
"Makefile",
"Ruby"
] | 2 | Makefile | k-nii0211/ansible-example | 5063757c059c0a970fb744fc480317da69da65c4 | 7f775cd26dd6f0e75a3e5c1b1fb96cf9c2311745 |
refs/heads/master | <file_sep>package tlcnet.udptest;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Arrays;
/* TODO: What if the Server starts listening after the Client has started transmitting?
* The first received pkt has SN > 1.
* Should we consider this an error and abort?
*/
public class Server {
static final int DEF_CHANNEL_PORT = 65432;
static final int DEF_SERVER_PORT = 65433;
private static final short END_TIMEOUT = 20000; //To stop waiting for pcks
private static final int RX_BUFSIZE = 2048; // Exceeding data will be discarded: note that such a datagram would be fragmented by IP
// When the write buffer exceeds this number of bytes, it is written on the output file
private static final int WRITEBUF_THRESH = 20 * 1024;
public static void main(String[] args) {
int listenPort = DEF_SERVER_PORT;
int channelPort = DEF_CHANNEL_PORT;
int clientPort = Client.DEF_CLIENT_PORT;
InetAddress clientAddr = null;
String filename = null;
FileOutputStream fileOutputStream = null;
// Check input parameters
if (args.length != 2) {
System.out.println("Usage: java Server <client address> <path to new file>");
return;
}
try {
// Get address of client from command line parameter
clientAddr = InetAddress.getByName(args[0]);
// Create output file and overwrite if it already exists
filename = args[1];
fileOutputStream = new FileOutputStream(filename, false);
} catch (UnknownHostException e) {
System.err.println(e); return;
} catch (FileNotFoundException e) {
System.err.println("Cannot create file!\n" + e);
}
// --- Create the socket ---
DatagramSocket socket = null;
try {
socket = new DatagramSocket(listenPort);
socket.setSoTimeout(END_TIMEOUT);
}
catch(SocketException e) {
System.err.println("Error creating a socket bound to port " + listenPort);
System.exit(-1);
}
// * * * * * * * * * * * * * *//
// * * DATA TRANSFER LOOP * *//
// * * * * * * * * * * * * * *//
// Create output stream to write received data. This is periodically emptied on the out file.
ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream();
boolean gotFIN = false; //Needed to stop the cycle
while(!gotFIN)
{
// ---- Receive packet ----
byte[] recvBuf = new byte[RX_BUFSIZE];
DatagramPacket recvPkt = new DatagramPacket(recvBuf, recvBuf.length);
try{
socket.receive(recvPkt);
}
catch (SocketTimeoutException e) {
System.out.println("Closing connection: FIN not received...");
break;
}
catch(IOException e) {
System.err.println("I/O error while receiving datagram:\n" + e);
socket.close(); System.exit(-1);
}
// ---- Process packet and prepare new packet ----
byte[] recvData = Arrays.copyOf(recvPkt.getData(), recvPkt.getLength()); // payload of recv UDP packet
UTPpacket recvUTPpkt = new UTPpacket(recvData); // parse payload
InetAddress channelAddr = recvPkt.getAddress(); // get sender (=channel) address and port
UTPpacket sendUTPpkt = new UTPpacket();
sendUTPpkt.dstAddr = clientAddr;
sendUTPpkt.dstPort = (short) clientPort;
sendUTPpkt.sn = recvUTPpkt.sn;
sendUTPpkt.payl = new byte[0];
switch (recvUTPpkt.function) {
case UTPpacket.FUNCT_DATA:
sendUTPpkt.function = UTPpacket.FUNCT_ACKDATA;
break;
case UTPpacket.FUNCT_FIN:
sendUTPpkt.function = UTPpacket.FUNCT_ACKFIN;
gotFIN = true;
break;
default:
System.out.println("Wut?");
System.exit(-1);
}
byte[] sendData = sendUTPpkt.getRawData(); // payload of outgoing UDP datagram
//DEBUG
System.out.println("\n------ RECEIVED\nHeader:\n" + Utils.byteArr2str(Arrays.copyOf(recvData, UTPpacket.HEADER_LENGTH)));
System.out.println("SN=" + recvUTPpkt.sn + "\nPayload length = " + recvUTPpkt.payl.length);
if(gotFIN)
System.out.println("Oh, this is a FIN! I'll ack it right away!");
// Append received packet to the ByteArrayOutputStream
// TODO: (for the Client as well) Maybe read/write asynchronously from/to file so as to optimize computational time for I/O operations?
try {
writeBuffer.write(recvUTPpkt.payl);
}
catch(IOException e) {
System.out.println("Error while putting data back together");
}
// If the buffer is too large, write it on file (append) and empty it.
if (writeBuffer.size() > WRITEBUF_THRESH) {
writeBufferToFile(writeBuffer, fileOutputStream);
}
// --- Send ACK or FINACK ---
DatagramPacket sendPkt = new DatagramPacket(sendData, sendData.length, channelAddr, channelPort);
try{
socket.send(sendPkt);
}
catch(IOException e) {
System.err.println("I/O error while sending datagram:\n" + e);
socket.close(); System.exit(-1);
}
}
System.out.println("Bye bye, Client! ;-)");
// Write the remaining data in the buffer to the file
writeBufferToFile(writeBuffer, fileOutputStream);
}
private static void writeBufferToFile(ByteArrayOutputStream buffer,
FileOutputStream fileOutputStream) {
System.out.println("\n - - Writing " + buffer.size() + " bytes to disk");
try {
fileOutputStream.write(buffer.toByteArray());
buffer.reset();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}<file_sep>package tlcnet.udptest;
public class Utils {
public static int[] byteArr2intArr(byte[] in) {
int[] out = new int[in.length];
for (int i = 0; i < in.length; i++) {
out[i] = in[i] & 0xff; // range 0 to 255
}
return out;
}
public static String byteArr2str(byte[] in) {
String out = "";
for (int i = 0; i < in.length; i++) {
out += " " + (in[i] & 0xff); // range 0 to 255
}
return out;
}
}
| c0aeec0cbd3a33a3d251c2c8f4d5392f09d367e1 | [
"Java"
] | 2 | Java | tlcdt/udptransfer | 614e875473c35dcccad3405c1bf877d463c9a927 | 2b1694903722e102b7edb9db1c72701bacf51e72 |
refs/heads/master | <file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"student")==0 || strcmp($_SESSION['user_type'],"teacher")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Admin Here!!</h4>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<center><h2>Welcome Admin!!</h2></br>
<p><h3>Today is: <?php echo date("Y-m-d") . "<br />"; ?></h3></p>
<p>Here, you can manage users, update subjects, routines, accouting...</p>
</center>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep></head>
<body>
<!-- Main site container -->
<div id="siteBox">
<!-- Main site header : holds the img, title and top tabbed menu -->
<div id="header">
<!-- top rounded corner -->
<img src="images/corner_tl.gif" alt="corner" style="float:left;" />
<!-- Site title and subTitle -->
<span class="title">
<span>School Management System</span>
<span class="subTitle">
SMS
</span>
</span>
<?php
if(!isset($_SESSION['user_type'])) {
?>
<!-- Menu is displayed in reverse order from how you define it (caused by float: right) -->
<a href="login.php" title="login" class="lastMenuItem">Login</a>
<a href="aboutus.php" title="about us">about us</a>
<a href="index.php" title="home" class="active">home<span class="desc">welcome</span></a>
<?php
}
else {
?>
<a href="logout.php" title="logout" class="lastMenuItem">Logout</a>
<?php
if(strcmp($_SESSION['user_type'],"admin")== 0){
echo ' <a href="admin/profile.php" title="profile" >Profile</a>';
echo '<a href="admin/account.php" title="routine">Account<span class="desc">Section</span></a>';
echo '<a href="admin/routines.php" title="routine">Routines</a>';
echo '<a href="admin/admin_subject.php" title="subject">Subjects</a>';
echo '<a href="admin/users.php" title="users">Users<span class="desc">Manage Users</span></a>';
}
else if(strcmp($_SESSION['user_type'],"teacher")== 0){
echo ' <a href="teacher/profile.php" title="profile" >Profile</a>';
echo '<a href="teacher/routines.php" title="routine">Routines</a>';
}
else if(strcmp($_SESSION['user_type'],"student")== 0){
echo '<a href="student/profile.php" title="profile" >Profile</a>';
echo '<a href="student/routines.php" title="routine">Routines</a>';
}
?>
<a href="index.php" title="home" >home<span class="desc">welcome</span></a>
<?php
}
?>
</div><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
</p>
<p>
<?php echo'<a href="teacher_details.php?id='.$_GET['id'].'" class="menuItem">Back</a>' ?>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(empty($_GET['id'])) {
$session->message("No teacher ID was provided.");
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!(Subject::assign_subject($_POST))) {
$session->message("Subject already assigned.");
}
redirect_to("teacher_details.php?id=".$_POST['teacher_id']);
}
?>
<form method="POST" action="" id="add_student" name="add">
<fieldset>
<legend>Assign Subject</legend>
<label>Subject:<label/>
<SELECT NAME="subject_id">
<OPTION VALUE=0>Choose
<?php // echo $options;?>
<?php echo Subject::get_all_subject_option() ;?>
</SELECT> </br><br/>
<input type="hidden" name = "teacher_id" value = "<?php echo $_GET['id']; ?>">
<input type="submit" name="add_btn" value="Assign"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
foreach($_POST as $key=>$value){
$_SESSION['form_data']['address'][$key]=$value;
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="#" class="menuItem">Add Student</a>
<a href="#" class="menuItem">Add Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<form method="POST" action="add_previous.php" id="add_parent" name="add">
<fieldset>
<legend>Parent Information</legend>
<label>Parent's details:</label><br/>
<label>First Name:<label/>
<input type="text" name="p_fname" required="true"/><br/>
<label>Middle Name:</label>
<input type="text" name="p_mname" /><br/>
<label>Last Name:<label/>
<input type="text" name="p_lname" required="true"/><br/>
<label>Gender</label><br/>
<input type="radio" name="p_gender" value="male">Male
<input type="radio" name="p_gender" value="female">Female<br/>
<label>Occupation:<label/>
<input type="text" name="occupation" required="true"/><br/>
<label>Relationship:<label/>
<input type="text" name="relation" required="true"/><br/>
<label>Mobile No. :<label/>
<input type="text" name="mobile_no" required="true"/><br/>
<label>Email :<label/>
<input type="text" name="p_email"/><br/>
<br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once("includes/initialize.php"); ?>
<?php if($session->is_logged_in()) {
redirect_to($_SESSION['user_type']."/index.php");
}
?>
<?php include_layout_template('header.php'); ?>
<?php include_layout_template('menu.php'); ?>
<?php include_layout_template('content_start.php'); ?>
<?php include_layout_template('content_right_start.php'); ?>
<p>
<h1><center>SCHOOL MANAGEMENT SYSTEM</center></h1>
</p>
<?php include_layout_template('content_end.php'); ?>
<?php include_layout_template('footer.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Attendance here!!</h4>
</p>
<p>
<a href="take_attendance.php" class="menuItem">Take Attendance</a>
<a href="view_attendance.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
$class_id = Teacher::check_classteacher($_SESSION['user_id']);
if(!$class_id) {
echo "You are not allowed to access this section!".'</br>';
}
else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$attendance = Teacher::view_attendance($_POST);
if(!empty($attendance)) {
echo "Date: ".$_POST['date']."<br/>";
?>
<table class="bordered">
<tr>
<th>Student </th>
<th>Status</th>
<!-- <th>Action</th> -->
</tr>
<?php foreach($attendance as $a) { ?>
<tr>
<td><?php echo full_name($a['fname'],$a['lname'],$a['mname']); ?></td>
<td><?php echo $a['status']; ?></td>
<!-- <td><a href="#">Edit</a></td> -->
</tr>
<?php } ?>
</table>
<?php
}
}
else {
?>
<form method="POST" action="" >
<fieldset>
<legend>View Attendance</legend>
<label>Date:<label/>
<SELECT NAME="date">
<?php Teacher::get_all_date_option($class_id) ;?>
</SELECT> </br><br/>
<input type="hidden" name="class_id" value="<?php echo $class_id; ?>"/>
<input type="submit" name="submit" value="View"/><br/><br/>
</fieldset>
</form>
<?php
}
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Attendance here!!</h4>
</p>
<p>
<a href="take_attendance.php" class="menuItem">Take Attendance</a>
<a href="view_attendance.php" class="menuItem">View Attendance</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<p><h4>In this section the class teacher can take attendance of students of their respective classes.</h4></p>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Student extends DatabaseObject {
public static function get_my_class($id) {
global $database;
$sql = "SELECT class_id FROM student WHERE id = '".$id."'";
$result = $database->query($sql);
$result = $database->fetch_array($result);
return $result['class_id'];
}
public static function view_attendance($id) {
global $database;
$sql = "SELECT * from student_attendance where student_id ='".$id."' Order by date";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;
}
}<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"teacher")==0 || strcmp($_SESSION['user_type'],"admin")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
$class = Student::get_my_class($_SESSION['user_id']);
// foreach($class as $key => $c) {
// $class[$key]['routine'] = Routine::find_by_id($c['class_id']);
// }
$routine=Routine::find_by_id($class);
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Student's Section!</h4>
<h5>View Routine!!</h5>
</p>
<p><a href="index.php" class="menuItem">BACK</a></p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php if(!empty($routine)){ ?>
<caption>Your Routine</caption>
<table class="bordered">
<tr>
<th>Preview</th>
<th>Class</th>
<th>Type</th>
</tr>
<?php
?>
<tr>
<td><img class = "routine" src="../<?php echo $routine->image_path(); ?>" width="100" /></td>
<td><?php echo $routine->class; ?></td>
<td><?php echo upcase($routine->image_type); ?></td>
</tr>
</table>
<?php }else{
echo output_message("There are no routines for you.");
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php $students = Admin::find_all_student(); ?>
<?php
foreach($students as $student)
{
echo '<a href = "student_details.php?id='.$student['id'].'">'.full_name($student['fname'],$student['lname'],$student['mname']).'</a>'.'</br>';
}
?><file_sep><?php
require_once(LIB_PATH.DS.'database.php');
class Account extends DatabaseObject {
public static function calc_salary($teacher_id) {
global $database;
$sql = "SELECT * from teacher_sub WHERE teacher_id = '".$teacher_id."'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
foreach($result as $key => $row) {
$result[$key]['class_id'] = self::get_classid($row['subject_id']);
}
$salary = 0;
foreach($result as $key => $row) {
$sql = "SELECT salary FROM salary_structure WHERE class_id = '".$row['class_id']."'";
$result = $database->query($sql);
$result = $database->fetch_array($result);
$salary+=$result['salary'];
}
return $salary;
}
public static function get_classid($subject_id) {
global $database;
$sql = "SELECT class_id from subject WHERE id = '".$subject_id."'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
//print_array($result);
return $result[0]['class_id'];
//
}
public static function check_payment($teacher_id) {
global $database;
$sql = "SELECT * FROM teacher_payment WHERE teacher_id = '".$teacher_id."'"." ORDER BY date_paid";
$result = $database->query($sql);
//print_array($result);
$result = $database->fetch_all($result);
return $result;
}
public static function pay_salary($id,$salary) {
global $database;
$salary_c = self::calc_salary($id);
$sql = "INSERT INTO teacher_payment(teacher_id, year, month, date_paid, amount) VALUES ('$id', '$salary[year]', '$salary[month]', '$salary[dop]', '$salary_c')";
if($database->query($sql)) {
return true;
}
else {
return false;
}
}
}
?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"teacher")==0 || strcmp($_SESSION['user_type'],"admin")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
$me = User::find_student_by_id($_SESSION['user_id']);
//print_array($me);
?>
<?php include_layout_template('header_inner.php'); ?>
<script src="../js/student.js"></script>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Student Here</h4>
</p>
<p>
<a href="../change_password.php" class="menuItem">Change Password</a>
<a href="view_attendance.php" class="menuItem">View Attendance details</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<center>
<h2>My Profile</h2></br>
<p><h3>Today is: <?php echo date("Y-m-d") . "<br />"; ?></h3></p>
</center>
<?php
echo "Full Name: ".full_name($me['fname'],$me['lname'],$me['mname'])."<br/>";
echo "Gender: ".upcase($me['gender'])."<br/>";
echo "Date of Birth: ".$me['dob']."<br/>";
echo "Blood Group: ".strtoupper($me['blood_group'])."<br/>";
echo "Nationality: ".upcase($me['nationality'])."<br/>";
echo "Email: ".$me['email']."<br/>";
echo '<a href = "#" id="contact">Contact Details</a>';
echo '<div id="contact_div" style="display:none;">';
echo "Home Phone: ".$me['contact']['home_phone']."<br/>";
echo "<br/>Permanent: <br/>";
echo "Zone: ".$me['contact']['permanent']['zone']."<br/>";
echo "District: ".$me['contact']['permanent']['district']."<br/>";
echo "City: ".$me['contact']['permanent']['city']."<br/>";
echo "Ward No.: ".$me['contact']['permanent']['ward_no']."<br/>";
echo "Tole: ".$me['contact']['permanent']['tole']."<br/>";
echo "House No.: ".$me['contact']['permanent']['house_no']."<br/>";
if(!empty($me['contact']['temporary'])) {
echo "<br/>Temporary: <br/>";
echo "Zone: ".$me['contact']['temporary']['zone']."<br/>";
echo "District: ".$me['contact']['temporary']['district']."<br/>";
echo "City: ".$me['contact']['temporary']['city']."<br/>";
echo "Ward No.: ".$me['contact']['temporary']['ward_no']."<br/>";
echo "Tole: ".$me['contact']['temporary']['tole']."<br/>";
echo "House No.: ".$me['contact']['temporary']['house_no']."<br/>";
}
echo "</div>";
echo '<br/><a href = "#" id="parent">Parent Details</a>';
echo '<div id="parent_div" style="display:none;">';
echo "Name: ".full_name($me['parent']['fname'],$me['parent']['lname'],$me['parent']['mname'])."<br/>";
echo "Gender: ".$me['parent']['gender']."<br/>";
echo "Occupation: ".$me['parent']['occupation']."<br/>";
echo "Mobile Number: ".$me['parent']['mobile']."<br/>";
echo "Relationship: ".$me['parent']['relation']."<br/>";
if(!empty($me['parent']['email']))
echo "Email: ".$me['parent']['email']."<br/>";
echo "</div>";
echo '<br/>';
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep></head>
<body>
<!-- Main site container -->
<div id="siteBox">
<!-- Main site header : holds the img, title and top tabbed menu -->
<div id="header">
<!-- top rounded corner -->
<img src="../images/corner_tl.gif" alt="corner" style="float:left;" />
<!-- Site title and subTitle -->
<span class="title">
<span>School Management System</span>
<span class="subTitle">
SMS
</span>
</span>
<!-- Menu is displayed in reverse order from how you define it (caused by float: right) -->
<a href="../logout.php" title="logout" class="lastMenuItem">Logout</a>
<a href="profile.php" title="profile">Profile</a>
<?php
if(strcmp($_SESSION['user_type'],"admin")== 0){
echo '<a href="account.php" title="routine">Account<span class="desc">Section</span></a>';
echo '<a href="routines.php" title="routine">Routines</a>';
echo '<a href="admin_subject.php" title="subject">Subjects</a>';
echo '<a href="users.php" title="users">Users<span class="desc">Manage Users</span></a>';
}
else if(strcmp($_SESSION['user_type'],"teacher")== 0){
echo '<a href="student_attendance.php" title="std_attendance">Attendance<span class="desc">Student</span></a>';
echo '<a href="subject.php" title="subject">Subjects</a>';
echo '<a href="routines.php" title="routine">Routines</a>';
}
else if(strcmp($_SESSION['user_type'],"student")== 0){
echo '<a href="routines.php" title="routine">Routines</a>';
}
?>
<a href="index.php" title="home" >home<span class="desc">welcome</span></a>
</div><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<script src="../js/student.js"></script>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<?php echo'<a href="assign_subject.php?id='.$_GET['id'].'" class="menuItem">Assign Subject</a>' ?>
<?php echo'<a href="teacher_subject.php?id='.$_GET['id'].'" class="menuItem">View Subject(s)</a>' ?>
<?php echo'<a href="teacher_salary.php?id='.$_GET['id'].'" class="menuItem">View Salary and Payments</a>' ?>
<a href="teacher_search.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(empty($_GET['id'])) {
$session->message("No teacher ID was provided.");
}
else {
$teacher = Admin::find_teacher_by_id($_GET['id']);
//print_array($teacher);
echo "Full Name: ".full_name($teacher['fname'],$teacher['lname'],$teacher['mname'])."<br/>";
$class_id = Teacher::check_classteacher($_GET['id']);
if($class_id) {
echo "Class Teacher of Class: ".upcase(Routine::get_class($class_id))."<br/>";
}
echo "Gender: ".upcase($teacher['gender'])."<br/>";
//echo "Date of Birth: ".$teacher['dob']."<br/>";
// echo "Blood Group: ".strtoupper($teacher['blood_group'])."<br/>";
// echo "Nationality: ".upcase($teacher['nationality'])."<br/>";
// echo "Email: ".$teacher['email']."<br/>";
// echo "Admission Date: ".$teacher['admission_date']."<br/>";
// echo "Previous School: ".$teacher['previous_school']."<br/>";
echo '<a href = "#" id="contact">Contact Details</a>';
echo '<div id="contact_div" style="display:none;">';
echo "Home Phone: ".$teacher['contact']['home_phone']."<br/>";
echo "<br/>Permanent: <br/>";
echo "Zone: ".$teacher['contact']['permanent']['zone']."<br/>";
echo "District: ".$teacher['contact']['permanent']['district']."<br/>";
echo "City: ".$teacher['contact']['permanent']['city']."<br/>";
echo "Ward No.: ".$teacher['contact']['permanent']['ward_no']."<br/>";
echo "Tole: ".$teacher['contact']['permanent']['tole']."<br/>";
echo "House No.: ".$teacher['contact']['permanent']['house_no']."<br/>";
if(!empty($teacher['contact']['temporary'])) {
echo "<br/>Temporary: <br/>";
echo "Zone: ".$teacher['contact']['temporary']['zone']."<br/>";
echo "District: ".$teacher['contact']['temporary']['district']."<br/>";
echo "City: ".$teacher['contact']['temporary']['city']."<br/>";
echo "Ward No.: ".$teacher['contact']['temporary']['ward_no']."<br/>";
echo "Tole: ".$teacher['contact']['temporary']['tole']."<br/>";
echo "House No.: ".$teacher['contact']['temporary']['house_no']."<br/>";
}
echo "</div>";
echo "<br/>";
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header.php'); ?>
<?php include_layout_template('menu.php'); ?>
<?php include_layout_template('content_start.php'); ?>
<?php include_layout_template('content_left_start.php'); ?>
<p>
<h4>Your Options:</h4>
</p>
<p>
<a href="#" class="menuItem">Change Password</a>
<a href="#" class="menuItem">................</a>
</p>
<?php include_layout_template('content_left_end.php'); ?>
<?php include_layout_template('content_right_start.php'); ?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Chuchaa manche lae hello".'</br>';
}
else {
?>
<form method="POST" action="">
<fieldset>
<legend>Change Password</legend>
<label>Old password:</label>
<input type = "<PASSWORD>" name="<PASSWORD>" required ="true"/></br>
<label>New password:</label>
<input type = "<PASSWORD>" name="<PASSWORD>password" required ="true"/></br></br>
<input type="submit" name="submit" value="Change Password" />
</fieldset>
</form>
<?php } ?>
<?php include_layout_template('content_end.php'); ?>
<?php include_layout_template('footer.php'); ?>
<file_sep><?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Admin extends DatabaseObject {
public static $contact_id;
// Common Database Methods
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function register_address($user_address) {
global $database;
$sql = "INSERT INTO address(zone, district, city, ward_no,tole, house_no) VALUES ('$user_address[p_zone]','$user_address[p_district]','$user_address[p_city]','$user_address[p_wardno]', '$user_address[p_tole]', '$user_address[p_houseno]')";
if($database->query($sql)) {
$permanent_id = $database->insert_id();
}
if($user_address['t_zone']!=NULL && $user_address['t_district']!=NULL && $user_address['t_city']!=NULL && $user_address['t_wardno']!=NULL && $user_address['t_tole']!=NULL && $user_address['t_houseno']!=NULL) {
$sql = "INSERT INTO address(zone, district, city, ward_no,tole, house_no) VALUES ('$user_address[t_zone]','$user_address[t_district]','$user_address[t_city]','$user_address[t_wardno]', '$user_address[t_tole]', '$user_address[t_houseno]')";
if($database->query($sql)) {
$temporary_id =$database->insert_id();
}
}
if(isset($temporary_id))
$sql = "INSERT INTO contact(permanent_address_id, temporary_address_id,home_phone) values('$permanent_id','$temporary_id', '$user_address[home_phone]')";
else
$sql = "INSERT INTO contact(permanent_address_id,home_phone) values('$permanent_id','$user_address[home_phone]')";
if($database->query($sql)) {
self::$contact_id = $database->insert_id();
}
}
public static function register_parent($parent_details) {
global $database;
echo self::$contact_id;
$c = self::$contact_id;
$sql = "INSERT INTO parent(fname,mname, lname, gender, occupation,contact_id,email,mobile) values ('$parent_details[p_fname]', '$parent_details[p_mname]', '$parent_details[p_lname]', '$parent_details[p_gender]', '$parent_details[occupation]', '$c', '$parent_details[p_email]', '$parent_details[mobile_no]')";
if($database->query($sql)) {
$parent_id =$database->insert_id();
}
return $parent_id;
}
public static function register_student($personal) {
global $database;
$c = self::$contact_id;
$pid = $database->insert_id();
$sql = "INSERT INTO student(fname, mname, lname, gender, dob, blood_group, nationality, contact_id, parent_id, class_id, admission_date, previous_school, email) values('$personal[fname]', '$personal[mname]', '$personal[lname]', '$personal[gender]', '$personal[dob]', '$personal[blood_group]', '$personal[nationality]', '$c', '$pid', '$personal[class_id]', '$personal[admission_date]', '$personal[previous_school]', '$personal[email]')";
if($database->query($sql)) {
$student_id =$database->insert_id();
}
return $student_id;
}
public static function register_relation($relation, $parent_id, $student_id) {
global $database;
$sql = "INSERT INTO parent_student_relationship(student_id, relation, parent_id) values('$student_id', '$relation', '$parent_id')";
$database->query($sql);
}
public static function register_teacher($teacher) {
global $database;
$c = self::$contact_id;
$sql = "INSERT INTO teacher(fname, mname, lname, gender, dob, qualification, blood_group, nationality, contact_id, email) values ('$teacher[fname]', '$teacher[mname]', '$teacher[lname]', '$teacher[gender]', '$teacher[dob]', '$teacher[qualification]', '$teacher[blood_group]', '$teacher[nationality]', '$c' ,'$teacher[email]')";
$database->query($sql);
}
public static function register_user($user_data) {
print_array($user_data);
global $database;
self::register_address($user_data['address']);
if($user_data['personal']['type']==3) {
$parent_id = self::register_parent($user_data['parent']);
$student_id = self::register_student($user_data['personal']);
self::register_relation($user_data['parent']['relation'],$parent_id,$student_id);
$username = strtolower($user_data['personal']['fname'])."_".$student_id;
$password = md5("abc");
$type = "student";
$sql = "INSERT INTO login(user_id, username, password, user_type) values ('$student_id', '$username', '$password', '$type')";
$database->query($sql);
}
else if($user_data['personal']['type']==2) {
self::register_teacher($user_data['personal']);
$teacher_id = $database->insert_id();
$username = strtolower($user_data['personal']['fname'])."_".$teacher_id;
$password = md5("abc");
$type = "teacher";
$sql = "INSERT INTO login(user_id, username, password, user_type) values ('$teacher_id', '$username', '$password', '$type')";
$database->query($sql);
}
}
public static function add_admin($data) {
global $database;
$sql="INSERT INTO admin(fname, mname, lname, gender, email) VALUES ('$data[fname]','$data[mname]','$data[lname]','$data[gender]','$data[email]') ";
if($database->query($sql)) {
$id =$database->insert_id();
$password = md5("abc");
$type = "admin";
}
$username = "admin_".$id;
$sql="INSERT INTO login(user_id, username, password, user_type) VALUES ('$id','$username','$password','$type')";
if($database->query($sql))
return true;
else
return false;
}
public static function find_all_teacher() {
global $database;
$sql = "SELECT id, fname, mname, lname FROM teacher order by fname";
$result_set = $database->query($sql);
$all = $database->fetch_all($result_set);
return $all;
}
public static function find_all_student() {
global $database;
$sql = "SELECT id, fname, mname, lname FROM student order by fname";
$result_set = $database->query($sql);
$all = $database->fetch_all($result_set);
return $all;
}
public static function find_teacher_by_id($id) {
global $database;
$sql = "SELECT * from teacher WHERE id = '".$id."'";
$result = $database->query($sql);
$result = $database->fetch_array($result);
$result['contact'] = User::get_contact($result['contact_id']);
return $result;
}
public static function find_student_by_id($id) {
global $database;
$sql = "SELECT * from student WHERE id = '".$id."'";
$result = $database->query($sql);
$result = $database->fetch_array($result);
$result['contact'] = User::get_contact($result['contact_id']);
return $result;
}
public static function search_student($search) {
global $database;
$field = $search['search_type'];
$sql = "SELECT * FROM student WHERE ".$field." like '".$search['keyword']."%'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;
}
public static function search_teacher($search) {
global $database;
$field = $search['search_type'];
$sql = "SELECT * FROM teacher WHERE ".$field." like '".$search['keyword']."%'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;
}
public static function view_students($classes) {
global $database;
$sql = "SELECT * FROM student WHERE class_id='".$classes."'";
$result = $database->query($sql);
$user_data = array();
while($row =$database->fetch_array($result))
{
array_push($user_data,$row);
}
return $user_data;
}
public static function assign_classteacher($data) {
global $database;
$sql="SELECT * FROM class WHERE teacher_id='".$data['teacher_id']."'";
$result=$database->query($sql);
if($database->num_rows($result)==0) {
$sql="UPDATE class SET teacher_id='".$data['teacher_id']."' where id ='".$data['class_id']."'";
if($database->query($sql))
return true;
else
return false;
}
else return false;
}
public static function get_classteacher($class_id) {
global $database;
$sql = "SELECT teacher.fname, teacher.lname, teacher.mname from teacher inner join class on teacher.id=class.teacher_id where class.id='".$class_id."'";
$result=$database->query($sql);
$result=$database->fetch_array($result);
if(!empty($result))
return full_name($result['fname'],$result['lname'],$result['mname']);
else
return "----";
}
public static function remove_classteacher($class_id) {
global $database;
$teacher=NULL;
$sql="UPDATE class SET teacher_id='$teacher' where id ='$class_id'";
if($database->query($sql))
return true;
else
return false;
}
}
?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Attendance here!!</h4>
</p>
<p>
<a href="profile.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
$attendance = Student::view_attendance($_SESSION['user_id']);
if(!empty($attendance)) {
?>
<table class="bordered">
<caption>Attendance Details</caption>
<tr>
<th>Date</th>
<th>Status</th>
</tr>
<?php foreach($attendance as $a) { ?>
<tr>
<td><?php echo $a['date']; ?></td>
<td><?php echo $a['status']; ?></td>
</tr>
<?php } ?>
</table>
<?php
}
else {
echo "No records!!<br/>";
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"student")==0 || strcmp($_SESSION['user_type'],"admin")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
$class_all = Teacher::get_myclass($_SESSION['user_id']);
//this is for removing the repeated class..
foreach($class_all as $element) {
$temp = $element['class_id'];
$class[$temp] = $element;
}
foreach($class as $key => $c) {
$class[$key]['routine'] = Routine::find_by_id($c['class_id']);
}
?>
<?php //print_array($class); ?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Teacher's Section</h4>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php if(!empty($class)){ ?>
<table class="bordered">
<tr>
<th>Preview</th>
<th>Subject Name</th>
<th>Class</th>
<th>Type</th>
</tr>
<?php
foreach($class as $key => $routine) {
?>
<tr>
<td><img class = "routine" src="../<?php echo $routine['routine']->image_path(); ?>" width="100" /></td>
<td><?php echo upcase($routine['sname']); ?> </td>
<td><?php echo $routine['routine']->class; ?></td>
<td><?php echo upcase($routine['routine']->image_type); ?></td>
</tr>
<?php
}
?>
</table>
<?php }else{
echo output_message("There are no routines for you.");
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"student")==0 || strcmp($_SESSION['user_type'],"teacher")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Your Options:</h4>
</p>
<p>
<a href="../change_password.php" class="menuItem">Change Password</a>
<a href="#" class="menuItem">................</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php echo output_message($message); ?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<script src="../js/student.js"></script>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="student_search.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(empty($_GET['id'])) {
$session->message("No student ID was provided.");
}
else {
$student = Admin::find_student_by_id($_GET['id']);
$parent = User::get_parent($student['id'],$student['parent_id']);
?>
<?php
echo "Full Name: ".full_name($student['fname'],$student['lname'],$student['mname'])."<br/>";
echo "Class: ".upcase(Routine::get_class($student['class_id']))."<br/>";
echo "Gender: ".upcase($student['gender'])."<br/>";
echo "Date of Birth: ".$student['dob']."<br/>";
echo "Blood Group: ".strtoupper($student['blood_group'])."<br/>";
echo "Nationality: ".upcase($student['nationality'])."<br/>";
echo "Email: ".$student['email']."<br/>";
echo "Admission Date: ".$student['admission_date']."<br/>";
echo "Previous School: ".$student['previous_school']."<br/>";
echo '<a href = "#" id="contact">Contact Details</a>';
echo '<div id="contact_div" style="display:none;">';
echo "Home Phone: ".$student['contact']['home_phone']."<br/>";
echo "<br/>Permanent: <br/>";
echo "Zone: ".$student['contact']['permanent']['zone']."<br/>";
echo "District: ".$student['contact']['permanent']['district']."<br/>";
echo "City: ".$student['contact']['permanent']['city']."<br/>";
echo "Ward No.: ".$student['contact']['permanent']['ward_no']."<br/>";
echo "Tole: ".$student['contact']['permanent']['tole']."<br/>";
echo "House No.: ".$student['contact']['permanent']['house_no']."<br/>";
if(!empty($student['contact']['temporary'])) {
echo "<br/>Temporary: <br/>";
echo "Zone: ".$student['contact']['temporary']['zone']."<br/>";
echo "District: ".$student['contact']['temporary']['district']."<br/>";
echo "City: ".$student['contact']['temporary']['city']."<br/>";
echo "Ward No.: ".$student['contact']['temporary']['ward_no']."<br/>";
echo "Tole: ".$student['contact']['temporary']['tole']."<br/>";
echo "House No.: ".$student['contact']['temporary']['house_no']."<br/>";
}
echo "</div>";
//parent ko details
echo '<br/><a href = "#" id="parent">Parent Details</a>';
echo '<div id="parent_div" style="display:none;">';
echo "Name: ".full_name($parent['fname'],$parent['lname'],$parent['mname'])."<br/>";
echo "Gender: ".$parent['gender']."<br/>";
echo "Occupation: ".$parent['occupation']."<br/>";
echo "Mobile Number: ".$parent['mobile']."<br/>";
echo "Relationship: ".$parent['relation']."<br/>";
if(!empty($parent['email']))
echo "Email: ".$parent['email']."<br/>";
echo "</div>";
echo '<br/>';
?>
<?php
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once("../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("../login.php"); } ?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Space for a left side link menu if needed:
</p>
<p>
<a href="#" class="menuItem">Update</a>
<a href="#" class="menuItem">Fee Section</a>
<a href="pay_salary.php" class="menuItem">Salary Section</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>Account Section here!!</h2>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="#" class="menuItem">Add Student</a>
<a href="#" class="menuItem">Add Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<form method="POST" action="add_address.php" id="add_student" name="add">
<fieldset>
<legend>Student: Personal Information</legend>
<label>First Name:</label>
<input type="text" name="fname" required="true" size = 30/><br/><br/>
<label>Middle Name:</label>
<input type="text" name="mname" size = 30/><br/><br/>
<label>Last Name:</label>
<input type="text" name="lname" required="true" size = 30/><br/><br/>
<label>Gender</label><br/>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br/><br/>
<label>Class:<label/>
<SELECT NAME="class_id">
<OPTION VALUE=0>Choose
<?php // echo $options;?>
<?php echo Routine::get_all_class() ;?>
</SELECT> </br><br/>
<label>Date Of Birth: </label>
<input type="text" name = "dob" id="datepicker" required="true"/><br/><br/>
<!-- <label>Year:</label><input type="text" name="year" required="true" size = 5/>
<label>Month:</label><input type="text" name="month" required="true" size = 5/>
<label>Date:</label><input type="text" name="date" required="true" size = 5/><br/> -->
<label>Blood Group:</label><input type="text" name="blood_group" required="true" size = 5/><br/>
<label>Nationality: </label>
<input type="text" name="nationality" required="true"/><br/>
<label>Email: </label>
<input type="text" name="email" size = 30/><br/>
<br />
<input type="hidden" name="flag" value="login"/>
<input type="hidden" name="type" value="3"/><br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"student")==0 || strcmp($_SESSION['user_type'],"admin")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
$teacher = Admin::find_teacher_by_id($_SESSION['user_id']);
?>
<?php include_layout_template('header_inner.php'); ?>
<script src="../js/student.js"></script>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Teacher Here</h4>
</p>
<p>
<a href="../change_password.php" class="menuItem">Change Password</a>
<a href="view_salary.php" class="menuItem">View Salary</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
echo "<b>Full Name: </b>".full_name($teacher['fname'],$teacher['lname'],$teacher['mname'])."<br/>";
$class_id = Teacher::check_classteacher($_SESSION['user_id']);
if($class_id) {
echo "Class Teacher of Class: ".strtoupper(Routine::get_class($class_id))."<br/>";
}
echo "Gender: ".upcase($teacher['gender'])."<br/>";
echo '<a href = "#" id="contact">Contact Details</a>';
echo '<div id="contact_div" style="display:none;">';
echo "Home Phone: ".$teacher['contact']['home_phone']."<br/>";
echo "<br/>Permanent: <br/>";
echo "Zone: ".$teacher['contact']['permanent']['zone']."<br/>";
echo "District: ".$teacher['contact']['permanent']['district']."<br/>";
echo "City: ".$teacher['contact']['permanent']['city']."<br/>";
echo "Ward No.: ".$teacher['contact']['permanent']['ward_no']."<br/>";
echo "Tole: ".$teacher['contact']['permanent']['tole']."<br/>";
echo "House No.: ".$teacher['contact']['permanent']['house_no']."<br/>";
if(!empty($teacher['contact']['temporary'])) {
echo "<br/>Temporary: <br/>";
echo "Zone: ".$teacher['contact']['temporary']['zone']."<br/>";
echo "District: ".$teacher['contact']['temporary']['district']."<br/>";
echo "City: ".$teacher['contact']['temporary']['city']."<br/>";
echo "Ward No.: ".$teacher['contact']['temporary']['ward_no']."<br/>";
echo "Tole: ".$teacher['contact']['temporary']['tole']."<br/>";
echo "House No.: ".$teacher['contact']['temporary']['house_no']."<br/>";
}
echo "</div>";
echo "<br/>";
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php
require_once('../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("../login.php"); }
?>
<?php
$max_file_size = 1048576; // expressed in bytes
// 10240 = 10 KB
// 102400 = 100 KB
// 1048576 = 1 MB
// 10485760 = 10 MB
if(isset($_POST['submit'])) {
$routine = new Routine();
$routine->image_type = $_POST['image_type'];
$routine->class_id = $_POST['class_id'];
$routine->attach_file($_FILES['file_upload']);
if($routine->save()) {
// Success
$session->message("Routine uploaded successfully.");
redirect_to('routines.php');
} else {
// Failure
$message = join("<br />", $routine->errors);
}
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<a href="routines.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>Photo Upload</h2>
<?php echo output_message($message); ?>
<form action="upload_routine.php" enctype="multipart/form-data" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
<p><input type="file" name="file_upload" /></p>
<label>Class:</label>
<SELECT NAME="class_id">
<OPTION VALUE=0>Choose
<?php echo Routine::get_all_class() ;?>
</SELECT></br><br/>
<label>Type:</label>
<SELECT NAME="image_type">
<OPTION VALUE=0>Choose
<OPTION VALUE="class">Class
<OPTION VALUE="exam">Exam
</SELECT><br/><br/>
<input type="submit" name="submit" value="Upload" />
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-AU">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<meta name="author" content="067bct" />
<meta name="keywords" content="School management system" />
<meta name="description" content="School Management System by 067BCT" />
<title>School Management System</title>
<link rel="stylesheet" type="text/css" href="../css/style.css" media="screen, tv, projection" />
<script src="../js/jquery.js"></script>
<script src="../js/viewroutine.js"></script>
<script src="../js/activeTab.js"></script>
<?php //<script src="../js/jquery-1.9.1.js"></script>?>
<script src="../js/jquery.ui.core.js"></script>
<script src="../js/jquery.ui.widget.js"></script>
<script src="../js/jquery.ui.datepicker.js"></script>
<link rel="stylesheet" href="../css/datepicker.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
});
</script><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
else if(strcmp($_SESSION['user_type'],"student")==0 || strcmp($_SESSION['user_type'],"admin")==0 ){
redirect_to("../".$_SESSION['user_type']."/index.php");
}
$class = Teacher::get_myclass($_SESSION['user_id']);
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Teacher's Section</h4>
<?php
foreach($class as $cls) {
echo '<a href="student_marks.php?id='.$cls['class_id'].'&subject_id='.$cls['subject_id'].'" class= "menuItem">'.$cls['sname'].'('.$cls['name'].')'.'</a>';
}
?>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<p><h3>In this section you can add marks..</h3></p>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php
if(!empty($_GET['del'])) {
Subject::del_teacher_sub($_GET['tsid']);
redirect_to("teacher_subject.php?id=".$_GET['id']);
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
</p>
<p>
<?php echo'<a href="teacher_details.php?id='.$_GET['id'].'" class="menuItem">Back</a>' ?>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(empty($_GET['id'])) {
$session->message("No teacher ID was provided.");
}
else {
$subjects = Subject::get_all_teacher_subject($_GET['id']);
if($subjects['total_subject']==0) {
echo "<p>No subjects assigned!!</p><br/>";
}
else {
echo "Total No. of subjects: ".$subjects['total_subject'];
?>
<table class="bordered">
<tr>
<th>Subject</th>
<th>Class</th>
<th>Remarks</th>
<th>Action</th>
</tr>
<?php foreach($subjects as $subject): ?>
<?php if(isset($subject['id'])) {?>
<tr>
<td><?php echo $subject['name']; ?></td>
<td><?php echo Routine::get_class($subject['class_id']); ?></td>
<td><?php echo $subject['remarks']; ?></td>
<td><a href="teacher_subject.php?del=1&tsid=<?php echo $subject['id']; ?>&id=<?php echo $_GET['id']; ?>">Delete</a></td>
</tr>
<?php } ?>
<?php endforeach; ?>
</table>
<?php
}
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php
$classes = array('Nursery','LKG','UKG','1','2','3','4','5','6','7','8','9','10');
$class_id = 1;
foreach($classes as $v)
{
echo '<a href="#" class="anchor" id="'.$class_id.'">Class '.$v.'</a></br>';
$class_id = $class_id + 1;
}
?>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click",".anchor", function(){
var id = $(this).attr("id");
$("#contentRight").load("show_students.php?classes="+id);
});
});
</script> <file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Add another Admin!
</p>
<p>
<a href="users.php" class="menuItem">BACK</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
if(Admin::add_admin($_POST))
echo output_message("Added Sucessfully!!");
else
echo output_message("Error: Couldn't Added!!");
}
else {
?>
<form method="POST" action="" name="add">
<fieldset>
<legend>Add Admin</legend>
<label>First Name:</label>
<input type="text" name="fname" required="true" size = 30/><br/><br/>
<label>Middle Name:</label>
<input type="text" name="mname" size = 30/><br/><br/>
<label>Last Name:</label>
<input type="text" name="lname" required="true" size = 30/><br/><br/>
<label>Gender</label><br/>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br/><br/>
<label>Email: </label>
<input type="text" name="email" size = 30/><br/>
<br />
<input type="hidden" name="flag" value="login"/>
<input type="hidden" name="type" value="1"/><br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php } ?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep>$(document).ready(function(){
$('#header a').click(function(){
//alert("alert.");
//$('#header a').removeClass('active');
$(this).addClass('active');
});
});
<file_sep><?php require_once("../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("../login.php"); } ?>
<?php
// must have an ID
if(empty($_GET['id'])) {
$session->message("No Subject was provided.");
redirect_to('subject.php');
}
?>
<?php
Subject::delete_subject($_GET['id']);
redirect_to("view_subject.php");
?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Space for a left side link menu if needed:
</p>
<p>
<a href="upload_routine.php" class="menuItem">Upload a new routine</a>
<a href="assign_class_teacher.php" class="menuItem">Assign Class Teacher</a>
<a href="remove_class_teacher.php" class="menuItem">Remove Class Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(Admin::remove_classteacher($_POST['class_id']))
echo output_message("Removed!");
else
echo output_message("Error: Couldn't remove!!");
}
?>
<form method="POST" action="" id="add_student" name="add">
<fieldset>
<legend>Remove Class Teacher</legend>
<label> From Class:<label/>
<SELECT NAME="class_id">
<OPTION VALUE=0>Choose
<?php echo Routine::get_all_class(); ?>
</SELECT> </br><br/>
<input type="submit" name="add_btn" value="Remove"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
</p>
<p><h3>Search students!!</h3></p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(isset($_POST['submit'])) {
$result = Admin::search_student($_POST);
foreach($result as $r)
{
echo '<a href = "student_details.php?id= '.$r['id'].'">'.full_name($r['fname'],$r['lname'],$r['mname']).'</a>'.'</br>';
}
}
else {
?>
<form method = "POST" action = "">
<fieldset>
<legend>Search</legend>
<label>Search By:</label>
<SELECT NAME="search_type">
<OPTION VALUE=0>Search:
<OPTION VALUE="fname">By Name
<OPTION VALUE="id">By Id
</SELECT><br/><br/>
<label>KeyWord:</label>
<input type="text" name="keyword" required="true" size=15/></br>
<input type="submit" name="submit" value="Search"/><br/><br/>
</fieldset>
</form>
<?php } ?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once("../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("../login.php"); } ?>
<?php
// Find all the routines
$routines = Routine::find_all();
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<a href="upload_routine.php" class="menuItem">Upload a new routine</a>
<a href="assign_class_teacher.php" class="menuItem">Assign Class Teacher</a>
<a href="remove_class_teacher.php" class="menuItem">Remove Class Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>All Routines</h2>
<?php echo output_message($message); ?>
<?php
if(Routine::count_all() != 0 ){
?>
<table class="bordered">
<tr>
<th>Preview</th>
<th>Class</th>
<th>Class-teacher</th>
<th>Type</th>
<th>Action</th>
</tr>
<?php foreach($routines as $routine) { ?>
<tr>
<td><img class = "routine" src="../<?php echo $routine->image_path(); ?>" width="100" /></td>
<td><?php echo $routine->class; ?></td>
<td><center><?php echo Admin::get_classteacher($routine->class_id); ?></center></td>
<td><?php echo upcase($routine->image_type); ?></td>
<td><a href="delete_routine.php?id=<?php echo $routine->id; ?>">Delete</a></td>
</tr>
<?php } ?>
</table>
<?php
}else{
echo output_message("There are no routines uploaded.");
}
?>
<br />
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
$classes=$_GET['classes'];
$view=Admin::view_students($classes);
if(empty($view)){echo "There are no students";}
else {echo "There are ".count($view)." students.<br><br>"; }
foreach($view as $show)
{
echo '<ul>';
echo '<li><a href="student_details.php?id='.$show['id'].'" class = "anchor" id="'.$show['id'].'">'.$show['fname'].' '.$show['lname'].'</a></br>';
echo '</ul>';
}
?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<a href="subject.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(empty($_GET['id']) || empty($_GET['subject_id'])) {
redirect_to("subject.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(Subject::assign_marks($_GET['id'],$_POST))
echo "Assigned!!".'</br>';
}
else {
?>
<form method="POST" action="" >
<fieldset>
<legend>Assign Marks</legend>
<label>Marks Obtained:<label/>
<input type="text" name="mo" required ="true" size=10/></br>
<label>Terminal<label/>
<input type="text" name="terminal" required ="true" size=20/></br>
<label>Date<label/>
<input type="text" name="date" required ="true" size=20/></br>
<label>Remarks<label/>
<input type="text" name="remarks" required ="true" size=20/></br>
<input type="hidden" name="subject_id" value="<?php echo $_GET['subject_id']; ?>">
<input type="submit" name="add_btn" value="Assign"/><br/><br/>
</fieldset>
</form>
<?php } ?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Subjects:
</p>
<p>
<a href="add_subject.php" class="menuItem">Add Subject</a>
<a href="view_subject.php" class="menuItem">View Subjects</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>In this section, we can manage subjects. We can add subjects, view subjects...</h2>
<?php
if(isset($_POST['submit'])) {
if(Subject::add_subject($_POST)) {
echo '<p>Subject added!!</p><br/>';
}
else {
echo '<p>Error in Adding!!</p><br/>';
}
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header.php'); ?>
<?php include_layout_template('menu.php'); ?>
<?php include_layout_template('content_start.php'); ?>
<?php include_layout_template('content_left_start.php'); ?>
<?php include_layout_template('content_left_end.php'); ?>
<?php include_layout_template('content_right_start.php'); ?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(User::change_password($_POST))
$session->message("passsword changed successfully.");
else
$session->message("passsword couldnot be changed!");
redirect_to($_SESSION['user_type']."/profile.php");
}
else {
?>
<form method="POST" action="">
<fieldset>
<legend>Change Password</legend>
<label>Old password:</label>
<input type = "<PASSWORD>" name="old_password" required ="true"/></br>
<label>New password:</label>
<input type = "<PASSWORD>" name="new_password" required ="true"/></br></br>
<input type="submit" name="submit" value="Change Password" />
</fieldset>
</form>
<?php } ?>
<?php include_layout_template('content_end.php'); ?>
<?php include_layout_template('footer.php'); ?>
<file_sep><?php
require_once(LIB_PATH.DS.'database.php');
class Subject extends DatabaseObject {
public static function get_all_class() {
global $database;
$sql = "SELECT id, name FROM class ORDER BY id";
$result_set = $database->query($sql);
$options="";
while($row = $database->fetch_array($result_set)){
$id=$row["id"];
$name=$row["name"];
$options.="<option value=\"$id\">".$name;
}
//print_array($options);
return $options;
}
public static function add_subject($subject_data) {
global $database;
if (self::subject_exits($subject_data['name'], $subject_data['class_id'], $subject_data['remark'])) {
return false;
}
else {
$sql = "INSERT INTO subject(name, class_id, fm, pm, remarks) VALUES ('$subject_data[name]','$subject_data[class_id]','$subject_data[fm]','$subject_data[pm]','$subject_data[remark]')";
if($database->query($sql))
return true;
else
return false;
}
}
public static function subject_exits($name, $c_id, $remark) {
global $database;
$sql= "SELECT id FROM subject WHERE class_id = ".$c_id." && name = '".$name."'"." && remarks = '".$remark."'";
$result = $database->query($sql);
return ($database->num_rows($result) == 1) ? true : false;
}
public static function get_all_subject() {
global $database;
$sql = "SELECT * FROM subject ORDER BY class_id";
$result = $database->query($sql);
$total_subject = $database->num_rows($result);
$result = $database->fetch_all($result);
$result['total_subject'] = $total_subject;
return $result;
}
public static function get_subject_by_id($id) {
global $database;
$sql = "SELECT * FROM subject WHERE class_id='".$id."'";
$result = $database->query($sql);
// $total_subject = $database->num_rows($result);
$result = $database->fetch_array($result);
//$result['total_subject'] = $total_subject;
return $result;
}
public static function get_all_subject_option() {
global $database;
$sql = "SELECT subject.id, subject.name,subject.remarks,class.name AS class_name FROM subject LEFT JOIN class ON subject.class_id = class.id ORDER BY class.id";
$result_set = $database->query($sql);
$options="";
while($row = $database->fetch_array($result_set)){
$id=$row["id"];
$name=$row["name"];
$class=$row["class_name"];
$remarks = $row["remarks"];
$options.="<option value=\"$id\">".$name." - ".$class." (".$remarks.")";
}
return $options;
}
public static function assign_subject($value) {
global $database;
$sql = "SELECT * FROM teacher_sub WHERE subject_id='".$value['subject_id']."'";
if(!$database->num_rows($database->query($sql))) {
$sql = "SELECT * from teacher_sub WHERE subject_id ='".$value['subject_id']."' && teacher_id='".$value['teacher_id']."'";
if(!$database->num_rows($database->query($sql))) {
$sql = "INSERT INTO teacher_sub(subject_id,teacher_id) VALUES ('$value[subject_id]', '$value[teacher_id]')";
$database->query($sql);
}
}
}
public static function delete_subject($id) {
//subject delete garda subject table bahek aru jata pani chan sab delete garnu parcha..
global $database;
$sql = "DELETE FROM subject WHERE id='".$id."' LIMIT 1";
$database->query($sql);
$sql = "DELETE FROM teacher_sub WHERE subject_id='".$id."' LIMIT 1";
$database->query($sql);
}
public static function get_all_teacher_subject($teacher_id) {
global $database;
$sql = "SELECT teacher_sub.id, subject.name, subject.class_id, subject.remarks FROM teacher_sub LEFT JOIN subject ON teacher_sub.subject_id = subject.id WHERE teacher_id ='".$teacher_id."'";
$result = $database->query($sql);
$total_subject = $database->num_rows($result);
$result = $database->fetch_all($result);
$result['total_subject'] = $total_subject;
return $result;
}
public static function del_teacher_sub($id) {
global $database;
$sql = "DELETE FROM teacher_sub WHERE id='".$id."' LIMIT 1";
$database->query($sql);
}
public static function assign_marks($id,$data) {
global $database;
$sql="INSERT INTO terminal(name,date) VALUES ('$data[terminal]','$data[date]')";
if($database->query($sql))
$result = $database->insert_id();
$sql="SELECT class_id FROM student WHERE id='".$id."'";
$class = $database->query($sql);
$class = $database->fetch_array($class);
$sql = "INSERT INTO student_marks(subject_id, student_id, class_id, marks_obtained, terminal_id,remarks) VALUES ('$data[subject_id]','$id','$class[class_id]','$data[mo]','$result','$data[remarks]')";
if($database->query($sql))
return true;
}
}
?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
foreach($_POST as $key=>$value){
$_SESSION['form_data']['personal'][$key]=$value;
}
?>
<?php
if($_POST["type"]==3)
{
$action = "add_parent.php";
}
else if ($_POST["type"]==2)
{
$action = "register_users.php";
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="#" class="menuItem">Add Student</a>
<a href="#" class="menuItem">Add Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<form method="POST" action=<?php echo $action; ?> id="add_address" name="add">
<fieldset>
<legend>Address</legend>
<label>Permanent: *</label><br/>
<label>Zone: </label>
<input type="text" name="p_zone" required="true"/><br/>
<label>District: </label>
<input type="text" name="p_district" required="true"/><br/>
<label>City: </label>
<input type="text" name="p_city" required="true"/><br/>
<label>Ward No.: </label>
<input type="text" name="p_wardno" required="true" size = 5/><br/>
<label>Tole: </label>
<input type="text" name="p_tole" required="true"/><br/>
<label>House No.: </label>
<input type="text" name="p_houseno" required="true"/><br/>
<label>Home Phone No.: </label>
<input type="text" name="home_phone"/><br/>
<label>Temporary: </label><br/>
<label>Zone: </label>
<input type="text" name="t_zone" /><br/>
<label>District: </label>
<input type="text" name="t_district"/><br/>
<label>City: </label>
<input type="text" name="t_city" /><br/>
<label>Ward No.: </label>
<input type="text" name="t_wardno" size = 5/><br/>
<label>Tole: </label>
<input type="text" name="t_tole"/><br/>
<label>House No.: </label>
<input type="text" name="t_houseno"/><br/>
<br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php
require_once("../includes/initialize.php");
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
if($_SESSION['form_data']['personal']['type']==3) {
foreach($_POST as $key=>$value){
$_SESSION['form_data']['personal'][$key]=$value;
}
}
else if($_SESSION['form_data']['personal']['type']==2) {
foreach($_POST as $key=>$value){
$_SESSION['form_data']['address'][$key]=$value;
}
}
?>
<?php
Admin::register_user($_SESSION['form_data']);
unset($_SESSION['form_data']);
redirect_to("users.php");
?><file_sep><?php
// If it's going to need the database, then it's
// probably smart to require it before we start.
require_once(LIB_PATH.DS.'database.php');
class Teacher extends DatabaseObject {
public static function get_myclass($id) {
global $database;
$sql = "SELECT subject_id FROM teacher_sub WHERE teacher_id = '".$id."'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
foreach($result as $key => $row) {
$result[$key]['class_id'] = Account::get_classid($row['subject_id']);
$result[$key]['sname'] = self::get_subject($row['subject_id']);
}
foreach($result as $key => $row) {
$result[$key]['name'] = Routine::get_class($row['class_id']);
}
return $result;
}
public static function get_subject($id) {
global $database;
$sql = "SELECT name FROM subject WHERE id = '".$id."'";
$result = $database->query($sql);
$result = $database->fetch_array($result);
return $result['name'];
}
public static function get_all_teacher_option() {
global $database;
$sql = "SELECT id,fname, lname, mname FROM teacher";
$result_set = $database->query($sql);
$options="";
while($row = $database->fetch_array($result_set)){
$id=$row["id"];
$name= full_name($row["fname"], $row["lname"], $row["mname"]);
$options.="<option value=\"$id\">".$name;
}
return $options;
}
public static function check_classteacher($id) {
global $database;
$sql = "SELECT * FROM class WHERE teacher_id = '".$id."'";
$result=$database->query($sql);
if($database->num_rows($result)==0) {
return false;
}
else
$result = $database->fetch_array($result);
return $result['id'];
}
public static function find_student_by_class($class_id) {
global $database;
$sql = "SELECT id,fname,mname,lname from student WHERE class_id = '".$class_id."'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;
}
public static function student_attendance($attendance) {
global $database;
array_pop($attendance);
$class_id = array_pop($attendance);
date_default_timezone_set("Asia/Kathmandu");
$date = date('Y-m-d');
echo $date."<br>";
$sql="SELECT * FROM student_attendance WHERE class_id='".$class_id."' && date='".$date."'";
$result=$database->query($sql);
if($database->num_rows($result)==0) {
foreach($attendance as $student_id => $atten) {
echo $student_id."=>".$atten."<br>";
$sql = "INSERT INTO student_attendance(student_id,class_id,date,status) values('$student_id','$class_id','$date','$atten')";
$database->query($sql);
}
}
else {
echo "Attendance already taken for today!".'</br>';
}
/*$sql = "SELECT id,fname,mname,lname from student WHERE class_id = '".$class_id."'";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;*/
}
public static function view_attendance($info) {
global $database;
$sql = "SELECT student.id as std_id,student.fname, student.mname, student.lname,student_attendance.status from student_attendance LEFT JOIN student ON student_attendance.student_id = student.id WHERE student_attendance.date ='".$info['date']."' && student_attendance.class_id='".$info['class_id']."' ORDER BY student.id";
$result = $database->query($sql);
$result = $database->fetch_all($result);
return $result;
}
public static function get_all_date_option($class_id) {
global $database;
$sql = "SELECT DISTINCT date from student_attendance WHERE class_id='".$class_id."' ORDER BY date ASC";
$result = $database->query($sql);
$result = $database->fetch_all($result);
//print_array($result);
$options="";
foreach($result as $r) {
$options.="<option value = ".$r['date'].">".$r['date']."</option>";
}
echo $options;
}
}
?><file_sep>-- phpMyAdmin SQL Dump
-- version 3.3.9
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 30, 2013 at 02:16 PM
-- Server version: 5.5.8
-- PHP Version: 5.3.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `school`
--
-- --------------------------------------------------------
--
--
Create `school`
Table structure for table `address`
--
CREATE TABLE IF NOT EXISTS `address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zone` text NOT NULL,
`district` text NOT NULL,
`city` text NOT NULL,
`ward_no` int(11) NOT NULL,
`tole` text NOT NULL,
`house_no` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
--
-- Dumping data for table `address`
--
INSERT INTO `address` (`id`, `zone`, `district`, `city`, `ward_no`, `tole`, `house_no`) VALUES
(1, 'Bagmati', 'lalitpur', 'patan', 7, 'Tyagal', '58'),
(2, 'Bagmati', 'Lalitpur', 'Patan', 6, 'Saugal', '57'),
(3, 'Bagmati', 'Kathmandu', 'Koteshwor', 19, 'Koteswor', '78'),
(4, 'Bagmati', 'Lalitpur', 'Patan', 7, 'Saugal', '68'),
(5, 'Bagmati', 'Lalitpur', 'Patan', 7, 'Tyagal', '45'),
(6, 'Bagmati', 'Kathmandu', 'Kathmandu', 14, 'Kupondole', '34'),
(7, 'Bagmati', 'Kathmandu', 'Ason', 17, 'Ason', '45'),
(8, 'Bagmati', 'Bhaktapur', 'Thimi', 3, 'Thimi', '34'),
(9, 'Bagmati', 'Kathmandu', 'Kathmandu', 17, 'Ason', '34'),
(10, 'Bagmati', 'Kathmandu', 'Kathmandu', 17, 'Nayabazar', '56'),
(11, 'Bagmati', 'Kathmandu', 'kathmandu', 9, 'Ason', '90');
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` text NOT NULL,
`mname` text,
`lname` text NOT NULL,
`gender` varchar(10) NOT NULL,
`status` text,
`email` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`id`, `fname`, `mname`, `lname`, `gender`, `status`, `email`) VALUES
(1, 'Rabindra', NULL, 'Poudel', 'Male', 'Super Active', '<EMAIL>');
-- --------------------------------------------------------
--
-- Table structure for table `assignment`
--
CREATE TABLE IF NOT EXISTS `assignment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subject_id` int(11) NOT NULL,
`teacher_id` int(11) NOT NULL,
`assigned_date` date NOT NULL,
`deadline` date NOT NULL,
`question` text,
`file` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `assignment`
--
-- --------------------------------------------------------
--
-- Table structure for table `assignment_submission`
--
CREATE TABLE IF NOT EXISTS `assignment_submission` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`assignment_id` int(11) NOT NULL,
`submission_date` date NOT NULL,
`status` varchar(20) NOT NULL,
`file` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `assignment_submission`
--
-- --------------------------------------------------------
--
-- Table structure for table `class`
--
CREATE TABLE IF NOT EXISTS `class` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL,
`teacher_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `class`
--
INSERT INTO `class` (`id`, `name`, `teacher_id`) VALUES
(1, 'Nursery', 0),
(2, 'LKG', NULL),
(3, 'UKG', 0),
(4, 'One', NULL),
(5, 'Two', NULL),
(6, 'Three', 1),
(7, 'Four', NULL),
(8, 'Five', NULL),
(9, 'Six', NULL),
(10, 'Seven', NULL),
(11, 'Eight', 0),
(12, 'Nine', NULL),
(13, 'Ten', 4);
-- --------------------------------------------------------
--
-- Table structure for table `contact`
--
CREATE TABLE IF NOT EXISTS `contact` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`permanent_address_id` int(11) NOT NULL,
`temporary_address_id` int(11) DEFAULT NULL,
`home_phone` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;
--
-- Dumping data for table `contact`
--
INSERT INTO `contact` (`id`, `permanent_address_id`, `temporary_address_id`, `home_phone`) VALUES
(1, 1, NULL, 'o'),
(2, 2, NULL, ''),
(3, 3, 4, '4357556'),
(4, 5, NULL, '7980'),
(5, 6, NULL, 'op'),
(6, 7, NULL, 'op'),
(7, 8, NULL, '2345934'),
(8, 9, 10, 'jkl'),
(9, 11, 12, 'jlk'),
(10, 13, NULL, '4362755'),
(11, 14, NULL, '20943'),
(12, 1, NULL, '01-4355422'),
(13, 2, NULL, '01-443932'),
(14, 3, NULL, '01-4566366'),
(15, 4, NULL, '01-445676'),
(16, 5, NULL, '01-465787'),
(17, 6, NULL, ''),
(18, 7, NULL, '01-4656939'),
(19, 8, NULL, '01-4958694'),
(20, 9, NULL, '01-456738'),
(21, 10, NULL, '01-456789'),
(22, 11, NULL, '');
-- --------------------------------------------------------
--
-- Table structure for table `fee_structure`
--
CREATE TABLE IF NOT EXISTS `fee_structure` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`class` varchar(10) NOT NULL,
`monthly_fee` int(11) NOT NULL,
`stationary` int(11) NOT NULL,
`computer` int(11) DEFAULT NULL,
`exam_fee` int(11) NOT NULL,
`admission_fee` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `fee_structure`
--
INSERT INTO `fee_structure` (`id`, `class`, `monthly_fee`, `stationary`, `computer`, `exam_fee`, `admission_fee`) VALUES
(1, '10', 2000, 500, 250, 400, 7000);
-- --------------------------------------------------------
--
-- Table structure for table `login`
--
CREATE TABLE IF NOT EXISTS `login` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`username` text NOT NULL,
`password` text NOT NULL,
`user_type` text NOT NULL,
`last_login` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
--
-- Dumping data for table `login`
--
INSERT INTO `login` (`id`, `user_id`, `username`, `password`, `user_type`, `last_login`) VALUES
(23, 3, 'pravesh_3', '<PASSWORD>', 'teacher', NULL),
(22, 2, 'aastha_2', '<PASSWORD>', 'teacher', NULL),
(4, 1, 'admin', '<PASSWORD>', 'admin', NULL),
(5, 3, 'student', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(21, 1, 'asmita_1', '900150983cd24fb0d6963f7d28e17f72', 'teacher', NULL),
(20, 5, 'abhay_5', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(19, 4, 'seema_4', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(18, 3, 'subindra_3', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(17, 2, 'raj_2', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(16, 1, 'ankit_1', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL),
(24, 4, 'akash_4', '900150983cd24fb0d6963f7d28e17f72', 'teacher', NULL),
(25, 5, 'bikram_5', '900150983cd24fb0d6963f7d28e17f72', 'teacher', NULL),
(26, 6, 'anup_6', '900150983cd24fb0d6963f7d28e17f72', 'student', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `parent`
--
CREATE TABLE IF NOT EXISTS `parent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` text NOT NULL,
`mname` varchar(11) DEFAULT NULL,
`lname` text NOT NULL,
`gender` varchar(10) NOT NULL,
`occupation` text NOT NULL,
`contact_id` int(11) NOT NULL,
`email` text,
`mobile` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `parent`
--
INSERT INTO `parent` (`id`, `fname`, `mname`, `lname`, `gender`, `occupation`, `contact_id`, `email`, `mobile`) VALUES
(1, 'Akash', '', 'Karna', 'male', 'Service', 12, '<EMAIL>', 2147483647),
(2, 'Navaraj', '', 'Baniya', 'male', 'Business', 13, '<EMAIL>', 2147483647),
(3, 'Bibek', '', 'Bajracharya', 'male', 'Engineer', 14, '<EMAIL>', 2147483647),
(4, 'Bheema', '', 'Lama', 'male', 'Driver', 15, '', 2147483647),
(5, 'Lalit', 'lal', 'Sharma', 'male', 'Shopkeeper', 16, '', 2147483647),
(6, 'Abc', '', 'shrestha', 'male', 'busness', 22, '', 98);
-- --------------------------------------------------------
--
-- Table structure for table `parent_student_relationship`
--
CREATE TABLE IF NOT EXISTS `parent_student_relationship` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`relation` varchar(20) NOT NULL,
`parent_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `parent_student_relationship`
--
INSERT INTO `parent_student_relationship` (`id`, `student_id`, `relation`, `parent_id`) VALUES
(1, 1, 'Father', 1),
(2, 2, 'Father', 2),
(3, 3, 'Father', 3),
(4, 4, 'Father', 4),
(5, 5, 'Father', 5),
(6, 6, 'Father', 6);
-- --------------------------------------------------------
--
-- Table structure for table `remarks`
--
CREATE TABLE IF NOT EXISTS `remarks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`user_type` int(11) NOT NULL,
`message` text NOT NULL,
`date` date NOT NULL,
`type` text NOT NULL,
`remark_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `remarks`
--
-- --------------------------------------------------------
--
-- Table structure for table `routine`
--
CREATE TABLE IF NOT EXISTS `routine` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`class_id` int(10) NOT NULL,
`picture_name` text NOT NULL,
`type` text NOT NULL,
`image_type` text NOT NULL,
`size` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `routine`
--
INSERT INTO `routine` (`id`, `class_id`, `picture_name`, `type`, `image_type`, `size`) VALUES
(1, 13, 'loadshedding.jpeg', 'image/jpeg', 'class', 180202),
(2, 6, 'class3.jpeg', 'image/jpeg', 'class', 180202),
(3, 7, 'class4.jpeg', 'image/jpeg', 'class', 180202),
(4, 1, 'class1.jpeg', 'image/jpeg', 'class', 180202),
(5, 2, 'class2.jpeg', 'image/jpeg', 'class', 180202),
(6, 8, 'class5.jpeg', 'image/jpeg', 'class', 180202);
-- --------------------------------------------------------
--
-- Table structure for table `salary_structure`
--
CREATE TABLE IF NOT EXISTS `salary_structure` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`class_id` int(10) NOT NULL,
`salary` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
--
-- Dumping data for table `salary_structure`
--
INSERT INTO `salary_structure` (`id`, `class_id`, `salary`) VALUES
(1, 1, 1000),
(2, 2, 1000),
(3, 3, 1000),
(4, 4, 1100),
(5, 5, 1200),
(6, 6, 1300),
(7, 7, 1400),
(8, 8, 1500),
(9, 9, 1600),
(10, 10, 1700),
(11, 11, 1800),
(12, 12, 1900),
(13, 13, 2000);
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE IF NOT EXISTS `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` text NOT NULL,
`mname` text,
`lname` text NOT NULL,
`gender` varchar(10) NOT NULL,
`dob` text NOT NULL,
`blood_group` varchar(10) NOT NULL,
`nationality` text NOT NULL,
`contact_id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL,
`class_id` int(10) NOT NULL,
`admission_date` text NOT NULL,
`previous_school` text NOT NULL,
`email` text,
`photo` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`id`, `fname`, `mname`, `lname`, `gender`, `dob`, `blood_group`, `nationality`, `contact_id`, `parent_id`, `class_id`, `admission_date`, `previous_school`, `email`, `photo`) VALUES
(1, 'Ankit', '', 'Karna', 'male', '2009-02-21', 'A+', 'Nepali', 12, 1, 1, '2013-02-14', '', '', NULL),
(2, 'Raj', '', 'Baniya', 'male', '2009-05-20', 'B-', 'Nepali', 13, 2, 2, '2012-12-26', '', '', NULL),
(3, 'Subindra', '', 'Bajracharya', 'female', '2008-04-12', 'A-', 'Nepali', 14, 3, 3, '2011-01-25', '', '', NULL),
(4, 'Seema', '', 'Lama', 'female', '2007-12-08', 'A+', 'Nepali', 15, 4, 4, '2010-01-20', '', '', NULL),
(5, 'Abhay', 'Kumar', 'Sharma', 'male', '2006-10-12', 'B-', 'Nepali', 16, 5, 6, '2009-02-15', '', '', NULL),
(6, 'anup', '', 'shrestha', 'male', '1990-09-09', 'o+', 'NEPALI', 22, 6, 6, '2013-02-03', '', '', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `student_account`
--
CREATE TABLE IF NOT EXISTS `student_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`last_paid_date` date NOT NULL,
`total_payment` double NOT NULL,
`due` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `student_account`
--
-- --------------------------------------------------------
--
-- Table structure for table `student_attendance`
--
CREATE TABLE IF NOT EXISTS `student_attendance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
`date` date NOT NULL,
`status` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `student_attendance`
--
INSERT INTO `student_attendance` (`id`, `student_id`, `class_id`, `date`, `status`) VALUES
(1, 5, 6, '2013-03-12', 'present'),
(2, 6, 6, '2013-03-12', 'absent');
-- --------------------------------------------------------
--
-- Table structure for table `student_marks`
--
CREATE TABLE IF NOT EXISTS `student_marks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subject_id` int(11) NOT NULL,
`student_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
`marks_obtained` int(11) NOT NULL,
`terminal_id` int(11) NOT NULL,
`remarks` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `student_marks`
--
INSERT INTO `student_marks` (`id`, `subject_id`, `student_id`, `class_id`, `marks_obtained`, `terminal_id`, `remarks`) VALUES
(1, 7, 5, 6, 90, 3, 'pass');
-- --------------------------------------------------------
--
-- Table structure for table `student_payments`
--
CREATE TABLE IF NOT EXISTS `student_payments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`year_month` date NOT NULL,
`date_paid` date NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `student_payments`
--
-- --------------------------------------------------------
--
-- Table structure for table `subject`
--
CREATE TABLE IF NOT EXISTS `subject` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`class_id` int(10) NOT NULL,
`fm` int(11) NOT NULL,
`pm` int(11) NOT NULL,
`remarks` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=33 ;
--
-- Dumping data for table `subject`
--
INSERT INTO `subject` (`id`, `name`, `class_id`, `fm`, `pm`, `remarks`) VALUES
(1, 'Headway English', 4, 100, 40, 'theory'),
(2, 'Health and Physical', 4, 50, 20, 'theory'),
(3, 'Social Studies', 4, 100, 40, 'theory'),
(4, 'Headway English', 5, 100, 40, 'theory'),
(5, 'Mathematics', 5, 100, 40, 'theory'),
(6, 'Social Studies', 5, 100, 40, 'theory'),
(7, 'Science', 6, 100, 40, 'theory'),
(8, 'Mathematics', 6, 100, 40, 'theory'),
(9, 'Nepali', 6, 100, 40, 'theory'),
(10, 'English', 7, 100, 40, 'theory'),
(11, 'Mathematics', 7, 100, 40, 'theory'),
(12, 'Science', 7, 100, 40, 'theory'),
(15, 'Computer', 7, 75, 30, 'theory'),
(14, 'Computer', 7, 25, 10, 'practical'),
(16, 'Mathematics', 8, 100, 40, 'theory'),
(17, 'English', 8, 100, 40, 'theory'),
(18, 'Science', 8, 100, 40, 'theory'),
(19, 'Mathematics', 9, 100, 40, 'theory'),
(20, 'English', 9, 100, 40, 'theory'),
(21, 'Science', 9, 100, 40, 'theory'),
(22, 'English', 10, 100, 40, 'theory'),
(23, 'Mathematics', 10, 100, 40, 'theory'),
(24, 'Computer', 10, 100, 40, 'theory'),
(25, 'Mathematics', 11, 100, 40, 'theory'),
(26, 'Optional Mathematics', 11, 100, 40, 'theory'),
(27, 'Science', 11, 100, 40, 'theory'),
(28, 'Mathematics', 12, 100, 40, 'theory'),
(29, 'Science', 12, 100, 40, 'theory'),
(30, 'Optional Mathematics', 13, 100, 40, 'theory'),
(31, 'Mathematics', 13, 100, 40, 'theory');
-- --------------------------------------------------------
--
-- Table structure for table `teacher`
--
CREATE TABLE IF NOT EXISTS `teacher` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fname` text NOT NULL,
`mname` text,
`lname` text NOT NULL,
`gender` varchar(10) NOT NULL,
`dob` text NOT NULL,
`qualification` text NOT NULL,
`blood_group` text NOT NULL,
`nationality` text NOT NULL,
`contact_id` int(11) NOT NULL,
`email` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `teacher`
--
INSERT INTO `teacher` (`id`, `fname`, `mname`, `lname`, `gender`, `dob`, `qualification`, `blood_group`, `nationality`, `contact_id`, `email`) VALUES
(1, 'Asmita', '', 'Shrestha', 'female', '1990-01-05', 'B.Ed', 'O-', 'Nepali', 17, '<EMAIL>'),
(2, 'Aastha', '', 'Maskey', 'female', '1990-08-10', 'B.Ed', 'B-', 'Nepali', 18, '<EMAIL>'),
(3, 'Pravesh', '', 'Shrestha', 'male', '1989-12-08', 'B.Ed', 'A-', 'Nepali', 19, '<EMAIL>'),
(4, 'Akash', 'Lal', 'Nakarmi', 'male', '1988-01-14', 'B.Ed', 'A+', 'Nepali', 20, ''),
(5, 'Bikram', 'Kaji', 'Basnet', 'male', '1988-09-09', 'M.Ed', 'AB+', 'Nepali', 21, '<EMAIL>');
-- --------------------------------------------------------
--
-- Table structure for table `teacher_account`
--
CREATE TABLE IF NOT EXISTS `teacher_account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`total_payment` double NOT NULL,
`payment_date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `teacher_account`
--
-- --------------------------------------------------------
--
-- Table structure for table `teacher_attendance`
--
CREATE TABLE IF NOT EXISTS `teacher_attendance` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`date` date NOT NULL,
`status` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `teacher_attendance`
--
-- --------------------------------------------------------
--
-- Table structure for table `teacher_payment`
--
CREATE TABLE IF NOT EXISTS `teacher_payment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`year` year(4) NOT NULL,
`month` text NOT NULL,
`date_paid` date NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `teacher_payment`
--
INSERT INTO `teacher_payment` (`id`, `teacher_id`, `year`, `month`, `date_paid`, `amount`) VALUES
(1, 2, 2013, 'Feb', '2013-03-12', 3700);
-- --------------------------------------------------------
--
-- Table structure for table `teacher_sub`
--
CREATE TABLE IF NOT EXISTS `teacher_sub` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subject_id` int(11) NOT NULL,
`teacher_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
--
-- Dumping data for table `teacher_sub`
--
INSERT INTO `teacher_sub` (`id`, `subject_id`, `teacher_id`) VALUES
(1, 1, 2),
(2, 4, 2),
(3, 10, 2),
(4, 3, 4),
(5, 6, 4),
(6, 7, 1),
(7, 12, 1),
(8, 18, 1),
(9, 5, 5),
(10, 19, 5),
(11, 30, 5),
(12, 9, 3),
(13, 14, 3),
(14, 2, 3),
(15, 31, 2);
-- --------------------------------------------------------
--
-- Table structure for table `terminal`
--
CREATE TABLE IF NOT EXISTS `terminal` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
--
-- Dumping data for table `terminal`
--
INSERT INTO `terminal` (`id`, `name`, `date`) VALUES
(1, 'first', '2069-09-09'),
(2, 'second', '2069-09-09'),
(3, 'second', '2069-09-09'),
(4, 'second', '2069-09-09');
<file_sep><?php
require_once('../includes/initialize.php');
if (!$session->is_logged_in()) { redirect_to("../login.php"); }
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="add_subject.php" class="menuItem">Add Subject</a>
<a href="view_subject.php" class="menuItem">View Subjects</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>Add Subject</h2>
<?php echo output_message($message); ?>
<form method="POST" action="admin_subject.php" id="add_subject" name="add">
<fieldset>
<legend>Subject Information</legend>
<label>Subject Name:</label>
<input type="text" name="name" required="true" size =50/><br/><br/>
<label>Class:</label>
<SELECT NAME="class_id">
<OPTION VALUE=0>Choose
<?php echo Routine::get_all_class() ;?>
</SELECT></br><br/>
<label>Full Marks:</label><input type = "text" name="fm" required="true" size=10/><br/><br/>
<label>Pass Marks:</label><input type = "text" name="pm" required="true" size=10/><br/><br/>
<label>Type:</label>
<SELECT NAME="remark">
<OPTION VALUE=0>Choose
<OPTION VALUE="theory">Theory
<OPTION VALUE="practical">Practical
</SELECT><br/><br/>
<input type="submit" name="submit" value="Add" /><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once("includes/initialize.php"); ?>
<?php if($session->is_logged_in()) {
redirect_to($_SESSION['user_type']."/index.php");
}
?>
<?php include_layout_template('header.php'); ?>
<?php include_layout_template('menu.php'); ?>
<?php include_layout_template('content_start.php'); ?>
<?php include_layout_template('content_right_start.php'); ?>
<p>
<h1><center>MEMBERS</center></h1>
</p>
<ul>
<li>067-BCT-503 (ANJAN RAI)</li>
<li>067-BCT-504 (ANJU MAHARJAN)</li>
<li>067-BCT-505 (ANUP SHRESTHA)</li>
<li>067-BCT-523 (DIPENDRA SHRESTHA)</li>
</ul>
<?php include_layout_template('content_end.php'); ?>
<?php include_layout_template('footer.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<h4>Attendance here!!</h4>
</p>
<p>
<a href="view_attendance.php" class="menuItem">View Attendance</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
$class_id = Teacher::check_classteacher($_SESSION['user_id']);
if(!$class_id) {
echo "You are not allowed to access this section!".'</br>';
}
else {
if($_SERVER["REQUEST_METHOD"] == "POST") {
//print_array($_POST);
Teacher::student_attendance($_POST);
}
else {
$students = Teacher::find_student_by_class($class_id);
?>
<p><h3>Today is: <?php echo date("Y-m-d") . "<br />"; ?></h3></p>
<?php
if(!empty($students)) {
?>
<form method="POST" action="">
<table class="bordered">
<tr>
<th>Student Name</th>
<th>Status</th>
</tr>
<?php
foreach($students as $student) {
?>
<tr>
<td><?php echo full_name($student['fname'],$student['lname'],$student['mname'])?></td>
<td><input type="radio" name="<?php echo $student['id']; ?>" value="present" required="true">Present
<input type="radio" name="<?php echo $student['id']; ?>" value="absent" required="true">Absent</br></td>
</tr>
<?php
}
?>
</table>
<input type="hidden" name="class_id" value="<?php echo $class_id;?>"/><br/><br/>
<input type="submit" name="submit" value="Submit"/><br/><br/>
</form>
<?php
}
else {
echo "<p>There are no students in your class.</p>";
}//form else end
}//post submit end
}//class teacher or not end
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Add Teacher...
</p>
<p>
<a href="users.php" class="menuItem">Back</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<form method="POST" action="add_address.php" id="add_teacher" name="add">
<fieldset>
<legend>Teacher: Personal Information</legend>
<label>First Name:</label><br/>
<input type="text" name="fname" required="true" /><br/>
<label>Middle Name:</label><br/>
<input type="text" name="mname" /><br/>
<label>Last Name:</label><br/>
<input type="text" name="lname" required="true"/><br/>
<label>Gender</label><br/>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female<br/>
<label>Date Of Birth: </label> <input type="text" name="dob" id="datepicker" required="true"/><br/>
<label>Mobile No. :</label><br/><input type="text" name="mobile_no"/><br/>
<label>Qualification: </label><input type="text" name="qualification" required="true"/><br/>
<label>Blood Group:</label><input type="text" name="blood_group" required="true" size = 5/><br/>
<label>Nationality: </label>
<input type="text" name="nationality" required="true"/><br/>
<label>Email: </label><input type="text" name="email"/><br/>
<br />
<input type="hidden" name="flag" value="login"/>
<input type="hidden" name="type" value="2"/><br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep>$(document).ready(function(){
$(document).on("click","#contact", function(){
$("#contact_div").toggle();
});
$(document).on("click","#parent", function(){
$("#parent_div").toggle();
});
});
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php
if(!empty($_GET['del'])) {
//Subject::del_teacher_sub($_GET['tsid']);
redirect_to("teacher_subject.php?id=".$_GET['id']);
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
</p>
<p>
<?php echo'<a href="teacher_details.php?id='.$_GET['id'].'" class="menuItem">Back</a>' ?>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
</br>
<?php
if(empty($_GET['id'])) {
$session->message("No teacher ID was provided.");
}
$salary_details = Account::check_payment($_GET['id']);
?>
<caption>Payments:</caption>
<table class="bordered">
<tr>
<th>Salary of the Year</th>
<th>Salary of the month</th>
<th>Date of Payment</th>
<th>Amount paid</th>
</tr>
<?php foreach($salary_details as $s): ?>
<tr>
<td><?php echo $s['year']; ?></td>
<td><?php echo upcase($s['month']); ?></td>
<td><?php echo $s['date_paid']; ?></td>
<td><?php echo $s['amount']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<hr>
<?php
$salary = Account::calc_salary($_GET['id']);
?>
<?php echo '<h3><p>Salary: '.$salary.'</p></h3></br>';?>
<hr>
</br>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php
if((empty($_GET['id'])&&empty($_GET['subject_id']))) {
//Subject::del_teacher_sub($_GET['tsid']);
redirect_to("subject.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
</p>
<a href="subject.php" class="menuItem">Back</a>
<p>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
$view=Admin::view_students($_GET['id']);
if(empty($view)){echo "There are no students<br/>";}
foreach($view as $show)
{
echo '<ul>';
echo '<li><a href="assign_marks.php?id='.$show['id'].' &&subject_id='.$_GET['subject_id'].'" class = "anchor" id="'.$show['id'].'">'.upcase($show['fname']).' '.upcase($show['lname']).'</a></br>';
echo '</ul>';
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Sujects:
</p>
<p>
<a href="add_subject.php" class="menuItem">Add Subject</a>
<a href="view_subject.php" class="menuItem">View Subjects</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>The list of Subjects...</h2>
<?php
$subjects = Subject::get_all_subject();
if($subjects['total_subject']==0) {
echo "<p>No subjects entered!!</p><br/>";
}
else {
?>
<table class="bordered">
<tr>
<th>Subject Name</th>
<th>Class</th>
<th>Full Marks</th>
<th>Pass Marks</th>
<th>Remarks</th>
<th>Action</th>
</tr>
<?php foreach($subjects as $subject): ?>
<?php if(isset($subject['id'])) {?>
<tr>
<td><?php echo upcase($subject['name']); ?></td>
<td><?php echo Routine::get_class($subject['class_id']); ?></td>
<td><?php echo $subject['fm']; ?></td>
<td><?php echo $subject['pm']; ?></td>
<td><?php echo upcase($subject['remarks']); ?></td>
<td><a href="delete_subject.php?id=<?php echo $subject['id']; ?>">Delete</a></td>
</tr>
<?php } ?>
<?php endforeach; ?>
</table>
<?php
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep>
<?php
require_once("../includes/initialize.php");
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
foreach($_POST as $key=>$value){
$_SESSION['form_data']['parent'][$key]=$value;
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="#" class="menuItem">Add Student</a>
<a href="#" class="menuItem">Add Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<form method="POST" action="register_users.php" id="add_parent" name="f_add">
<fieldset>
<legend>Personal Information</legend>
<label>Admission date:<label/>
<input type="text" name="admission_date" id="datepicker" required="true"/><br/>
<label>Name of Previous school:<label/>
<input type="text" name="previous_school" size=50/><br/>
<br/>
<input type="submit" name="add_btn" value="Submit"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?><file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<script src="../js/users.js"></script>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Manage Users:
</p>
<p>
<a href="add_admin.php" class="menuItem">Add Another Admin</a>
</p>
<p><h3>Add:</h3></p>
<p>
<a href="add_student.php" class="menuItem">Add Student</a>
<a href="add_teacher.php" class="menuItem">Add Teacher</a>
</p>
<p><h3>View:</h3></p>
<p>
<a href="#" type="student" class="menuItem view">View Students</a>
<a href="#" type="teacher" class="menuItem view">View Teachers</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<h2>In this section you can add and view students and teachers account..</h2>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php $teachers = Admin::find_all_teacher(); ?>
<?php
foreach($teachers as $teacher)
{
echo '<a href = "teacher_details.php?id='.$teacher['id'].'">'.full_name($teacher['fname'],$teacher['lname'],$teacher['mname']).'</a>'.'</br>';
}
?><file_sep><?php require_once("../includes/initialize.php"); ?>
<?php if (!$session->is_logged_in()) { redirect_to("../login.php"); } ?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Space for a left side link menu if needed:
</p>
<p>
<a href="#" class="menuItem">Update</a>
<a href="#" class="menuItem">Fee Section</a>
<a href="pay_salary.php" class="menuItem">Salary Section</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if(isset($_GET['id'])) {
$salary_details = Account::check_payment($_GET['id']);
?>
<caption>Payments:</caption>
<table class="bordered">
<tr>
<th>Salary [Year(A.D.)]</th>
<th>Month</th>
<th>Date of Payment</th>
<th>Amount paid</th>
</tr>
<?php foreach($salary_details as $s): ?>
<tr>
<td><?php echo $s['year']; ?></td>
<td><?php echo upcase($s['month']); ?></td>
<td><?php echo $s['date_paid']; ?></td>
<td><?php echo $s['amount']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<hr>
<?php
if(isset($_POST['submit'])) {
if(Account::pay_salary($_GET['id'],$_POST))
{
echo "Paid salary for ".$_POST['year'].", ".upcase($_POST['month']).'</br>';
}
else
echo "Not paid.".'</br>';
}
else{
// Account::check_payment($_GET['id']);
$salary = Account::calc_salary($_GET['id']);
?>
<?php echo '<h3><p>Salary: '.$salary.'</p></h3></br>';?>
<hr>
<form method = "POST" action = "">
<fieldset>
<legend>Payment Here:</legend>
<label>Year: </label>
<input type="text" name="year" required="true" size=15/></br>
<label>Month: </label>
<input type="text" name="month" required="true" size=10/></br>
<label>Date Of Payment: </label>
<input type="text" name = "dop" id="datepicker" required="true"/><br/>
<input type="submit" name="submit" value="Paid"/><br/>
</fieldset>
</form>
<?php } ?>
</br>
<?php }
else {
$teachers = Admin::find_all_teacher();
foreach($teachers as $teacher)
{
echo '<a href = "pay_salary.php?id='.$teacher['id'].'">'.full_name($teacher['fname'],$teacher['lname'],$teacher['mname']).'</a>'.'</br>';
}
}
?>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?>
<file_sep><?php require_once('../includes/initialize.php'); ?>
<?php
//check login
if(!$session->is_logged_in()) {
redirect_to("../index.php");
}
?>
<?php include_layout_template('header_inner.php'); ?>
<?php include_layout_template('menu_inner.php'); ?>
<?php include_layout_template('content_start_inner.php'); ?>
<?php include_layout_template('content_left_start_inner.php'); ?>
<p>
<span class="header">links</span>
Space for a left side link menu if needed:
</p>
<p>
<a href="upload_routine.php" class="menuItem">Upload a new routine</a>
<a href="assign_class_teacher.php" class="menuItem">Assign Class Teacher</a>
<a href="remove_class_teacher.php" class="menuItem">Remove Class Teacher</a>
</p>
<?php include_layout_template('content_left_end_inner.php'); ?>
<?php include_layout_template('content_right_start_inner.php'); ?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(Admin::assign_classteacher($_POST))
echo output_message("Assigned!!");
else
echo output_message("Error: Not Assigned!!");
}
?>
<form method="POST" action="" id="add_student" name="add">
<fieldset>
<legend>Assign Class Teacher</legend>
<label>Class:<label/>
<SELECT NAME="class_id">
<OPTION VALUE=0>Choose
<?php echo Routine::get_all_class(); ?>
</SELECT> </br><br/>
<label>Teacher:<label/>
<SELECT NAME="teacher_id">
<OPTION VALUE=0>Choose
<?php $teacher = Teacher::get_all_teacher_option();
echo $teacher;
?>
</SELECT> </br><br/>
<input type="submit" name="add_btn" value="Assign"/><br/><br/>
</fieldset>
</form>
<?php include_layout_template('content_end_inner.php'); ?>
<?php include_layout_template('footer_inner.php'); ?> | ff9aa4299fb4b9f01ce40b41611de58e27dd8ebe | [
"JavaScript",
"SQL",
"PHP"
] | 56 | PHP | AnjuMaharjan/SchoolManagementSystem | c2076948e6902da22c39ab51ce38a097880bbfae | 4c17b1dfea4d99181ca8d8d927da2886ad6f30ea |
refs/heads/master | <file_sep># DDD Event Store PostreSql<file_sep><?php
declare(strict_types=1);
namespace PcComponentes\DddPostgreSQL\Repository;
use PcComponentes\Ddd\Domain\Model\ValueObject\DateTimeValueObject;
use PcComponentes\Ddd\Domain\Model\ValueObject\Uuid;
use PcComponentes\Ddd\Infrastructure\Repository\EventStoreRepository as DddEventStoreRepository;
interface EventStoreRepository extends DddEventStoreRepository
{
public function countEventsFor(Uuid $aggregateId): int;
public function countGivenEventsByAggregate(Uuid $aggregateId, string ...$events): int;
public function countEventsFilteredByAggregate(Uuid $aggregateId, string ...$events): int;
public function countEventsForSince(Uuid $aggregateId, DateTimeValueObject $since): int;
public function getGivenEventsByAggregate(Uuid $aggregateId, int $offset, int $limit, string ...$events): array;
public function getEventsFilteredByAggregate(Uuid $aggregateId, int $offset, int $limit, string ...$events): array;
public function countEventsForSinceVersion(Uuid $aggregateId, int $aggregateVersion): int;
public function getSinceVersion(Uuid $aggregateId, int $aggregateVersion): array;
public function getPaginated(Uuid $aggregateId, int $offset, int $limit): array;
public function getAll(int $offset, int $limit): array;
}
<file_sep><?php
declare(strict_types=1);
namespace PcComponentes\DddPostgreSQL\Repository;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Statement;
use PcComponentes\Ddd\Domain\Model\ValueObject\DateTimeValueObject;
use PcComponentes\Ddd\Domain\Model\ValueObject\Uuid;
use PcComponentes\Ddd\Util\Message\AggregateMessage;
use PcComponentes\Ddd\Util\Message\Serialization\JsonApi\AggregateMessageStream;
use PcComponentes\Ddd\Util\Message\Serialization\JsonApi\AggregateMessageStreamDeserializer;
abstract class PostgresBaseAggregateRepository
{
protected Connection $connection;
protected AggregateMessageStreamDeserializer $deserializer;
private string $occurredOnFormat;
final public function __construct(
Connection $connection,
AggregateMessageStreamDeserializer $deserializer,
string $occurredOnFormat = 'U'
) {
$this->connection = $connection;
$this->deserializer = $deserializer;
$this->occurredOnFormat = $occurredOnFormat;
}
abstract protected function tableName(): string;
protected function insert(AggregateMessage $message): void
{
$stmt = $this->connection->prepare(
\sprintf(
'insert into %s
(message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload)
values
(:message_id, :aggregate_id, :aggregate_version, :occurred_on, :message_name, :payload)',
$this->tableName(),
),
);
$this->bindAggregateMessageValues($message, $stmt);
$this->execute($stmt);
}
protected function forceInsert(AggregateMessage $message): void
{
$stmt = $this->connection->prepare(
\sprintf(
'INSERT INTO %s (message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload)
VALUES
(:message_id, :aggregate_id, :aggregate_version, :occurred_on, :message_name, :payload)
ON CONFLICT (aggregate_id) DO UPDATE SET
message_id = :message_id,
message_name = :message_name,
aggregate_version = :aggregate_version,
payload = :payload,
occurred_on = :occurred_on',
$this->tableName(),
),
);
$this->bindAggregateMessageValues($message, $stmt);
$this->execute($stmt);
}
protected function findByAggregateIdSince(Uuid $aggregateId, DateTimeValueObject $since): array
{
$stmt = $this->connection->prepare(
\sprintf(
'SELECT message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload FROM %s
WHERE aggregate_id = :aggregate_id AND occurred_on > :occurred_on
ORDER BY occurred_on ASC, aggregate_version ASC',
$this->tableName(),
),
);
$value = $aggregateId->value();
$timestamp = $this->mapDatetime($since);
$stmt->bindParam(':aggregate_id', $value);
$stmt->bindParam(':occurred_on', $timestamp);
$this->execute($stmt);
$messages = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$results = [];
foreach ($messages as $message) {
$results[] = $this->deserializer->unserialize($this->convertResultToStream($message));
}
return $results;
}
protected function findByAggregateIdSinceVersion(Uuid $aggregateId, int $aggregateVersion): array
{
$stmt = $this->connection->prepare(
\sprintf(
'SELECT message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload FROM %s
WHERE aggregate_id = :aggregate_id AND aggregate_version > :aggregate_version
ORDER BY aggregate_version ASC',
$this->tableName(),
),
);
$stmt->bindValue('aggregate_id', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->bindValue('aggregate_version', $aggregateVersion, \PDO::PARAM_INT);
$this->execute($stmt);
$messages = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$results = [];
foreach ($messages as $message) {
$results[] = $this->deserializer->unserialize($this->convertResultToStream($message));
}
return $results;
}
protected function findByAggregateId(Uuid $aggregateId): array
{
$stmt = $this->queryByAggregateId($aggregateId);
$events = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$results = [];
foreach ($events as $event) {
$results[] = $this->deserializer->unserialize(
$this->convertResultToStream($event),
);
}
return $results;
}
protected function findByMessageId(Uuid $messageId): ?AggregateMessage
{
$stmt = $this->queryByMessageId($messageId);
$message = $stmt->fetch(\PDO::FETCH_ASSOC);
return $message
? $this->deserializer->unserialize($this->convertResultToStream($message))
: null;
}
protected function findOneByAggregateId(Uuid $aggregateId): ?AggregateMessage
{
$stmt = $this->queryByAggregateId($aggregateId);
$message = $stmt->fetch(\PDO::FETCH_ASSOC);
return $message
? $this->deserializer->unserialize($this->convertResultToStream($message))
: null;
}
protected function countByAggregateId(Uuid $aggregateId): int
{
$stmt = $this->connection->prepare(
\sprintf(
'select COUNT(message_id) as count
from %s
where aggregate_id = :aggregateId',
$this->tableName(),
),
);
$stmt->bindValue('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$this->execute($stmt);
$result = $stmt->fetch();
return $result['count'];
}
protected function countGivenEventsByAggregateId(Uuid $aggregateId, string ...$eventNames): int
{
$stmt = $this->connection
->createQueryBuilder()
->select('count(message_id) as count')
->from($this->tableName())
->where('aggregate_id = :aggregateId')
->andWhere('message_name IN (:eventNames)');
$stmt->setParameter('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->setParameter('eventNames', $eventNames, Connection::PARAM_STR_ARRAY);
return $stmt->execute()->fetchOne();
}
protected function countFilteredEventsByAggregateId(Uuid $aggregateId, string ...$eventNames): int
{
$stmt = $this->connection
->createQueryBuilder()
->select('count(message_id) as count')
->from($this->tableName())
->where('aggregate_id = :aggregateId')
->andWhere('message_name NOT IN (:eventNames)');
$stmt->setParameter('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->setParameter('eventNames', $eventNames, Connection::PARAM_STR_ARRAY);
return $stmt->execute()->fetchOne();
}
protected function countByAggregateIdSince(Uuid $aggregateId, DateTimeValueObject $since): int
{
$stmt = $this->connection->prepare(
\sprintf(
'select COUNT(message_id) as count
from %s
where aggregate_id = :aggregateId AND occurred_on > :occurred_on',
$this->tableName(),
),
);
$stmt->bindValue('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->bindValue('occurred_on', $this->mapDatetime($since), \PDO::PARAM_STR);
$this->execute($stmt);
$result = $stmt->fetch();
return $result['count'];
}
protected function countByAggregateIdSinceVersion(Uuid $aggregateId, int $aggregateVersion)
{
$stmt = $this->connection->prepare(
\sprintf(
'select COUNT(message_id) as count
from %s
where aggregate_id = :aggregateId AND aggregate_version > :aggregateVersion',
$this->tableName(),
),
);
$stmt->bindValue('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->bindValue('aggregateVersion', $aggregateVersion, \PDO::PARAM_INT);
$this->execute($stmt);
$result = $stmt->fetch();
return $result['count'];
}
protected function queryByAggregateIdPaginated(Uuid $aggregateId, int $offset, int $limit): array
{
$stmt = $this->connection->prepare(
\sprintf(
'select message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload
from %s
where aggregate_id = :aggregateId
ORDER BY occurred_on DESC, aggregate_version ASC
LIMIT :limit
OFFSET :offset',
$this->tableName(),
),
);
$stmt->bindValue('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
$stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
$this->execute($stmt);
$events = $stmt->fetchAll();
foreach ($events as $key => $event) {
$events[$key]['payload'] = \json_decode($event['payload'], true);
}
return $events;
}
protected function queryGivenEventsByAggregateIdPaginated(
Uuid $aggregateId,
int $offset,
int $limit,
string ...$eventNames
): array {
$stmt = $this->connection
->createQueryBuilder()
->addSelect('a.message_id, a.aggregate_id, a.aggregate_version, a.occurred_on, a.message_name, a.payload')
->from($this->tableName(), 'a')
->where('a.aggregate_id = :aggregateId')
->andWhere('a.message_name IN (:eventNames)')
->setParameter('aggregateId', $aggregateId->value(), \PDO::PARAM_STR)
->setParameter('eventNames', $eventNames, Connection::PARAM_STR_ARRAY)
->setFirstResult($offset)
->setMaxResults($limit)
->orderBy('a.occurred_on', 'DESC')
->addOrderBy('a.aggregate_version', 'ASC')
->execute();
$events = $stmt->fetchAll();
foreach ($events as $key => $event) {
$events[$key]['payload'] = \json_decode($event['payload'], true);
}
return $events;
}
protected function queryEventsFilteredByAggregateIdPaginated(
Uuid $aggregateId,
int $offset,
int $limit,
string ...$eventNames
): array {
$stmt = $this->connection
->createQueryBuilder()
->addSelect('a.message_id, a.aggregate_id, a.aggregate_version, a.occurred_on, a.message_name, a.payload')
->from($this->tableName(), 'a')
->where('a.aggregate_id = :aggregateId')
->andWhere('a.message_name NOT IN (:eventNames)')
->setParameter('aggregateId', $aggregateId->value(), \PDO::PARAM_STR)
->setParameter('eventNames', $eventNames, Connection::PARAM_STR_ARRAY)
->setFirstResult($offset)
->setMaxResults($limit)
->orderBy('a.occurred_on', 'DESC')
->addOrderBy('a.aggregate_version', 'ASC')
->execute();
$events = $stmt->fetchAll();
foreach ($events as $key => $event) {
$events[$key]['payload'] = \json_decode($event['payload'], true);
}
return $events;
}
protected function execute(Statement $stmt): void
{
$result = $stmt->execute();
if (false !== $result) {
return;
}
$errorInfo = \json_encode($stmt->errorInfo(), \JSON_ERROR_NONE);
$errorCode = (string) $stmt->errorCode();
if (false === \is_string($errorInfo)) {
$errorInfo = '';
}
throw new \RuntimeException(\sprintf('%s | %s', $errorInfo, $errorCode));
}
private function bindAggregateMessageValues(AggregateMessage $message, Statement $stmt): void
{
$stmt->bindValue('message_id', $message->messageId()->value(), \PDO::PARAM_STR);
$stmt->bindValue('aggregate_id', $message->aggregateId()->value(), \PDO::PARAM_STR);
$stmt->bindValue('aggregate_version', $message->aggregateVersion(), \PDO::PARAM_INT);
$stmt->bindValue('occurred_on', $this->mapDatetime($message->occurredOn()), \PDO::PARAM_STR);
$stmt->bindValue('message_name', $message::messageName(), \PDO::PARAM_STR);
$stmt->bindValue(
'payload',
\json_encode($message->messagePayload(), \JSON_THROW_ON_ERROR, 512),
\PDO::PARAM_STR,
);
}
private function convertResultToStream($event): AggregateMessageStream
{
return new AggregateMessageStream(
$event['message_id'],
$event['aggregate_id'],
(float) $event['occurred_on'],
$event['message_name'],
(int) $event['aggregate_version'],
$event['payload'],
);
}
private function queryByAggregateId(Uuid $aggregateId): Statement
{
$stmt = $this->connection->prepare(
\sprintf(
'select message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload
from %s
where aggregate_id = :aggregateId
ORDER BY occurred_on ASC, aggregate_version ASC',
$this->tableName(),
),
);
$stmt->bindValue('aggregateId', $aggregateId->value(), \PDO::PARAM_STR);
$this->execute($stmt);
return $stmt;
}
private function queryByMessageId(Uuid $messageId): Statement
{
$stmt = $this->connection->prepare(
\sprintf(
'select message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload
from %s
where message_id = :message_id',
$this->tableName(),
),
);
$stmt->bindValue('message_id', $messageId->value(), \PDO::PARAM_STR);
$this->execute($stmt);
return $stmt;
}
private function mapDateTime(\DateTimeInterface $occurredOn): string
{
return $occurredOn->format($this->occurredOnFormat);
}
}
<file_sep><?php
declare(strict_types=1);
namespace PcComponentes\DddPostgreSQL\Migration;
final class PostgresMessageStoreDefinition
{
public const EVENT_STORE = 'event_store';
public const SNAPSHOT_STORE = 'snapshot_store';
public static function eventStoreUpSchema(): string
{
return \sprintf(
'
CREATE TABLE %s (
message_id UUID NOT NULL,
aggregate_id varchar(36) NOT NULL,
aggregate_version INT NOT NULL,
occurred_on float NOT NULL,
message_name character varying(128) NOT NULL,
payload jsonb NOT NULL,
PRIMARY KEY(message_id)
);
CREATE INDEX "event_store_message_name" ON "event_store" ("message_name");
CREATE INDEX "event_store_aggregate_id" ON "event_store" ("aggregate_id");
',
self::EVENT_STORE,
);
}
public static function snapshotStoreUpSchema(): string
{
return \sprintf(
'
CREATE TABLE %s (
message_id UUID NOT NULL,
aggregate_id varchar(36) NOT NULL,
aggregate_version INT NOT NULL,
occurred_on float NOT NULL,
message_name character varying(128) NOT NULL,
payload jsonb NOT NULL,
PRIMARY KEY(message_id)
);
CREATE INDEX "snapshot_store_message_name" ON "snapshot_store" ("message_name");
CREATE INDEX "snapshot_store_aggregate_id" ON "snapshot_store" ("aggregate_id");
ALTER TABLE snapshot_store ADD CONSTRAINT "snapshot_store_unique_aggregate_id" UNIQUE ("aggregate_id");
',
self::SNAPSHOT_STORE,
);
}
public static function eventStoreDownSchema(): string
{
return \sprintf('DROP TABLE %s', self::EVENT_STORE);
}
public static function snapshotStoreDownSchema(): string
{
return \sprintf('DROP TABLE %s', self::SNAPSHOT_STORE);
}
}
<file_sep><?php
declare(strict_types=1);
namespace PcComponentes\DddPostgreSQL\Repository;
use PcComponentes\Ddd\Domain\Model\DomainEvent;
use PcComponentes\Ddd\Domain\Model\ValueObject\DateTimeValueObject;
use PcComponentes\Ddd\Domain\Model\ValueObject\Uuid;
use PcComponentes\DddPostgreSQL\Migration\PostgresMessageStoreDefinition;
final class PostgresEventStoreRepository extends PostgresBaseAggregateRepository implements EventStoreRepository
{
public function add(DomainEvent ...$events): void
{
foreach ($events as $theEvent) {
$this->insert($theEvent);
}
}
public function get(Uuid $aggregateId): array
{
return $this->findByAggregateId($aggregateId);
}
public function getPaginated(Uuid $aggregateId, int $offset, int $limit): array
{
return $this->queryByAggregateIdPaginated($aggregateId, $offset, $limit);
}
public function getGivenEventsByAggregate(Uuid $aggregateId, int $offset, int $limit, string ...$events): array
{
return $this->queryGivenEventsByAggregateIdPaginated($aggregateId, $offset, $limit, ...$events);
}
public function getEventsFilteredByAggregate(Uuid $aggregateId, int $offset, int $limit, string ...$events): array
{
return $this->queryEventsFilteredByAggregateIdPaginated($aggregateId, $offset, $limit, ...$events);
}
public function getSince(Uuid $aggregateId, DateTimeValueObject $since): array
{
return $this->findByAggregateIdSince($aggregateId, $since);
}
public function getSinceVersion(Uuid $aggregateId, int $aggregateVersion): array
{
return $this->findByAggregateIdSinceVersion($aggregateId, $aggregateVersion);
}
public function getByMessageId(Uuid $messageId): ?DomainEvent
{
return $this->findByMessageId($messageId);
}
public function getByMessageName(string $messageName): array
{
return [];
}
public function getByMessageNameSince(string $messageName, DateTimeValueObject $since): array
{
return [];
}
public function countEventsFor(Uuid $aggregateId): int
{
return $this->countByAggregateId($aggregateId);
}
public function countGivenEventsByAggregate(Uuid $aggregateId, string ...$events): int
{
return $this->countGivenEventsByAggregateId( $aggregateId, ...$events);
}
public function countEventsFilteredByAggregate(Uuid $aggregateId, string ...$events): int
{
return $this->countFilteredEventsByAggregateId($aggregateId, ...$events);
}
public function countEventsForSince(Uuid $aggregateId, DateTimeValueObject $since): int
{
return $this->countByAggregateIdSince($aggregateId, $since);
}
public function countEventsForSinceVersion(Uuid $aggregateId, int $aggregateVersion): int
{
return $this->countByAggregateIdSinceVersion($aggregateId, $aggregateVersion);
}
public function getAll(int $offset, int $limit): array
{
$stmt = $this->connection->prepare(
\sprintf(
'select message_id, aggregate_id, aggregate_version, occurred_on, message_name, payload
from %s
LIMIT :limit OFFSET :offset',
$this->tableName(),
),
);
$stmt->bindValue('limit', $limit, \PDO::PARAM_INT);
$stmt->bindValue('offset', $offset, \PDO::PARAM_INT);
$this->execute($stmt);
return $stmt->fetchAll();
}
protected function tableName(): string
{
return PostgresMessageStoreDefinition::EVENT_STORE;
}
}
<file_sep><?php
declare(strict_types=1);
namespace PcComponentes\DddPostgreSQL\Repository;
use PcComponentes\Ddd\Domain\Model\Snapshot;
use PcComponentes\Ddd\Domain\Model\ValueObject\Uuid;
use PcComponentes\Ddd\Infrastructure\Repository\SnapshotStoreRepository;
use PcComponentes\DddPostgreSQL\Migration\PostgresMessageStoreDefinition;
final class PostgresSnapshotStoreRepository extends PostgresBaseAggregateRepository implements SnapshotStoreRepository
{
public function set(Snapshot $snapshot): void
{
$this->forceInsert($snapshot);
}
public function get(Uuid $aggregateId): ?Snapshot
{
return $this->findOneByAggregateId($aggregateId);
}
public function remove(Snapshot $snapshot): void
{
// TODO: Implement remove() method.
}
protected function tableName(): string
{
return PostgresMessageStoreDefinition::SNAPSHOT_STORE;
}
}
| 486ad9079dbe37d8dc41fc7bd7163f1b4349d53b | [
"Markdown",
"PHP"
] | 6 | Markdown | PcComponentes/ddd-postgresql | 6e14643d54b2dd5edde96973b13dc2fc333e9854 | 15bb9c748ce629d5e866621eb20fe0181108db48 |
refs/heads/master | <file_sep>export default class Planet {
constructor({ climate, gravity, name, orbital_period, population, rotation_period, terrain }) {
this.climate = climate
this.gravity = gravity
this.name = name
this.orbitalPeriod = orbital_period
this.population = population
this.rotationPeriod = rotation_period
this.terrain = terrain
}
get Template() {
return /*html*/`
<div class='col-3'>
<div class="card p-2 value">
${this.name} - ${this.climate} ${this.terrain}
</div>
</div>
`
}
} | 75927090a0aa93fce5af8a9df5737fd84b48e8e8 | [
"JavaScript"
] | 1 | JavaScript | CoreyWhitmore/fall2020-swapi | 3caa90a7df0aa37be7ebb540e4802f49648df51f | bf01d33a8a1c92ae36e79865cd22ae87d306ae33 |
refs/heads/master | <file_sep>### To start the server
From the path of server.js
`node server.js`
### URL to the website
http://localhost:7007
Reference article
https://dev.to/lisahjung/beginner-s-guide-to-creating-a-node-js-server-3d0j
<file_sep>//Routes to handle client requests
//Package contains writeFile functionality which allows us to create a file
const fs = require("fs");
//CreateServer() method in server.js accepts a requestListener function
const requestListener = (req, res) => {
//Can filter various fields
console.log(req.url, req.method, req.headers)
const url = req.url;
if (url === "/") {
res.setHeader("Content-Type", 'text/html')
res.write("<html>");
res.write("<head><title>All the Feels</title></head>");
res.write(
'<body><h1>Hey there, welcome to the food tracker!</h1><p>Enter any food below and hit send to save your food.</p><form action = "/food" method="POST"><input type = "text" name="food"><button type = "submit">Send</button></body>'
);
res.write("</html>");
return res.end();
}
if (url === "/food" && req.method === "POST") {
const body = [];
req.on("data", (chunk) => {
body.push(chunk);
});
//The first parameter specifies the name of the event and the second parameter defines the function triggered by an event
return req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
console.log(parsedBody)
const food = parsedBody.split("=")[1];
fs.writeFile('user_food.txt', food, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
return res.end();
});
}
};
//export routes file so that routes could be imported into server.js
module.exports = requestListener;<file_sep>//import all the necessary components to set up a server
//http core module to launch a server
//import modules by using the require() keyword
const http = require('http')
//import routes.js as constant
const routes = require("./routes")
//creates a server and accepts a requestListener function
const server = http.createServer(routes)
//listen for incoming requests from the browser
server.listen(7007); | 4d0ab3d796c714226602abc7219b431370f0ad08 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | theqajedi/first-node-js-try | 3464345ac6621aeb4df83c1e7020804d9ac47bd1 | a0a41ed122f3899ec10d54ebe5ce09fec99868c6 |
refs/heads/master | <repo_name>Codeleton011/Example_C_Programs<file_sep>/C_Dynamic_memory_allocation/C_Dynamic_memory_allocation/Main.c
// C_Dynamic_memory_allocation
// Author: Codeleton011
// Date: 2017. 05. 18
#include <stdio.h>
// Employee structure
typedef struct{
int age;
char* name;
float sallary;
} employee;
// Main
int main()
{
//Dynamic memory allocation
employee * em1 = malloc(sizeof(employee));
em1->age = 20;
em1->name = "Employee1";
em1->sallary = 40000;
//Print informations to the screen
printf("Employee information: \n");
printf("Name: %s \n", em1->name);
printf("Age: %d \n", em1->age);
printf("Sallary: %f \n", em1->sallary);
getchar(); // Prevent cmd closed
return 0;
}<file_sep>/C_Keylogger/C_Keylogger/Main.c
// C_Keylogger
// Author: Codeleton011
// Date: 2017. 05. 18.
#include <stdio.h>
#include <conio.h>
#include <string.h>
// Main
int main()
{
while (1)
{
if (_kbhit())
{
char* c = _getch(); // Store the Key in the char
printf("%s", &c); // Print the key to the screen
}
}
return 0;
}<file_sep>/C_Standard_Input_Output/C_Standard_Input_Output/Main.c
// C_Standard_Input_Output
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#define _CRT_SECURE_NO_WARNINGS // Disable unsafe errors
#include <stdio.h>
// Main
int main()
{
char str[50];
// IO with gets and puts
printf("Enter a value:");
gets(str);
printf("\nYou entered:");
puts(str);
char str2[50];
int i;
printf("Enter a value:");
scanf("%s %d", str2, &i);
printf("You entered: %s %d", str2, i);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Predefined_macros/C_Predefined_macros/Main.c
// C_Predefined_macros
// Author: Codeleton011
// Date: 2017. 05. 21
#include <stdio.h>
// Main
int main()
{
printf("File :%s\n", __FILE__);
printf("Date :%s\n", __DATE__);
printf("Time :%s\n", __TIME__);
printf("Line :%d\n", __LINE__);
getchar(); // Prevent cmd closing
return 0;
}<file_sep>/C_Using_header_files/C_Using_header_files/Main.c
// C_Using_header_files
// Author: Codeleton011
// Date: 2017. 05. 21
#include "test.h" // Contains #include <stdio.h>
// Main
int main()
{
int a = 20;
printf("Area of the cube: %d", getCubeArea(a));
getchar(); // Prevent cmd closing
return 0;
}<file_sep>/C_Global_variables/C_Global_variables/Main.c
// C_Global_variables
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#include <stdio.h>
int globalVar = 20; // This int is a global variable
// Main
int main()
{
globalVar = globalVar + 100;
printf("Sum: %d", globalVar);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Hello_World/C_Hello_World/Main.c
// An example C program
// Author: Codeleton011
// Date: 2017. 05. 17
#include <stdio.h> // Standard input-output header file
int main() // Main
{
printf("Hello World!"); // Prints "Hello World!" to the screen
getchar(); // Prevent cmd from closing
return 0;
}<file_sep>/README.md
<h1> Example C Programs </h1>
<img src="http://www.unixstickers.com/image/cache/data/stickers/C/C%20language.sh-600x600.png" width="100"/>
<p> Learn C programming with these examples:) </p>
<p> This examples created with <i>Visual Studio 2013 Ultimate</i> </p>
<b> Made by: Codeleton011 </b>
<file_sep>/C_Using_sizeof_operator/C_Using_sizeof_operator/Main.c
// C_Using_sizeof_operator
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#include <stdio.h>
#include <limits.h>
// Main
int main()
{
// Get storage size of the objects or type in bytes
printf("Int size: %d \n", sizeof(int));
printf("Float size: %d \n", sizeof(float));
printf("Char size: %d \n", sizeof(char));
printf("Double size: %d \n", sizeof(double));
printf("Long size: %d \n", sizeof(long));
getchar(); // Prevent cmd closing
return 0;
}<file_sep>/C_Structures/C_Structures/Main.c
// C_Structures
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#define _CRT_SECURE_NO_WARNINGS // Disable strcpy unsafe error
#include <stdio.h>
#include <string.h>
// Employee -> Structure
struct Employee{
char name[50];
char rank[50];
int sallary;
};
void printEmployee(struct Employee *em);
// Main
int main()
{
// Declare new Employee
struct Employee emp1;
// strcpy from string.h -> strcpy(destination, source);
strcpy(emp1.name, "John");
strcpy(emp1.rank, "Admin");
emp1.sallary = 10000;
//Employee *em pointing to &emp1
printEmployee(&emp1);
getchar(); // Prevent cmd closing
return 0;
}
// Employee *em pointing to an employee
void printEmployee(struct Employee *em)
{
// Access to pointer ID->var
printf("Employee name: %s \n", em->name);
printf("Employee rank: %s \n", em->rank);
printf("Employee sallary: %d \n", em->sallary);
}
<file_sep>/C_1_dimension_array/C_1_dimension_array/Main.c
// C_1_dimension_array
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#include <stdio.h>
// Main
int main()
{
// Char storing 5 numbers
char numbers[5] = { 1, 2, 3, 4, 5 };
// Access the array with for loop
for (int i = 0; i < 5; i++)
{
printf("Numbers[%d] = %d \n", i, numbers[i]);
}
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Error_Handling/C_Error_Handling/Main.c
// C_Error_Handling
// Author: Codeleton011
// Date: 2017. 05. 21
#include <stdio.h>
#include <stdlib.h>
// Main
int main()
{
int divident = 234;
int divisor = 0;
int q;
if (divisor == 0)
{
fprintf(stderr, "Zero Division Error!");
getchar();
exit(-1);
}
// This code is not executed because the divisor is 0
q = divident / divisor;
fprintf(stderr, "Value of quotient : %d\n", q);
return 0;
}<file_sep>/C_The_define_preprocessor/C_The_define_preprocessor/Main.c
// C_define_preprocessor
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#define num1 10
#define num2 20
#include <stdio.h>
// Main
int main()
{
int num3;
num3 = num1 + num2;
printf("Sum: %d", num3);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Basic_Console_Calculator/C_Basic_Console_Calculator/Main.c
// An C Basic Calculator
// Author: Codeleton011
// Date: 2017. 05. 18
// Codeleton011
#define _CRT_SECURE_NO_WARNINGS // Disable scanf warnings
#include <stdio.h>
float a;
float b;
float c;
float sum;
// Main
int main()
{
printf("Welcome to basic c calculator!\n");
printf("First number:");
scanf("%f", &a); // User types the A number
printf("\n");
printf("Second number:");
scanf("%f", &b); // User types the B number
c = a + b; // Sum
printf("Sum: %f", c);
getchar(); // Prevent cmd closed
}<file_sep>/C_Unions/C_Unions/Main.c
// C_Unions
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#define _CRT_SECURE_NO_WARNINGS // Disable strcpy unsafe error
#include <stdio.h>
#include <string.h>
// Union
union Employee{
int sallary;
char name[50];
int foo;
};
// Main
int main()
{
// Access to an union
union Employee emp1;
emp1.sallary = 10000;
printf("Employee sallary: %d \n", emp1.sallary);
strcpy(emp1.name, "John");
printf("Employee name: %s \n", emp1.name);
emp1.foo = 10;
printf("Foo: %d \n", emp1.foo);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Using_header_files/C_Using_header_files/test.c
#include "test.h"
int getCubeArea(int a)
{
return a*a;
}<file_sep>/C_Using_header_files/C_Using_header_files/test.h
#ifndef TEST_H // Include guard
#define TEST_H
#include <stdio.h>
int getCubeArea(int a);
#endif<file_sep>/C_Pointers/C_Pointers/Main.c
// C_Pointers
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#include <stdio.h>
// Main
int main()
{
int num = 10;
int* p = #
printf("Number: %d \n", num);
printf("Memory address of the number: %d \n", &num);
printf("A pointer pointing to num: %d \n", *p);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Multi_dimensional_array/C_Multi_dimensional_array/Main.c
// C_Multi_dimensional_array
// Author: Codeleton011
// Date: 2017. 05. 21
// Codeleton011
#include <stdio.h>
// Main
int main()
{
// 1->5 numbers 2->5 numbers 3->5 numbers
char numbers[][5] = { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 } };
// Access into numbers with double loop
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 5; j++)
{
printf("Numbers[%d][%d] = %d \n", i, j, numbers[i][j]);
}
}
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_File_IO/C_File_IO/Main.c
// C_File_IO
// Author: Codeleton011
// Date: 2017. 05. 21
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
// Main
int main()
{
FILE *fp;
// ===WRITE===
// Write to a file, if file is not exists the program is creates a new fiel
fp = fopen("test.txt", "w+"); // fopen(path, mode) mode= write+
// See test.txt after this program is executed :P
fprintf(fp, "Hello C Input! \n"); // fprintf(FILE, string);
// Close the FILE
fclose(fp);
// ===READ===
FILE *fr;
char buffer[255];
fr = fopen("test.txt", "r"); // Open in read mode
fgets(buffer, 255, fr); // fgets read file until new line
printf("%s", buffer);
getchar(); // Prevent cmd closing
return 0;
}
<file_sep>/C_Advanced_Console_Calculator/C_Advanced_Console_Calculator/Main.c
// An C Advanced console calculator
// Author: Codeleton011
// Date: 2017. 05. 17
#define _CRT_SECURE_NO_WARNINGS // Disable compiler warnings scanf
#include <stdio.h>
// Pre-defined methods
float add(float a, float b);
float div(float a, float b);
float mul(float a, float b);
float sub(float a, float b);
float a; // First number
float b; // Second number
float sum; // Summary
char answ; // Storing the letters
// Main
int main()
{
printf("*******************************\n");
printf("Advanced console calculator\n");
printf("Please select an operation\n");
printf("Addition - A\n");
printf("Division - D\n");
printf("Multiplication - M\n");
printf("Subtraction - S\n");
printf("Exit app - E\n");
printf("*******************************\n");
printf("Your answer: ");
answ = getchar();
// Switch for operations
switch (answ)
{
case 'A':
printf("Addition: \n");
printf("First number:");
scanf("%f", &a);
printf("\n");
printf("Second number:");
scanf("%f", &b);
sum = add(a, b);
printf("Sum: %f \n", sum);
printf("Press enter for continue...");
getchar();
getchar();
system("cls");
return main();
break;
case 'D':
printf("Division: \n");
printf("First number:");
scanf("%f", &a);
printf("\n");
printf("Second number:");
scanf("%f", &b);
sum = div(a, b);
printf("Sum: %f \n", sum);
printf("Press enter for continue...");
getchar();
getchar();
system("cls");
return main();
break;
case 'M':
printf("Multiplication: \n");
printf("First number:");
scanf("%f", &a);
printf("\n");
printf("Second number:");
scanf("%f", &b);
sum = mul(a, b);
printf("Sum: %f \n", sum);
printf("Press enter for continue...");
getchar();
getchar();
system("cls");
return main();
break;
case 'S':
printf("Subtraction: \n");
printf("First number:");
scanf("%f", &a);
printf("\n");
printf("Second number:");
scanf("%f", &b);
sum = sub(a, b);
printf("Sum: %f \n", sum);
printf("Press enter for continue...");
getchar();
getchar();
system("cls");
return main();
break;
case 'E':
exit(0);
break;
}
}
float add(float a, float b)
{
return a + b;
}
float div(float a, float b)
{
return a - b;
}
float mul(float a, float b)
{
return a * b;
}
float sub(float a, float b)
{
return a / b;
} | 064cb993ac5bde44cd1aa944e2687d9d0d620a19 | [
"Markdown",
"C"
] | 21 | C | Codeleton011/Example_C_Programs | 757e70ea205201bb2461d568335d78246b46bd44 | b6050f2210aa1b3b3040308e3e4ae78f7100fb22 |
refs/heads/main | <file_sep>using System.Collections.Generic;
namespace WebEnterprise.Data.Entities
{
public class Magazine
{
public int ID { set; get; }
public string Name { set; get; }
public List<Document> Documents { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ViewModels.Catalog.Contacts
{
public class GetContactsPagingRequest : PagingRequestBase
{
public string Keyword { get; set; }
public List<Guid> UserIds { get; set; }
public string UserName { get; set; }
public long? ContactId { get; set; }
}
}<file_sep>// change background home header navbar
$(window).on('scroll', function () {
if ($(this).scrollTop() > 50) {
document.querySelector(".background-navbar").setAttribute(
"style", "background-color: rgba(255, 255, 255, .15);backdrop-filter: blur(5px); animation: headerGrowth ease-in 0.3s;"
);
}
else{
document.querySelector(".background-navbar").setAttribute("style", "");
}
});
/*Interactivity to determine when an animated element in in view. In view elements trigger our animation*/
$(document).ready(function() {
//window and animation items
var animation_elements = $.find('.content-block, .content-block2');
var web_window = $(window);
//check to see if any animation containers are currently in view
function check_if_in_view() {
//get current window information
var window_height = web_window.height();
var window_top_position = web_window.scrollTop();
var window_bottom_position = (window_top_position + window_height);
//iterate through elements to see if its in view
$.each(animation_elements, function() {
//get the element sinformation
var element = $(this);
var element_height = $(element).outerHeight();
var element_top_position = $(element).offset().top;
var element_bottom_position = (element_top_position + element_height);
//check to see if this current container is visible (its viewable if it exists between the viewable space of the viewport)
if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
element.addClass('in-view');
} else {
element.removeClass('in-view');
}
});
}
//on or scroll, detect elements in view
$(window).on('scroll resize', function() {
check_if_in_view()
})
//trigger our scroll event on initial load
$(window).trigger('scroll');
$(".search-btn").on("click", function(){
$(".search-input").toggleClass("inclicked");
$(".search-btn").toggleClass("close");
});
// click event
$("#login").on("click", function(e){
e.preventDefault();
$(".popup").addClass("show-popup")
});
$("#close-login").on("click", function(){
$(".popup").removeClass("show-popup")
});
$(".documentBox").on("click", function(e){
console.log("text");
$(".popup-document").addClass("show-popup")
});
});
// validator form login
function validator(options){
function validate(inputElement, rule){
var errorMessage = rule.test(inputElement.value)
var errorElement = inputElement.parentElement.querySelector(options.errorSelector);
if(errorMessage){
errorElement.innerText= errorMessage;
inputElement.parentElement.classList.add('invalid')
}
else{
errorElement.innerText= '';
inputElement.parentElement.classList.remove('invalid');
}
return !errorMessage;
}
var formElement = document.querySelector(options.form);
if(formElement){
formElement.onsubmit = function(e){
options.rules.forEach(rule => {
var inputElement = formElement.querySelector(rule.selector);
var isValid = validate(inputElement, rule);
if(!isValid){
e.preventDefault();
}
});
}
}
if (formElement){
options.rules.forEach(rule => {
var inputElement = formElement.querySelector(rule.selector);
if(inputElement){
inputElement.onblur= function(){
validate(inputElement, rule);
}
inputElement.oninput = function(){
var errorElement = inputElement.parentElement.querySelector(options.errorSelector);
errorElement.innerText= '';
inputElement.parentElement.classList.remove('invalid');
}
}
});
}
};
validator.isRequired = function(selector){
return{
selector : selector,
test: function(value){
return value.trim() ? undefined : 'Please enter your information'
}
}
};
validator.minLength = function(selector, min){
return{
selector : selector,
test: function(value){
return value.length >= min ? undefined : `Please enter at least ${min} characters`
}
}
};
<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.Untilities.Constants;
using WebEnterprise.ViewModels.Catalog.Contacts;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ApiIntegration
{
public class ContactApiClient : BaseApiClient, IContactApiClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
public ContactApiClient(IHttpClientFactory httpClientFactory,
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration)
: base(httpClientFactory, httpContextAccessor, configuration)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_httpClientFactory = httpClientFactory;
}
public async Task<bool> CreateContact(ContactsCreateRequest request)
{
var sessions = _httpContextAccessor
.HttpContext
.Session
.GetString(SystemConstants.AppSettings.Token);
var client = _httpClientFactory.CreateClient("BackendApi");
client.BaseAddress = new Uri(_configuration[SystemConstants.AppSettings.BaseAddress]);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions);
var requestContent = new MultipartFormDataContent();
if (request.ThumbnailImage != null)
{
byte[] data;
using (var br = new BinaryReader(request.ThumbnailImage.OpenReadStream()))
{
data = br.ReadBytes((int)request.ThumbnailImage.OpenReadStream().Length);
}
ByteArrayContent bytes = new ByteArrayContent(data);
requestContent.Add(bytes, "thumbnailImage", request.ThumbnailImage.FileName);
}
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.ApartmentNumber.ToString()) ? "" : request.ApartmentNumber.ToString()), "ApartmentNumber");
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.NameStreet.ToString()) ? "" : request.NameStreet.ToString()), "NameStreet");
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.UserID.ToString()) ? "" : request.UserID.ToString()), "UserID");
var response = await client.PostAsync($"/api/contact/", requestContent);
return response.IsSuccessStatusCode;
}
public async Task<PagedResult<ContactsVm>> GetPagings(GetContactsPagingRequest request)
{
var data = await GetAsync<PagedResult<ContactsVm>>(
$"/api/contact/paging?pageIndex={request.PageIndex}" +
$"&pageSize={request.PageSize}" +
$"&keyword={request.Keyword}&userName={request.UserName}");
return data;
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.Untilities.Constants;
using WebEnterprise.ViewModels.Catalog.Contacts;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ApiIntegration
{
public interface IContactApiClient
{
Task<PagedResult<ContactsVm>> GetPagings(GetContactsPagingRequest request);
Task<bool> CreateContact(ContactsCreateRequest request);
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebEnterprise.ApiIntegration;
using WebEnterprise.ViewModels.Catalog.Positions;
namespace WebEnterprise.Admin.Controllers
{
public class PositionController : BaseController
{
private readonly IUserApiClient _userApiClient;
private readonly IConfiguration _configuration;
private readonly IPositionApiClient _positionApiClient;
public PositionController(IUserApiClient userApiClient,
IPositionApiClient positionApiClient,
IConfiguration configuration)
{
_userApiClient = userApiClient;
_configuration = configuration;
_positionApiClient = positionApiClient;
}
public async Task<IActionResult> Index(string keyword, int pageIndex = 1, int pageSize = 10)
{
var request = new GetPositionsPagingRequest()
{
Keyword = keyword,
PageIndex = pageIndex,
PageSize = pageSize,
};
var data = await _positionApiClient.GetPagings(request);
ViewBag.Keyword = keyword;
if (TempData["result"] != null)
{
ViewBag.SuccessMsg = TempData["result"];
}
return View(data);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Create([FromForm] PositionsCreateRequest request)
{
if (!ModelState.IsValid)
return View(request);
var result = await _positionApiClient.CreatePosition(request);
if (result)
{
TempData["result"] = "Create Document access";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Thêm sản phẩm thất bại");
return View(request);
}
[HttpGet]
public async Task<IActionResult> Edit(int id)
{
var positions = await _positionApiClient.GetById(id);
var editVm = new PositionsVm()
{
ID = positions.ID,
Name = positions.Name,
FacultyID = positions.FacultyID
};
return View(editVm);
}
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Edit([FromForm] PositionsUpdateRequest request)
{
if (!ModelState.IsValid)
return View(request);
var result = await _positionApiClient.UpdatePosition(request);
if (result)
{
TempData["result"] = "Update Position succsess";
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Fail update position");
return View(request);
}
}
}<file_sep>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebEnterprise.Application.Catalog.Positions;
using WebEnterprise.ViewModels.Catalog.Positions;
namespace WebEnterprise.BackendApi.Controllers
{
[Route("api/[Controller]")]
[ApiController]
[Authorize]
public class PositionsController : Controller
{
private readonly IPositionsService _positionsService;
public PositionsController(IPositionsService positionsService)
{
_positionsService = positionsService;
}
//http://localhost:port/documents?pageIndex=1&pageSize=10&CategoryId=
[HttpGet("paging")]
public async Task<IActionResult> GetAllPaging([FromQuery] GetPositionsPagingRequest request)
{
var positions = await _positionsService.GetAllPaging(request);
return Ok(positions);
}
[HttpGet("getbyuser")]
public async Task<IActionResult> GetByUser([FromQuery] GetPositionsPagingRequest request)
{
var documents = await _positionsService.GetAllByUserId(request);
return Ok(documents);
}
//http://localhost:port/contact/1
[HttpGet("{positionId}")]
public async Task<IActionResult> GetById(int positionId)
{
var contacts = await _positionsService.GetById(positionId);
if (contacts == null)
return BadRequest("Can not find position");
return Ok(contacts);
}
[HttpPost]
[Consumes("multipart/form-data")]
[Authorize]
public async Task<IActionResult> Create([FromForm] PositionsCreateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var positionId = await _positionsService.Create(request);
if (positionId == 0)
return BadRequest();
var document = await _positionsService.GetById(positionId);
return CreatedAtAction(nameof(GetById), new { id = positionId }, document);
}
[HttpPut]
public async Task<IActionResult> Update([FromForm] PositionsUpdateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var affectedResult = await _positionsService.Update(request);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var affectedResult = await _positionsService.Delete(id);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
namespace WebEnterprise.ViewModels.Catalog.Contacts
{
public class ContactsUpdateRequest
{
public long ID { get; set; }
public string ApartmentNumber { set; get; }
public string NameStreet { set; get; }
public int TotalOfDocument { set; get; }
public IFormFile ThumbnailImage { get; set; }
}
}<file_sep>using Microsoft.AspNetCore.Http;
using System;
namespace WebEnterprise.ViewModels.Catalog.Contacts
{
public class ContactsCreateRequest
{
public string ApartmentNumber { set; get; }
public string NameStreet { set; get; }
public Guid UserID { get; set; }
public IFormFile ThumbnailImage { get; set; }
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WebEnterprise.Data.Entities;
namespace WebEnterprise.Data.Configurations
{
public class PositionConfigurations : IEntityTypeConfiguration<Position>
{
public void Configure(EntityTypeBuilder<Position> builder)
{
builder.ToTable("Position");
builder.HasKey(x => x.ID);
builder.Property(x => x.ID).UseIdentityColumn();
builder.Property(x => x.Name);
builder.Property(x => x.UserID);
builder.Property(x => x.FacultyID);
builder.HasOne(x => x.Users).WithMany(x => x.Positions).HasForeignKey(x => x.UserID);
builder.HasOne(x => x.Faculties).WithMany(x => x.Positions).HasForeignKey(x => x.FacultyID);
}
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WebEnterprise.Data.Entities;
namespace WebEnterprise.Data.Configurations
{
public class MagazineConfigurations : IEntityTypeConfiguration<Magazine>
{
public void Configure(EntityTypeBuilder<Magazine> builder)
{
builder.ToTable("Magazines");
builder.HasKey(x => x.ID);
builder.Property(x => x.ID).UseIdentityColumn();
builder.Property(x => x.Name);
}
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebEnterprise.Data.Migrations
{
public partial class changepassadmin : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "e4d2421e-f50d-4c0f-8f7c-7bbcf030b90d");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("a0626e5f-0945-425c-9135-421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "954551e0-9106-4cca-8a99-c6b298b0218e", "<KEY> });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "75384f80-b661-4ec3-9c67-6964dfe29263");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("a0626e5f-0945-425c-9135-421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "6677d4f8-85b3-4dac-879c-2d9acc5dbda3", "<KEY> });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.ViewModels.Catalog.Positions;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ApiIntegration
{
public interface IPositionApiClient
{
Task<PagedResult<PositionsVm>> GetPagings(GetPositionsPagingRequest request);
Task<bool> CreatePosition(PositionsCreateRequest request);
Task<PositionsVm> GetById(int id);
Task<bool> UpdatePosition(PositionsUpdateRequest request);
Task<PagedResult<PositionsVm>> GetByUserID(GetPositionsPagingRequest request);
}
}<file_sep>using System;
namespace WebEnterprise.Data.Entities
{
public class Position
{
public int ID { get; set; }
public string Name { get; set; }
public int FacultyID { get; set; }
public Guid UserID { get; set; }
public User Users { get; set; }
public Faculty Faculties { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
namespace WebEnterprise.ViewModels.Catalog.Contacts
{
public class ContactsVm
{
public long ID { set; get; }
public string UserName { get; set; }
public string ApartmentNumber { set; get; }
public string NameStreet { set; get; }
public int TotalOfDocument { set; get; }
public Guid UserIds { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using WebEnterprise.Data.EF;
using WebEnterprise.Data.Entities;
using WebEnterprise.Untilities.Exceptions;
using WebEnterprise.ViewModels.Catalog.Positions;
using WebEnterprise.ViewModels.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
namespace WebEnterprise.Application.Catalog.Positions
{
public class PositionsService : IPositionsService
{
private readonly WebEnterpriseDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
public PositionsService(WebEnterpriseDbContext context, IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
_context = context;
}
public async Task<int> Create(PositionsCreateRequest request)
{
var position = new Position()
{
Name = request.Name,
FacultyID = request.FacultyID,
UserID = request.UserID
};
_context.Positions.Add(position);
await _context.SaveChangesAsync();
return position.ID;
}
public async Task<int> Delete(int positionId)
{
var position = await _context.Positions.FindAsync(positionId);
if (position == null) throw new WebEnterpriseException($"Cannot find a position : {positionId}");
_context.Positions.Remove(position);
return await _context.SaveChangesAsync();
}
public async Task<int> Update(PositionsUpdateRequest request)
{
var position = await _context.Positions.FindAsync(request.ID);
position.Name = request.Name;
position.FacultyID = request.FacultyID;
return await _context.SaveChangesAsync();
}
public async Task<PositionsVm> GetById(int PositionsId)
{
var position = await _context.Positions.FindAsync(PositionsId);
var positionVm = new PositionsVm()
{
ID = position.ID,
Name = position.Name,
FacultyID = position.FacultyID,
UserID = position.UserID,
};
return positionVm;
}
public async Task<PagedResult<PositionsVm>> GetAllPaging(GetPositionsPagingRequest request)
{
var query = from p in _context.Positions
join f in _context.Faculties on p.FacultyID equals f.ID
join u in _context.Users on p.UserID equals u.Id
select new { p, u, f };
if (request.UserIds != null && request.UserIds.Count > 0)
{
query = query.Where(c => request.UserName.Contains(c.p.Users.UserName));
}
if (!string.IsNullOrEmpty(request.Keyword))
{
query = query.Where(x => x.p.Users.UserName.Contains(request.Keyword));
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new PositionsVm()
{
ID = x.p.ID,
Name = x.p.Name,
UserID = x.p.UserID,
UserName = x.u.UserName,
Faculty = x.f.Name
}).ToListAsync();
var pagedResult = new PagedResult<PositionsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
public async Task<PagedResult<PositionsVm>> GetAllByUserId(GetPositionsPagingRequest request)
{
var claimsIdentity = _httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
var userId = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier)?.Value.ToString();
var query = from p in _context.Positions
join f in _context.Faculties on p.FacultyID equals f.ID
join u in _context.Users on p.UserID equals u.Id
where p.UserID.ToString() == userId
select new { p, u, f };
if (request.PositionID.HasValue && request.PositionID.Value > 0)
{
query = query.Where(c => c.u.UserName == request.UserName);
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new PositionsVm()
{
ID = x.p.ID,
UserID = x.u.Id,
UserName = x.u.UserName,
Faculty = x.f.Name,
}).ToListAsync();
var pagedResult = new PagedResult<PositionsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using WebEnterprise.Application.Common;
using WebEnterprise.Application.System.Users;
using WebEnterprise.Data.EF;
using WebEnterprise.Data.Entities;
using WebEnterprise.Untilities.Exceptions;
using WebEnterprise.ViewModels.Catalog.Contacts;
using WebEnterprise.ViewModels.Catalog.UserImage;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.Application.Catalog.Contacts
{
public class ContactsService : IContactsService
{
private readonly WebEnterpriseDbContext _context;
private readonly IStorageService _storageService;
private const string USER_CONTENT_FOLDER_NAME = "user-content";
public ContactsService(WebEnterpriseDbContext context, IStorageService storageService)
{
_context = context;
_storageService = storageService;
}
private async Task<string> SaveFile(IFormFile file)
{
var originalFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fileName = $"{Guid.NewGuid()}{Path.GetExtension(originalFileName)}";
await _storageService.SaveFileAsync(file.OpenReadStream(), fileName);
return "/" + USER_CONTENT_FOLDER_NAME + "/" + fileName;
}
public async Task TotalOfDocument(long documentId)
{
var document = await _context.Documents.FindAsync(documentId);
document.ViewCount += 1;
await _context.SaveChangesAsync();
}
public async Task<long> Create(ContactsCreateRequest request)
{
var contact = new Contact()
{
ApartmentNumber = request.ApartmentNumber,
NameStreet = request.NameStreet,
UserID = request.UserID
};
if (request.ThumbnailImage != null)
{
contact.UserImages = new List<UserImage>()
{
new UserImage()
{
Caption = "Thumbnail image",
DayCreated = DateTime.Now,
FileSize = request.ThumbnailImage.Length,
ImagePath = await this.SaveFile(request.ThumbnailImage),
IsDefault = true,
}
};
}
_context.Contacts.Add(contact);
await _context.SaveChangesAsync();
return contact.ID;
}
public async Task<long> Update(ContactsUpdateRequest request)
{
var contact = await _context.Contacts.FindAsync(request.ID);
contact.ApartmentNumber = request.ApartmentNumber;
contact.NameStreet = request.NameStreet;
contact.TotalofDocument = request.TotalOfDocument;
if (request.ThumbnailImage != null)
{
var thumbnailImage = await _context.UserImages.FirstOrDefaultAsync(i => i.IsDefault == true && i.ContactID == request.ID);
if (thumbnailImage != null)
{
thumbnailImage.FileSize = request.ThumbnailImage.Length;
thumbnailImage.ImagePath = await this.SaveFile(request.ThumbnailImage);
_context.UserImages.Update(thumbnailImage);
}
}
return await _context.SaveChangesAsync();
}
public async Task<long> Delete(long contactId)
{
var contact = await _context.Contacts.FindAsync(contactId);
if (contact == null) throw new WebEnterpriseException($"Cannot find a contact : {contactId}");
var images = _context.UserImages.Where(i => i.ContactID == contactId);
foreach (var image in images)
{
await _storageService.DeleteFileAsync(image.ImagePath);
}
_context.Contacts.Remove(contact);
return await _context.SaveChangesAsync();
}
public async Task<ContactsVm> GetById(long contactId)
{
var contact = await _context.Contacts.FindAsync(contactId);
var contactsViewModel = new ContactsVm()
{
ID = contact.ID,
ApartmentNumber = contact.ApartmentNumber,
NameStreet = contact.NameStreet,
UserIds = contact.UserID
};
return contactsViewModel;
}
public async Task<int> AddImage(long contactId, UserImageCreateRequest request)
{
var userImage = new UserImage()
{
Caption = request.Caption,
DayCreated = DateTime.Now,
IsDefault = request.IsDefault,
ContactID = contactId,
};
if (request.ImageFile != null)
{
userImage.ImagePath = await this.SaveFile(request.ImageFile);
userImage.FileSize = request.ImageFile.Length;
}
_context.UserImages.Add(userImage);
await _context.SaveChangesAsync();
return userImage.ID;
}
public async Task<int> UpdateImage(int imageId, UserImageUpdateRequest request)
{
var userImage = await _context.UserImages.FindAsync(imageId);
if (userImage == null)
throw new WebEnterpriseException($"Cannot find an image with id {imageId}");
if (request.ImageFile != null)
{
userImage.ImagePath = await this.SaveFile(request.ImageFile);
userImage.FileSize = request.ImageFile.Length;
}
_context.UserImages.Update(userImage);
return await _context.SaveChangesAsync();
}
public async Task<int> RemoveImage(int imageId)
{
var userImage = await _context.UserImages.FindAsync(imageId);
if (userImage == null)
throw new WebEnterpriseException($"Cannot find an image with id {imageId}");
_context.UserImages.Remove(userImage);
return await _context.SaveChangesAsync();
}
public async Task<List<UserImageViewModel>> GetListImages(long contactId)
{
return await _context.UserImages.Where(x => x.ContactID == contactId)
.Select(i => new UserImageViewModel()
{
Caption = i.Caption,
DateCreated = i.DayCreated,
FileSize = i.FileSize,
ID = i.ID,
ImagePath = i.ImagePath,
IsDefault = i.IsDefault,
ContactID = i.ContactID,
}).ToListAsync();
}
public async Task<UserImageViewModel> GetImageById(int imageId)
{
var image = await _context.UserImages.FindAsync(imageId);
if (image == null)
throw new WebEnterpriseException($"Cannot find an image with id {imageId}");
var viewModel = new UserImageViewModel()
{
Caption = image.Caption,
DateCreated = image.DayCreated,
FileSize = image.FileSize,
ID = image.ID,
ImagePath = image.ImagePath,
IsDefault = image.IsDefault,
ContactID = image.ContactID,
};
return viewModel;
}
public async Task<PagedResult<ContactsVm>> GetAllByUserId(GetContactsPagingRequest request)
{
var query = from c in _context.Contacts
join u in _context.Users on c.UserID equals u.Id
select new { c, u };
if (request.ContactId.HasValue && request.ContactId.Value > 0)
{
query = query.Where(c => c.u.UserName == request.UserName);
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new ContactsVm()
{
ID = x.c.ID,
ApartmentNumber = x.c.ApartmentNumber,
NameStreet = x.c.NameStreet,
TotalOfDocument = x.c.TotalofDocument
}).ToListAsync();
var pagedResult = new PagedResult<ContactsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
public async Task<PagedResult<ContactsVm>> GetAllPaging(GetContactsPagingRequest request)
{
var query = from c in _context.Contacts
join u in _context.Users on c.UserID equals u.Id
select new { c, u };
if (request.UserIds != null && request.UserIds.Count > 0)
{
query = query.Where(c => request.UserName.Contains(c.c.Users.UserName));
}
if (!string.IsNullOrEmpty(request.Keyword))
{
query = query.Where(x => x.c.Users.UserName.Contains(request.Keyword));
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new ContactsVm()
{
ID = x.c.ID,
ApartmentNumber = x.c.ApartmentNumber,
NameStreet = x.c.NameStreet,
TotalOfDocument = x.c.TotalofDocument,
UserIds = x.c.UserID,
UserName = x.u.UserName
}).ToListAsync();
var pagedResult = new PagedResult<ContactsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebEnterprise.ApiIntegration;
using WebEnterprise.ViewModels.Catalog.Contacts;
namespace WebEnterprise.Admin.Controllers
{
public class ContactController : BaseController
{
private readonly IUserApiClient _userApiClient;
private readonly IConfiguration _configuration;
private readonly IContactApiClient _contactApiClient;
public ContactController(IUserApiClient userApiClient,
IContactApiClient contactApiClient,
IConfiguration configuration)
{
_userApiClient = userApiClient;
_configuration = configuration;
_contactApiClient = contactApiClient;
}
public async Task<IActionResult> Index(string keyword, int pageIndex = 1, int pageSize = 10)
{
var request = new GetContactsPagingRequest()
{
Keyword = keyword,
PageIndex = pageIndex,
PageSize = pageSize,
};
var data = await _contactApiClient.GetPagings(request);
ViewBag.Keyword = keyword;
if (TempData["result"] != null)
{
ViewBag.SuccessMsg = TempData["result"];
}
return View(data);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Create([FromForm] ContactsCreateRequest request)
{
if (!ModelState.IsValid)
return View(request);
var result = await _contactApiClient.CreateContact(request);
if (result)
{
TempData["result"] = "Thêm mới sản phẩm thành công";
return RedirectToAction("Index", "Contact");
}
ModelState.AddModelError("", "Thêm sản phẩm thất bại");
return View(request);
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.Untilities.Constants;
using WebEnterprise.ViewModels.Catalog.Positions;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ApiIntegration
{
public class PositionApiClient : BaseApiClient, IPositionApiClient
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUserApiClient _userApiClient;
public PositionApiClient(IHttpClientFactory httpClientFactory,
IHttpContextAccessor httpContextAccessor,
IConfiguration configuration, IUserApiClient userApiClient)
: base(httpClientFactory, httpContextAccessor, configuration)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_userApiClient = userApiClient;
}
public async Task<bool> CreatePosition(PositionsCreateRequest request)
{
var sessions = _httpContextAccessor
.HttpContext
.Session
.GetString(SystemConstants.AppSettings.Token);
var client = _httpClientFactory.CreateClient("BackendApi");
client.BaseAddress = new Uri(_configuration[SystemConstants.AppSettings.BaseAddress]);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions);
var requestContent = new MultipartFormDataContent();
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.Name) ? "" : request.Name), "Name");
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.FacultyID.ToString()) ? "" : request.FacultyID.ToString()), "FacultyID");
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.UserID.ToString()) ? "" : request.UserID.ToString()), "UserID");
var response = await client.PostAsync($"/api/positions/", requestContent);
return response.IsSuccessStatusCode;
}
public async Task<PagedResult<PositionsVm>> GetByUserID(GetPositionsPagingRequest request)
{
var data = await GetAsync<PagedResult<PositionsVm>>(
$"/api/positions/getbyuser?pageIndex={request.PageIndex}" +
$"&pageSize={request.PageSize}" +
$"&keyword={request.Keyword}&userName={request.UserName}");
return data;
}
public async Task<PositionsVm> GetById(int id)
{
var data = await GetAsync<PositionsVm>($"/api/positions/{id}");
return data;
}
public async Task<PagedResult<PositionsVm>> GetPagings(GetPositionsPagingRequest request)
{
var data = await GetAsync<PagedResult<PositionsVm>>(
$"/api/positions/paging?pageIndex={request.PageIndex}" +
$"&pageSize={request.PageSize}" +
$"&keyword={request.Keyword}&userName={request.UserName}");
return data;
}
public async Task<bool> UpdatePosition(PositionsUpdateRequest request)
{
var sessions = _httpContextAccessor
.HttpContext
.Session
.GetString(SystemConstants.AppSettings.Token);
var client = _httpClientFactory.CreateClient("BackendApi");
client.BaseAddress = new Uri(_configuration[SystemConstants.AppSettings.BaseAddress]);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions);
var requestContent = new MultipartFormDataContent();
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.Name) ? "" : request.Name.ToString()), "name");
requestContent.Add(new StringContent(string.IsNullOrEmpty(request.FacultyID.ToString()) ? "" : request.FacultyID.ToString()), "FacultyID");
var response = await client.PutAsync($"/api/positions/" + request.ID, requestContent);
return response.IsSuccessStatusCode;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.ViewModels.Catalog.Positions;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.Application.Catalog.Positions
{
public interface IPositionsService
{
Task<int> Create(PositionsCreateRequest request);
Task<int> Update(PositionsUpdateRequest request);
Task<int> Delete(int positionId);
Task<PagedResult<PositionsVm>> GetAllPaging(GetPositionsPagingRequest request);
Task<PagedResult<PositionsVm>> GetAllByUserId(GetPositionsPagingRequest request);
Task<PositionsVm> GetById(int positionId);
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ViewModels.Catalog.Positions
{
public class GetPositionsPagingRequest : PagingRequestBase
{
public string Keyword { get; set; }
public List<Guid> UserIds { get; set; }
public string UserName { get; set; }
public int? PositionID { get; set; }
}
}<file_sep>using System;
namespace WebEnterprise.ViewModels.Catalog.Document
{
public class DocumentsVm
{
public long ID { get; set; }
public string UserName { get; set; }
public Guid UserID { get; set; }
public string DocumentPath { get; set; }
public int MagazineID { get; set; }
public int FacultyID { get; set; }
public string Caption { get; set; }
public int ViewCount { get; set; }
public long FileSize { get; set; }
public DateTime CreateOn { set; get; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebEnterprise.Data.Migrations
{
public partial class changListDocument : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Documents_FacultyOfDocumentID",
table: "Documents");
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "83e8b8ce-57ae-41e0-8bc9-c2b5ba5e4b48");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("a0626e5f-0945-425c-9135-421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "73e0f1fb-817f-4aa4-b983-492ff7d42020", "<KEY> });
migrationBuilder.CreateIndex(
name: "IX_Documents_FacultyOfDocumentID",
table: "Documents",
column: "FacultyOfDocumentID");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Documents_FacultyOfDocumentID",
table: "Documents");
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "6d157f2c-<KEY>");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("a0626e5f-0945-425c-9135-421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "5bcce0f3-522d-4bb4-a396-cf943384b066", "<KEY> });
migrationBuilder.CreateIndex(
name: "IX_Documents_FacultyOfDocumentID",
table: "Documents",
column: "FacultyOfDocumentID",
unique: true);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Threading.Tasks;
using WebEnterprise.ViewModels.Catalog.Contacts;
using WebEnterprise.ViewModels.Catalog.UserImage;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.Application.Catalog.Contacts
{
public interface IContactsService
{
Task<long> Create(ContactsCreateRequest request);
Task<long> Update(ContactsUpdateRequest request);
Task<long> Delete(long contactId);
Task<ContactsVm> GetById(long contactId);
Task TotalOfDocument(long documentId);
Task<PagedResult<ContactsVm>> GetAllPaging(GetContactsPagingRequest request);
Task<int> AddImage(long contactId, UserImageCreateRequest request);
Task<int> RemoveImage(int imageId);
Task<int> UpdateImage(int imageId, UserImageUpdateRequest request);
Task<List<UserImageViewModel>> GetListImages(long contactId);
Task<UserImageViewModel> GetImageById(int imageId);
Task<PagedResult<ContactsVm>> GetAllByUserId(GetContactsPagingRequest request);
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using WebEnterprise.Data.Entities;
namespace WebEnterprise.Data.Configurations
{
public class ContactConfigurations : IEntityTypeConfiguration<Contact>
{
public void Configure(EntityTypeBuilder<Contact> builder)
{
builder.ToTable("Contacts");
builder.HasKey(x => x.ID);
builder.Property(x => x.ID).UseIdentityColumn();
builder.Property(x => x.ApartmentNumber);
builder.Property(x => x.NameStreet);
builder.Property(x => x.TotalofDocument);
builder.Property(x => x.UserID);
builder.HasOne(x => x.Users).WithMany(x => x.Contacts).HasForeignKey(x => x.UserID);
}
}
}<file_sep>using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
using WebEnterprise.ApiIntegration;
using WebEnterprise.ViewModels.Catalog.Document;
namespace WebEnterprise.Admin.Controllers
{
public class DocumentController : BaseController
{
private readonly IUserApiClient _userApiClient;
private readonly IConfiguration _configuration;
private readonly IDocumentApiClient _documentApiClient;
public DocumentController(IUserApiClient userApiClient,
IDocumentApiClient documentApiClient,
IConfiguration configuration)
{
_userApiClient = userApiClient;
_configuration = configuration;
_documentApiClient = documentApiClient;
}
public async Task<IActionResult> Index(string keyword, int pageIndex = 1, int pageSize = 10)
{
var request = new GetDocumentsPagingRequest()
{
Keyword = keyword,
PageIndex = pageIndex,
PageSize = pageSize,
};
var data = await _documentApiClient.GetPagings(request);
ViewBag.Keyword = keyword;
if (TempData["result"] != null)
{
ViewBag.SuccessMsg = TempData["result"];
}
return View(data);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<IActionResult> Create([FromForm] DocumentsCreateRequest request)
{
if (!ModelState.IsValid)
return View(request);
var result = await _documentApiClient.CreateDocument(request);
if (result)
{
TempData["result"] = "Create Document access";
return RedirectToAction("Index", "Document");
}
ModelState.AddModelError("", "Thêm sản phẩm thất bại");
return View(request);
}
}
}<file_sep>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using WebEnterprise.Application.Catalog.Contacts;
using WebEnterprise.ViewModels.Catalog.Contacts;
using WebEnterprise.ViewModels.Catalog.UserImage;
namespace WebEnterprise.BackendApi.Controllers
{
[Route("api/[Controller]")]
[ApiController]
[Authorize]
public class ContactController : ControllerBase
{
private readonly IContactsService _contactsService;
public ContactController(IContactsService contactsService)
{
_contactsService = contactsService;
}
//http://localhost:port/contact?pageIndex=1&pageSize=10&CategoryId=
[HttpGet("paging")]
public async Task<IActionResult> GetAllPaging([FromQuery] GetContactsPagingRequest request)
{
var contacts = await _contactsService.GetAllPaging(request);
return Ok(contacts);
}
//http://localhost:port/contact/1
[HttpGet("{contactId}")]
public async Task<IActionResult> GetById(long contactId)
{
var contacts = await _contactsService.GetById(contactId);
if (contacts == null)
return BadRequest("Can not find contact");
return Ok(contacts);
}
[HttpPost]
[Consumes("multipart/form-data")]
[Authorize]
public async Task<IActionResult> Create([FromForm] ContactsCreateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var contactId = await _contactsService.Create(request);
if (contactId == 0)
return BadRequest();
var contact = await _contactsService.GetById(contactId);
return CreatedAtAction(nameof(GetById), new { id = contactId }, contact);
}
[HttpPut]
public async Task<IActionResult> Update([FromForm] ContactsUpdateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var affectedResult = await _contactsService.Update(request);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
[HttpDelete("{contactId}")]
public async Task<IActionResult> Delete(int contactId)
{
var affectedResult = await _contactsService.Delete(contactId);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
[HttpGet("{contactId}/images/{imageId}")]
public async Task<IActionResult> GetImageById(long contactId, int imageId)
{
var image = await _contactsService.GetImageById(imageId);
if (image == null)
return BadRequest("Cannot find contact");
return Ok(image);
}
//Image
[HttpPost("{contactId}/images")]
public async Task<IActionResult> CreateImage(int contactId, [FromForm] UserImageCreateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var imageId = await _contactsService.AddImage(contactId, request);
if (imageId == 0)
return BadRequest();
var image = await _contactsService.GetImageById(imageId);
return CreatedAtAction(nameof(GetImageById), new { id = imageId }, image);
}
[HttpPut("{contactId}/images/{imageId}")]
[Authorize]
public async Task<IActionResult> UpdateImage(int imageId, [FromForm] UserImageUpdateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _contactsService.UpdateImage(imageId, request);
if (result == 0)
return BadRequest();
return Ok();
}
[HttpDelete("{contactId}/images/{imageId}")]
[Authorize]
public async Task<IActionResult> RemoveImage(int imageId)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await _contactsService.RemoveImage(imageId);
if (result == 0)
return BadRequest();
return Ok();
}
}
}<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using WebEnterprise.Application.Common;
using WebEnterprise.Data.EF;
using WebEnterprise.Data.Entities;
using WebEnterprise.Untilities.Constants;
using WebEnterprise.Untilities.Exceptions;
using WebEnterprise.ViewModels.Catalog.Document;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.Application.Catalog.Documents
{
public class DocumentsService : IDocumentsService
{
private readonly WebEnterpriseDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IStorageService _storageService;
private const string USER_CONTENT_FOLDER_NAME = "user-content";
public DocumentsService(WebEnterpriseDbContext context, IStorageService storageService, IHttpContextAccessor httpContextAccessor)
{
_context = context;
_storageService = storageService;
_httpContextAccessor = httpContextAccessor;
}
private async Task<string> SaveFile(IFormFile file)
{
var originalFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fileName = $"{Guid.NewGuid()}{Path.GetExtension(originalFileName)}";
await _storageService.SaveFileAsync(file.OpenReadStream(), fileName);
return "/" + USER_CONTENT_FOLDER_NAME + "/" + fileName;
}
public async Task<long> Create(DocumentsCreateRequest request)
{
var user = new User()
{
};
var document = new Document()
{
UserID = request.UserID,
FacultyOfDocumentID = request.FalcultyOfDocumentID,
MagazineID = request.MagazineID,
Caption = "Document file",
CreateOn = DateTime.Now.Date,
};
if (request.DocumentFile != null)
{
user.Documents = new List<Document>()
{
new Document()
{
Caption = "Document file",
CreateOn = DateTime.Now.Date,
FileSize = request.DocumentFile.Length,
DocumentPath = await this.SaveFile(request.DocumentFile),
}
};
}
if (request.FalcultyOfDocumentID == 1)
{
SystemConstants.SendMail("<EMAIL>");
}
_context.Documents.Add(document);
await _context.SaveChangesAsync();
return document.ID;
}
public async Task<long> Delete(long documentId)
{
var document = await _context.Documents.FindAsync(documentId);
if (document == null) throw new WebEnterpriseException($"Cannot find a document : {documentId}");
_context.Documents.Remove(document);
return await _context.SaveChangesAsync();
}
public async Task<DocumentsVm> GetById(long documentId)
{
var document = await _context.Documents.FindAsync(documentId);
if (document == null)
throw new WebEnterpriseException($"Cannot find an document with id {document}");
var viewModel = new DocumentsVm()
{
Caption = document.Caption,
CreateOn = document.CreateOn,
FileSize = document.FileSize,
ID = document.ID,
DocumentPath = document.DocumentPath,
UserID = document.UserID,
};
return viewModel;
}
public async Task<PagedResult<DocumentsVm>> GetAllPaging(GetDocumentsPagingRequest request)
{
var query = from c in _context.Documents
join u in _context.Users on c.UserID equals u.Id
select new { c, u };
if (request.UserIds != null && request.UserIds.Count > 0)
{
query = query.Where(c => request.UserName.Contains(c.c.User.UserName));
}
if (!string.IsNullOrEmpty(request.Keyword))
{
query = query.Where(x => x.c.User.UserName.Contains(request.Keyword));
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new DocumentsVm()
{
ID = x.c.ID,
UserID = x.c.UserID,
UserName = x.u.UserName,
Caption = x.c.Caption,
FacultyID = x.c.FacultyOfDocumentID,
MagazineID = x.c.MagazineID,
CreateOn = x.c.CreateOn.Date
}).ToListAsync();
var pagedResult = new PagedResult<DocumentsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
public async Task<PagedResult<DocumentsVm>> GetAllByUserId(GetDocumentsPagingRequest request)
{
var claimsIdentity = _httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
var userId = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier)?.Value.ToString();
var query = from c in _context.Documents
join u in _context.Users on c.UserID equals u.Id
where c.UserID.ToString() == userId
select new { c, u };
if (request.DocumentId.HasValue && request.DocumentId.Value > 0)
{
query = query.Where(c => c.u.UserName == request.UserName);
}
int TotalRow = await query.CountAsync();
var data = await query.Skip((request.PageIndex - 1) * request.PageSize)
.Take(request.PageSize)
.Select(x => new DocumentsVm()
{
ID = x.c.ID,
UserID = x.u.Id,
UserName = x.u.UserName,
Caption = x.c.Caption,
FacultyID = x.c.FacultyOfDocumentID,
MagazineID = x.c.MagazineID,
CreateOn = x.c.CreateOn.Date
}).ToListAsync();
var pagedResult = new PagedResult<DocumentsVm>()
{
TotalRecord = TotalRow,
Items = data
};
return pagedResult;
}
public async Task<int> RemoveDocument(int documentId)
{
var document = await _context.Documents.FindAsync(documentId);
if (document == null)
throw new WebEnterpriseException($"Cannot find an image with id {documentId}");
_context.Documents.Remove(document);
return await _context.SaveChangesAsync();
}
public async Task<DocumentsVm> GetByUserId(long documentid)
{
var document = await _context.Documents.FindAsync(documentid);
var user = await (from u in _context.Users
join d in _context.Documents on u.Id equals d.UserID
select d.User.UserName).ToListAsync();
var documentvm = new DocumentsVm()
{
ID = document.ID,
UserName = document.User.UserName,
Caption = document.Caption,
};
return documentvm;
}
}
}<file_sep>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebEnterprise.Application.Catalog.Documents;
using WebEnterprise.ViewModels.Catalog.Document;
namespace WebEnterprise.BackendApi.Controllers
{
[Route("api/[Controller]")]
[ApiController]
[Authorize]
public class DocumentsController : ControllerBase
{
private readonly IDocumentsService _documentsService;
public DocumentsController(IDocumentsService documentsService)
{
_documentsService = documentsService;
}
//http://localhost:port/documents?pageIndex=1&pageSize=10&CategoryId=
[HttpGet("paging")]
public async Task<IActionResult> GetAllPaging([FromQuery] GetDocumentsPagingRequest request)
{
var documents = await _documentsService.GetAllPaging(request);
return Ok(documents);
}
[HttpGet("getbyuser")]
public async Task<IActionResult> GetByUser([FromQuery] GetDocumentsPagingRequest request)
{
var documents = await _documentsService.GetAllByUserId(request);
return Ok(documents);
}
//http://localhost:port/contact/1
[HttpGet("{documentId}")]
public async Task<IActionResult> GetById(long documentId)
{
var contacts = await _documentsService.GetById(documentId);
if (contacts == null)
return BadRequest("Can not find document");
return Ok(contacts);
}
[HttpPost]
[Consumes("multipart/form-data")]
[Authorize]
public async Task<IActionResult> Create([FromForm] DocumentsCreateRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var documentId = await _documentsService.Create(request);
if (documentId == 0)
return BadRequest();
var document = await _documentsService.GetById(documentId);
return CreatedAtAction(nameof(GetById), new { id = documentId }, document);
}
//[HttpPut]
//public async Task<IActionResult> Update([FromForm] ContactsUpdateRequest request)
//{
// if (!ModelState.IsValid)
// {
// return BadRequest(ModelState);
// }
// var affectedResult = await _contactsService.Update(request);
// if (affectedResult == 0)
// return BadRequest();
// return Ok();
//}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var affectedResult = await _documentsService.Delete(id);
if (affectedResult == 0)
return BadRequest();
return Ok();
}
}
}<file_sep>using System;
namespace WebEnterprise.Data.Entities
{
public class UserImage
{
public int ID { get; set; }
public long ContactID { get; set; }
public string ImagePath { get; set; }
public string Caption { get; set; }
public bool IsDefault { get; set; }
public DateTime DayCreated { get; set; }
public long FileSize { get; set; }
public Contact Contacts { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace WebEnterprise.ViewModels.Catalog.Positions
{
public class PositionsUpdateRequest
{
public int ID { get; set; }
public string Name { get; set; }
public int FacultyID { get; set; }
}
}<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace WebEnterprise.Data.Migrations
{
public partial class addnewtablelanguge : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "DataFile",
table: "Documents");
migrationBuilder.DropColumn(
name: "FileType",
table: "Documents");
migrationBuilder.DropColumn(
name: "Name",
table: "Documents");
migrationBuilder.AddColumn<string>(
name: "Caption",
table: "Documents",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "DocumentPath",
table: "Documents",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "FileSize",
table: "Documents",
nullable: false,
defaultValue: 0L);
migrationBuilder.CreateTable(
name: "Languages",
columns: table => new
{
Id = table.Column<string>(unicode: false, maxLength: 5, nullable: false),
Name = table.Column<string>(maxLength: 20, nullable: false),
IsDefault = table.Column<bool>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Languages", x => x.Id);
});
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "75384f80-b661-4ec3-9c67-6964dfe29263");
migrationBuilder.InsertData(
table: "Languages",
columns: new[] { "Id", "IsDefault", "Name" },
values: new object[,]
{
{ "vi", true, "Tiếng Việt" },
{ "en", false, "English" }
});
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("<KEY>421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "6677d4f8-85b3-4dac-879c-2d9acc5dbda3", "AQAAAAEAACcQAAAAEGsQp67cxrGSoow8jiMrfnxGk8Yq3NmTQ2d/VHLIYzm5aR+w/J/o7rdHa7Kf4FCMhw==" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Languages");
migrationBuilder.DropColumn(
name: "Caption",
table: "Documents");
migrationBuilder.DropColumn(
name: "DocumentPath",
table: "Documents");
migrationBuilder.DropColumn(
name: "FileSize",
table: "Documents");
migrationBuilder.AddColumn<byte[]>(
name: "DataFile",
table: "Documents",
type: "varbinary(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "FileType",
table: "Documents",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "Name",
table: "Documents",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.UpdateData(
table: "GroupUsers",
keyColumn: "Id",
keyValue: new Guid("9936b153-37a9-41d8-9781-f0532c25e732"),
column: "ConcurrencyStamp",
value: "abac7402-b589-49ad-9ac2-9766760b55d3");
migrationBuilder.UpdateData(
table: "Users",
keyColumn: "Id",
keyValue: new Guid("a0626e5f-0945-425c-9135-421ce9ffd4a1"),
columns: new[] { "ConcurrencyStamp", "PasswordHash" },
values: new object[] { "bbee473a-7066-45fa-903d-289e396401ea", "<KEY> });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace WebEnterprise.Data.Entities
{
public class Contact
{
public long ID { set; get; }
public string ApartmentNumber { set; get; }
public string NameStreet { set; get; }
public int TotalofDocument { get; set; }
public Guid UserID { get; set; }
public User Users { get; set; }
public List<UserImage> UserImages { get; set; }
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebEnterprise.ViewModels.Catalog.Document;
using WebEnterprise.ViewModels.Common;
namespace WebEnterprise.ApiIntegration
{
public interface IDocumentApiClient
{
Task<PagedResult<DocumentsVm>> GetPagings(GetDocumentsPagingRequest request);
Task<bool> CreateDocument(DocumentsCreateRequest request);
public Task<PagedResult<DocumentsVm>> GetByUserID(GetDocumentsPagingRequest request);
Task<bool> DeleteDocument(long id);
}
} | f803a6498f12bcdc096c2a3c6f95e37c76437d06 | [
"JavaScript",
"C#"
] | 34 | C# | hellomynick/CMSGreenWichProject | 35c0e144463345c977ab29dd81504915dcd0a8ed | 81e84bc4a911e831f1b4b93fde9e642ed338d95a |
refs/heads/master | <repo_name>leanovichilya/morse-decoder<file_sep>/src/index.js
const MORSE_TABLE = {
'.-': 'a',
'-...': 'b',
'-.-.': 'c',
'-..': 'd',
'.': 'e',
'..-.': 'f',
'--.': 'g',
'....': 'h',
'..': 'i',
'.---': 'j',
'-.-': 'k',
'.-..': 'l',
'--': 'm',
'-.': 'n',
'---': 'o',
'.--.': 'p',
'--.-': 'q',
'.-.': 'r',
'...': 's',
'-': 't',
'..-': 'u',
'...-': 'v',
'.--': 'w',
'-..-': 'x',
'-.--': 'y',
'--..': 'z',
'.----': '1',
'..---': '2',
'...--': '3',
'....-': '4',
'.....': '5',
'-....': '6',
'--...': '7',
'---..': '8',
'----.': '9',
'-----': '0'
};
function decode(expr) {
// write your solution here
let decodeSymbol = '';
let morseMessage = '';
let decodeMessage = '';
let countAsterisc = 0;
let count = 0;
for (let i = 0; i < expr.length; i += 1) {
count += 1;
if (expr[i] === '1') {
decodeSymbol += expr[i] + expr[i + 1];
i += 1;
count += 1;
if (decodeSymbol === '10') {
morseMessage += '.';
} else {
morseMessage += '-';
}
decodeSymbol = '';
} else if (expr[i] === '*') {
countAsterisc += 1;
if (countAsterisc === 10) {
decodeMessage += ' ';
countAsterisc = 0;
}
}
if (count % 10 === 0 && morseMessage !== '') {
decodeMessage += MORSE_TABLE[morseMessage];
morseMessage = '';
}
}
return decodeMessage;
}
module.exports = {
decode
};
| 17f616d5050056e22281b8813f8bf8a3c4b1ff50 | [
"JavaScript"
] | 1 | JavaScript | leanovichilya/morse-decoder | 9674069378b68e63d2a08e21541ea727cba8b815 | 4d000025061b855b7c0db9c200d0792d02538686 |
refs/heads/master | <file_sep># Terraform custom provider: Device42
## Description
This is a custom created terraform provider to be used to interact with the device42 API.
## Device Resource: Argument Reference
* name - (required) the server hostname (minus the domain)
* custom_fields - (optional) a hash (map) of custom fields and values that will be added to this device
## Examples:
```
provider "device42" {
host = "api.device42.com" #Optional
username = "user1" #Optional
password = "<PASSWORD>" #Optional
}
resource "device42_device" "server-1" {
name = "server-1" #Required
custom_fields = { #Optional
"bt_lob" = "lob_1" #Optional
"bt_owner" = "terraform" #Optional
}
}
```<file_sep>module terraform-provider-device42
go 1.12
require (
github.com/go-resty/resty/v2 v2.0.0
github.com/hashicorp/terraform v0.12.0
)
<file_sep>package main
import (
"crypto/tls"
"fmt"
"github.com/go-resty/resty/v2"
"github.com/hashicorp/terraform/helper/schema"
)
// Environment variables the provider recognizes for configuration
const (
// Environment variable to configure the device42 api host
HostEnv string = "D42_HOST"
// Environment variable to configure the device42 api username attribute
UsernameEnv string = "D42_USER"
// Environment variable to configure the device42 api password attribute
PasswordEnv string = "<PASSWORD>"
)
// Provider -- main device42 provider structure
func Provider() *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
// -- API Interaction Definitions --
"host": &schema.Schema{
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc(
HostEnv,
"",
),
Description: "The device42 server to interact with.",
},
"password": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(
PasswordEnv,
"",
),
Description: "The password to authenticate with Device42.",
},
"username": &schema.Schema{
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(
UsernameEnv,
"",
),
Description: "The username to authenticate with Device42.",
},
"client_tls_insecure": &schema.Schema{
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether to perform TLS cert verification on the server's certificate. " +
"Defaults to `false`.",
},
},
ResourcesMap: map[string]*schema.Resource{
"device42_device": resourceDevice42Device(),
},
ConfigureFunc: providerConfigure,
}
}
func providerConfigure(d *schema.ResourceData) (interface{}, error) {
host := d.Get("host").(string)
username := d.Get("username").(string)
password := d.Get("password").(string)
tlsInsecure := d.Get("client_tls_insecure").(bool)
if host == "" {
return nil, fmt.Errorf("no Device42 host was provided")
}
client := resty.New()
client.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: tlsInsecure})
client.SetHostURL(fmt.Sprintf("https://%s/api", host))
client.SetBasicAuth(username, password)
return client, nil
}
<file_sep>package main
import (
"fmt"
"log"
"strconv"
"strings"
"github.com/go-resty/resty/v2"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
type customField struct {
Key string `json:"key"`
Notes interface{} `json:"notes"`
Value interface{} `json:"value"`
}
type apiDeviceReadResponse struct {
Aliases []interface{} `json:"aliases"`
AssetNo string `json:"asset_no"`
Category string `json:"category"`
Cpucore interface{} `json:"cpucore"`
Cpucount interface{} `json:"cpucount"`
Cpuspeed interface{} `json:"cpuspeed"`
CustomFields []customField `json:"custom_fields"`
Customer interface{} `json:"customer"`
Datastores []interface{} `json:"datastores"`
DeviceExternalLinks []interface{} `json:"device_external_links"`
DeviceID int64 `json:"device_id"`
DevicePurchaseLineItems []interface{} `json:"device_purchase_line_items"`
HddDetails interface{} `json:"hdd_details"`
Hddcount interface{} `json:"hddcount"`
Hddraid interface{} `json:"hddraid"`
HddraidType interface{} `json:"hddraid_type"`
Hddsize interface{} `json:"hddsize"`
HwDepth interface{} `json:"hw_depth"`
HwModel interface{} `json:"hw_model"`
HwModelID interface{} `json:"hw_model_id"`
HwSize interface{} `json:"hw_size"`
ID int64 `json:"id"`
InService bool `json:"in_service"`
IPAddresses []interface{} `json:"ip_addresses"`
IsItBladeHost string `json:"is_it_blade_host"`
IsItSwitch string `json:"is_it_switch"`
IsItVirtualHost string `json:"is_it_virtual_host"`
LastUpdated string `json:"last_updated"`
MacAddresses []interface{} `json:"mac_addresses"`
Manufacturer interface{} `json:"manufacturer"`
Name string `json:"name"`
Nonauthoritativealiases []interface{} `json:"nonauthoritativealiases"`
Notes string `json:"notes"`
Os interface{} `json:"os"`
RAM interface{} `json:"ram"`
SerialNo string `json:"serial_no"`
ServiceLevel string `json:"service_level"`
Tags []interface{} `json:"tags"`
Type string `json:"type"`
UcsManager interface{} `json:"ucs_manager"`
UUID string `json:"uuid"`
VirtualHostName interface{} `json:"virtual_host_name"`
VirtualSubtype string `json:"virtual_subtype"`
}
type apiResponse struct {
Code int64 `json:"code"`
Msg []interface{} `json:"msg"`
}
func resourceDevice42Device() *schema.Resource {
return &schema.Resource{
Create: resourceDevice42DeviceCreate,
Read: resourceDevice42DeviceRead,
Update: resourceDevice42DeviceUpdate,
Delete: resourceDevice42DeviceDelete,
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Required: true,
Description: "The hostname of the device.",
},
"device_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "virtual",
Description: "The type of the device. " +
"Valid values are 'physical', 'virtual', 'blade', 'cluster', or 'other'.",
ValidateFunc: validation.StringInSlice([]string{
"physical", "virtual", "blade", "cluster", "other",
}, false),
},
"custom_fields": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Computed: true,
Description: "Any custom fields that will be used in device42.",
DiffSuppressFunc: suppressCustomFieldsDiffs,
},
},
}
}
// -----------------------------------------------------------------------------
// Resource CRUD Operations
// -----------------------------------------------------------------------------
func resourceDevice42DeviceCreate(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
name := d.Get("name").(string)
deviceType := d.Get("device_type").(string)
resp, err := client.R().
SetFormData(map[string]string{
"name": name,
"type": deviceType,
}).
SetResult(apiResponse{}).
Post("/device/")
if err != nil {
return err
}
r := resp.Result().(*apiResponse)
if r.Code != 0 {
return fmt.Errorf("API returned code %d", r.Code)
}
log.Printf("[DEBUG] Result: %#v", r)
id := int(r.Msg[1].(float64))
if d.Get("custom_fields") != nil {
fields := d.Get("custom_fields").(map[string]interface{})
bulkFields := []string{}
for k, v := range fields {
bulkFields = append(bulkFields, fmt.Sprintf("%v:%v", k, v))
}
resp, err := client.R().
SetFormData(map[string]string{
"name": name,
"bulk_fields": strings.Join(bulkFields, ","),
}).
SetResult(apiResponse{}).
Put("/1.0/device/custom_field/")
if err != nil {
return err
}
r := resp.Result().(*apiResponse)
if r.Code != 0 {
return fmt.Errorf("API returned code %d", r.Code)
}
}
// Only set ID after all conditions are successfull
d.SetId(strconv.Itoa(id))
return resourceDevice42DeviceRead(d, m)
}
func resourceDevice42DeviceRead(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
resp, err := client.R().
SetResult(apiDeviceReadResponse{}).
Get(fmt.Sprintf("/1.0/devices/id/%s/", d.Id()))
if err != nil {
log.Printf("[WARN] No device found: %s", d.Id())
d.SetId("")
return nil
}
r := resp.Result().(*apiDeviceReadResponse)
fields := flattenCustomFields(r.CustomFields)
d.Set("id", r.ID)
d.Set("name", r.Name)
d.Set("device_type", r.Type)
d.Set("custom_fields", fields)
return nil
}
func resourceDevice42DeviceUpdate(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
name := d.Get("name").(string)
if d.HasChange("custom_fields") {
updateList := setCustomFields(d)
for k, v := range updateList {
resp, err := client.R().
SetFormData(map[string]string{
"name": name,
"key": k,
"value": v.(string),
}).
SetResult(apiResponse{}).
Put("/1.0/device/custom_field/")
if err != nil {
return err
}
r := resp.Result().(*apiResponse)
log.Printf("[DEBUG] Result: %#v", r)
}
}
return resourceDevice42DeviceRead(d, m)
}
func resourceDevice42DeviceDelete(d *schema.ResourceData, m interface{}) error {
client := m.(*resty.Client)
log.Printf("Deleting device %s (UUID: %s)", d.Get("name"), d.Id())
url := fmt.Sprintf("/1.0/devices/%s/", d.Id())
resp, err := client.R().
SetResult(apiResponse{}).
Delete(url)
if err != nil {
return err
}
r := resp.Result().(*apiResponse)
log.Printf("[DEBUG] Result: %#v", r)
return nil
}
func setCustomFields(d *schema.ResourceData) map[string]interface{} {
updatedFields := make(map[string]interface{})
if d.HasChange("custom_fields") {
oldRaw, newRaw := d.GetChange("custom_fields")
old := oldRaw.(map[string]interface{})
new := newRaw.(map[string]interface{})
for k, v := range new {
if old[k] != v {
log.Printf("[DEBUG] Change to custom field: %s, Old Value: '%s', New Value: '%s'", k, old[k], v)
updatedFields[k] = v
}
}
}
return updatedFields
}
func flattenCustomFields(in []customField) map[string]interface{} {
out := make(map[string]interface{}, len(in))
for _, x := range in {
out[x.Key] = x.Value
}
return out
}
func suppressCustomFieldsDiffs(k, old, new string, d *schema.ResourceData) bool {
field := strings.TrimPrefix(k, "custom_fields.")
setFields := d.Get("custom_fields").(map[string]interface{})
if _, ok := setFields[field]; ok {
return false
}
return true
}
| eb7e8b2697eda47d51990bbaa16d2988aa3ba99f | [
"Markdown",
"Go Module",
"Go"
] | 4 | Markdown | jgrancell/terraform-provider-device42 | 869ca4bb6e4ae088f8b617d5f05ca988c7855b8d | 528d02ce1957660c13350fa971d1ab0034fce773 |
refs/heads/master | <repo_name>exilaus/K34M<file_sep>/karya34m/karya34m.ino
//#define timing
//#define timingG
//#define echoserial
char wifi_telebot[20] = "";
char *wifi_ap = "K34M";
char *wifi_pwd = "<PASSWORD>";
char wifi_dns[20] = "K34M";
#include "config_pins.h"
#include "common.h"
#include "gcode.h"
#include "temp.h"
#include "timer.h"
#include "eprom.h"
#include "motion.h"
#include<stdint.h>
#ifdef WIFISERVER
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <FS.h> // Include the SPIFFS library
#include <WebSocketsServer.h>
//#include <TelegramBot.h>
uint8_t wfhead = 0;
uint8_t wftail = 0;
uint8_t wfbuf[BUFSIZE];
char wfb[300];
int wfl = 0;
int bpwf = 0;
ESP8266WebServer server ( 80 );
WebSocketsServer webSocket = WebSocketsServer(81); // create a websocket server on port 81
File fsUploadFile;
//#define NOINTS noInterrupts();
//#define INTS interrupts();
#define NOINTS
#define INTS
String getContentType(String filename) { // convert the file extension to the MIME type
if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
bool handleFileRead(String path) { // send the right file to the client (if it exists)
NOINTS
if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file
xprintf(PSTR("handleFileRead: %s\n"), path.c_str());
String contentType = getContentType(path); // Get the MIME type
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal
if (SPIFFS.exists(pathWithGz)) // If there's a compressed version available
path += ".gz"; // Use the compressed verion
File file = SPIFFS.open(path, "r"); // Open the file
size_t sent = server.streamFile(file, contentType); // Send it to the client
file.close(); // Close the file again
xprintf(PSTR("\tSent file: %s\n") , path.c_str());
return true;
}
//xprintf(PSTR("\tFile Not Found: %s\n") , path.c_str()); // If the file doesn't exist, return false
INTS
return false;
}
void handleFileUpload() { // upload a new file to the SPIFFS
NOINTS
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
String filename = upload.filename;
if (!filename.startsWith("/")) filename = "/" + filename;
xprintf(PSTR("handleFileUpload Name: %s\n"), filename.c_str());
fsUploadFile = SPIFFS.open(filename, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
filename = String();
} else if (upload.status == UPLOAD_FILE_WRITE) {
if (fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
} else if (upload.status == UPLOAD_FILE_END) {
if (fsUploadFile) { // If the file was successfully created
fsUploadFile.close(); // Close the file again
xprintf(PSTR("handleFileUpload Size: %d\n"), upload.totalSize);
server.sendHeader("Location", "/upload"); // Redirect the client to the success page
server.send(303);
} else {
server.send(500, "text/plain", "500: couldn't create file");
}
}
INTS
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) { // When a WebSocket message is received
switch (type) {
case WStype_DISCONNECTED: // if the websocket is disconnected
xprintf(PSTR("[%d] Disconnected!\n"), fi(num));
break;
case WStype_CONNECTED: { // if a new websocket connection is established
IPAddress ip = webSocket.remoteIP(num);
xprintf(PSTR("[%d] Connected from %d.%d.%d.%d url: %s\n"), fi(num), fi(ip[0]), fi(ip[1]), fi(ip[2]), fi(ip[3]), payload);
}
break;
case WStype_TEXT: // if new text data is received
//xprintf(PSTR("%s"),payload);
//webSocket.sendTXT(num, payload);
for (int i = 0; i < lenght; i++) {
buf_push(wf, payload[i]);
}
//webSocket.broadcastTXT(payload);
break;
}
}
void wifiwr(uint8_t s) {
wfb[wfl] = s;
wfl++;
if (s == '\n') {
wfb[wfl] = 0;
wfl = 0;
webSocket.broadcastTXT(wfb);
}
}
//String token = "540208354:<KEY>" ; // REPLACE myToken WITH YOUR TELEGRAM BOT TOKEN
//const char BotToken[] = "540208354:<KEY>";
//#include <WiFiClientSecure.h>
WiFiClientSecure net_ssl;
//TelegramBot bot (BotToken, net_ssl);
void setupwifi() {
NOINTS
WiFi.mode(WIFI_STA);
WiFi.begin( wifi_ap , wifi_pwd);
WiFi.hostname("K34M-"+WiFi.macAddress().substring(4,8));
int i = 0;
while ((WiFi.status() != WL_CONNECTED) and (i < 100)) { // Wait for the Wi-Fi to connect
delay(1000);
++i;
if (i==10) {
WiFi.mode(WIFI_AP);
const char *password = "<PASSWORD>";
WiFi.softAP(wifi_ap, wifi_pwd);
IPAddress ip = WiFi.softAPIP();
xprintf(PSTR("i:%d AP:%s Ip:%d.%d.%d.%d\n"), i , wifi_dns, fi(ip[0]), fi(ip[1]), fi(ip[2]), fi(ip[3]) );
i=100;
}
zprintf(PSTR("."));
}
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
#ifdef TELEGRAM
bot.begin();
char buf[46];
sprintf(buf, "CNC:%s http://%d.%d.%d.%d", wifi_dns, ip[0], ip[1], ip[2], ip[3] );
//if (strlen(wifi_telebot))bot.sendMessage(wifi_telebot, buf);
#endif
if ( MDNS.begin ( wifi_dns) ) {
xprintf(PSTR("MDNS responder started %s\n"), wifi_dns);
}
server.on("/upload", HTTP_GET, []() { // if the client requests the upload page
if (!handleFileRead("/upload.html")) // send it if it exists
server.send ( 200, "text/html", "<form method=\"post\" enctype=\"multipart/form-data\"><input type=\"file\" name=\"name\"> <input class=\"button\" type=\"submit\" value=\"Upload\"></form>" );
});
server.on("/upload", HTTP_POST, // if the client posts to the upload page
[]() {
server.send(200);
}, // Send status 200 (OK) to tell the client we are ready to receive
handleFileUpload // Receive and save the file
);
server.onNotFound([]() { // If the client requests any URI
if (!handleFileRead(server.uri())) // send it if it exists
server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
});
server.begin();
webSocket.begin(); // start the websocket server
webSocket.onEvent(webSocketEvent); // if there's an incomming websocket message, go to function 'webSocketEvent'
MDNS.addService("http", "tcp", 80);
SPIFFS.begin();
INTS
}
void wifi_loop() {
webSocket.loop();
server.handleClient();
// if there is an incoming message...
// its blocking/long time so no use
/* message m = bot.getUpdates(); // Read new messages
if ( m.chat_id != 0 ) { // Checks if there are some updates
Serial.println(m.text);
bot.sendMessage(m.chat_id, m.text); // Reply to the same chat with the same text
}
*/
}
#else
#define wifi_loop()
#endif
int line_done, ack_waiting = 0;
int ct = 0;
uint32_t gt = 0;
int n = 0;
uint32_t kctr = 0;
int akey = 0, lkey = 0;
int kdl = 200;
/*
*/
/*
=========================================================================================================================================================
*/
int tmax, tmin;
uint32_t dbtm, dbcm = 0;
void gcode_loop() {
#ifndef ISPC
/*
if (micros() - dbtm > 1000000) {
dbtm = micros();
extern int32_t dlp;
extern int subp;
float f = (cmctr - dbcm);
f /= XSTEPPERMM;
//if (f>0)
//zprintf(PSTR("Subp:%d STEP:%d %f %d\n"),fi(subp),cmctr,ff(f),fi(dlp/8));
dbcm = cmctr;
}
*/
/*
=========================================================================================================================================================
*/
/*
=========================================================================================================================================================
MOTIONLOOP
=========================================================================================================================================================
*/
int32_t zz;
#ifdef timing
uint32_t t1 = micros();
if (motionloop())
{
uint32_t t2 = micros() - t1;
tmax = fmax(t2, tmax);
tmin = fmin(t2, tmin);
if (ct++ > 1) {
zprintf(PSTR("%d %dus\n"), fi(tmin), fi(tmax));
tmax = 0;
tmin = 1000;
ct = 0;
}
}
#else
for (int i = 0; i < 5; i++) {
if (!motionloop())break;
}
#endif
servo_loop();
if (ack_waiting) {
zprintf(PSTR("ok\n"));
ack_waiting = 0;
n = 1;
}
char c = 0;
// wifi are first class
#ifdef WIFISERVER
if (buf_canread(wf)) {
buf_pop(wf, c);
} else
#endif
{
if (serialav())
{
if (n) {
gt = micros();
n = 0;
}
serialrd(c);
}
}
if (c) {
if (c == '\n') {
lineprocess++;
}
#ifdef echoserial
serialwr(c);
#endif
line_done = gcode_parse_char(c);
if (line_done) {
ack_waiting = line_done - 1;
#ifdef timingG
zprintf(PSTR("Gcode:%dus\n"), fi(micros() - gt));
#endif
}
}
#else
#endif
}
int setupok = 0;
void setupother() {
#ifdef output_enable
zprintf(PSTR("Init motion\n"));
initmotion();
zprintf(PSTR("Init Gcode\n"));
init_gcode();
zprintf(PSTR("Init Temp\n"));
init_temp();
zprintf(PSTR("Init eeprom\n"));
reload_eeprom();
zprintf(PSTR("Init timer\n"));
timer_init();
#else
initmotion();
init_gcode();
init_temp();
reload_eeprom();
timer_init();
#endif
#ifdef WIFISERVER
setupwifi();
#endif
// servo_init();
setupok = 1;
zprintf(PSTR("start\nok\n"));
}
uint32_t t1;
void setup() {
// put your setup code here, to run once:
// Serial.setDebugOutput(true);
serialinit(115200);//115200);
t1 = millis();
//while (!Serial.available())continue;
#ifndef DELAYEDSETUP
setupother();
#endif
}
void loop() {
//demo();
#ifdef DELAYSETUP
if (!setupok && (t1 - millis() > DELAYSETUP * 1000))setupother();
#endif
if (setupok) {
gcode_loop();
wifi_loop();
}
}
<file_sep>/karya34m/eprom.cpp
#include "motion.h"
#include "config_pins.h"
#include "common.h"
//char wifi_telebot[20]="";
//char wifi_ap[40]="myap";
//char wifi_pwd[20]="pwd";
//char wifi_dns[20]="karyacnc";
#ifdef USE_EEPROM
#include "eprom.h"
void reload_eeprom() {
eepromcommit;
ax_home[0] = ((float)eepromread(EE_xhome)) * 0.001;
ax_home[1] = ((float)eepromread(EE_yhome)) * 0.001;
ax_home[2] = ((float)eepromread(EE_zhome)) * 0.001;
accel = eepromread(EE_accelx);
mvaccel = eepromread(EE_mvaccelx);
maxf[0] = eepromread(EE_max_x_feedrate);
maxf[1] = eepromread(EE_max_y_feedrate);
maxf[2] = eepromread(EE_max_z_feedrate);
maxf[3] = eepromread(EE_max_e_feedrate);
stepmmx[0] = (float)eepromread(EE_xstepmm) * 0.001;
stepmmx[1] = (float)eepromread(EE_ystepmm) * 0.001;
stepmmx[2] = (float)eepromread(EE_zstepmm) * 0.001;
stepmmx[3] = (float)eepromread(EE_estepmm) * 0.001;
xyjerk=eepromread(EE_jerk);
homingspeed=eepromread(EE_homing);
xyscale = (float)eepromread(EE_xyscale) * 0.001;
#ifdef NONLINEAR
delta_radius= (float)eepromread(EE_hor_radius) * 0.001;
delta_diagonal_rod= (float)eepromread(EE_rod_length) * 0.001;
#endif
axisofs[0]=(float)eepromread(EE_towera_ofs) * 0.001;
axisofs[1]=(float)eepromread(EE_towerb_ofs) * 0.001;
axisofs[2]=(float)eepromread(EE_towerc_ofs) * 0.001;
#ifdef USE_BACKLASH
xback[0] = eepromread(EE_xbacklash);
xback[1] = eepromread(EE_ybacklash);
xback[2] = eepromread(EE_zbacklash);
xback[3] = eepromread(EE_ebacklash);
#endif
#ifdef WIFISERVER
// eepromreadstring(380,wifi_telebot);
// eepromreadstring(400,wifi_ap);
// eepromreadstring(450,wifi_pwd);
// eepromreadstring(470,wifi_dns);
#endif
preparecalc();
}
void reset_eeprom() {
#ifndef SAVE_RESETMOTION
reset_motion();
eepromwrite(EE_xhome, ff(ax_home[0]));
eepromwrite(EE_yhome, ff(ax_home[1]));
eepromwrite(EE_zhome, ff(ax_home[2]));
eepromwrite(EE_accelx, fi(accel));
eepromwrite(EE_mvaccelx, fi(mvaccel));
eepromwrite(EE_max_x_feedrate, fi(maxf[0]));
eepromwrite(EE_max_y_feedrate, fi(maxf[1]));
eepromwrite(EE_max_z_feedrate, fi(maxf[2]));
eepromwrite(EE_max_e_feedrate, fi(maxf[3]));
eepromwrite(EE_xstepmm, ff(stepmmx[0]));
eepromwrite(EE_ystepmm, ff(stepmmx[1]));
eepromwrite(EE_zstepmm, ff(stepmmx[2]));
eepromwrite(EE_estepmm, ff(stepmmx[3]));
eepromwrite(EE_homing,homingspeed);
eepromwrite(EE_jerk,xyjerk);
eepromwrite(EE_xyscale,ff(xyscale));
#ifdef NONLINEAR
eepromwrite(EE_hor_radius,ff(delta_radius));
eepromwrite(EE_rod_length,ff(delta_diagonal_rod));
#endif
eepromwrite(EE_towera_ofs,ff(axisofs[0]));
eepromwrite(EE_towerb_ofs,ff(axisofs[1]));
eepromwrite(EE_towerc_ofs,ff(axisofs[2]));
#ifdef USE_BACKLASH
eepromwrite(EE_xbacklash, fi(xback[0]));
eepromwrite(EE_ybacklash, fi(xback[1]));
eepromwrite(EE_zbacklash, fi(xback[2]));
eepromwrite(EE_ebacklash, fi(xback[3]));
#endif
eepromcommit;
#endif
}
#else
void reload_eeprom() {}
void reset_eeprom() {}
#endif
<file_sep>/karya34m/timer.cpp
#include <stdlib.h>
#include <stdio.h>
#include "timer.h"
#include <stdint.h>
#include "config_pins.h"
#include "common.h"
#include "motion.h"
#ifdef servo_pin
uint32_t servo_timer = 0;
int32_t servo_pos = 0;
#ifdef __AVR__
static volatile int ISRCount, remainder, counter; // iteration counter used in the interrupt routines;
ISR (TIMER2_OVF_vect)
{
++ISRCount; // increment the overlflow counter
if (ISRCount == counter) { // are we on the final iteration for this channel
TCNT2 = remainder; // yes, set count for overflow after remainder ticks
}
if (ISRCount == (counter + 1)) {
digitalWrite( servo_pin, LOW ); // pulse this channel low if active
} else if (ISRCount > 157) {
digitalWrite( servo_pin, HIGH); // pulse this channel low if active
ISRCount = 0; // reset the isr iteration counter
TCNT2 = 0; // reset the clock counter register
}
}
#endif
void servo_set(int us)
{
counter = us / 128;
remainder = 255 - (2 * (us - ( counter * 128)));
}
void servo_init()
{
pinMode(servo_pin, OUTPUT);
#ifdef __AVR__
servo_set(1000);
ISRCount = 0; // clear the value of the ISR counter;
/* setup for timer 2 */
TIMSK2 = 0; // disable interrupts
TCCR2A = 0; // normal counting mode
TCCR2B = _BV(CS21); // set prescaler of 8 = 2MHZ
TCNT2 = 0; // clear the timer2 count
TIFR2 = _BV(TOV2); // clear pending interrupts;
TIMSK2 = _BV(TOIE2) ; // enable the overflow interrupt
#endif
}
void servo_loop()
{
#ifdef __AVR__
#else
uint32_t m = micros();
if (m - servo_timer > 20000) {
servo_timer = m;
digitalWrite(servo_pin, HIGH);
}
if (m - servo_timer > servo_pos) {
digitalWrite(servo_pin, LOW);
}
#endif
}
#else
void servo_loop() {}
void servo_init() {}
void servo_set(int us) {}
#endif
int somedelay(int32_t n)
{
float f = 0;
int m = 10;
while (m--) {
int nn = n;
while (nn--) {
f += n;
asm("");
}
}
return f + n;
}
//#define somedelay(n) delayMicroseconds(n);
int dogfeed = 0;
#ifndef ISPC
#include<arduino.h>
#define dogfeedevery 200 // loop
// ESP8266 specific code here
#else
#define dogfeedevery 100000 // loop
#include<sys/time.h>
uint32_t micros()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return 1000000 * tv.tv_sec + tv.tv_usec;
}
#endif
int feedthedog()
{
if (dogfeed++ > dogfeedevery) {
dogfeed = 0;
#if defined(__AVR__)
// AVR specific code here
#elif defined(ESP8266)
// ESP8266 specific code here
ESP.wdtFeed();
#else
#endif
//zprintf(PSTR("Feed the dog\n"));
return 1;
}
return 0;
}
// ======================== TIMER for motionloop =============================
uint32_t next_step_time;
#ifdef USETIMER1
int busy1 = 0;
volatile uint32_t ndelay = 0, ndelay2 = 0;
/*
AVR TIMER
*/
#ifdef __AVR__
#define USETIMEROK
#define MINDELAY 45000
ISR(TIMER1_COMPA_vect)
//void tm()
{
TIMSK1 &= ~(1 << OCIE1A);
// stepper tick
//cli();
if (ndelay2 == 0) {
if (ndelay < 30000) {
ndelay = 20;
coreloopm();
TCNT1 = 0;
ndelay = fmax(20, ndelay);
} else {
ndelay = fmax(20, ndelay - 30100);
}
} else {
// turn off laser , laser constant burn mode
ndelay = ndelay2;
ndelay2 = 0;
#ifdef laser_pin
digitalWrite(laser_pin, LOW);
#endif
}
OCR1A = ndelay > 30000 ? 30000 : ndelay;
//sei();
TIMSK1 |= (1 << OCIE1A);
//if (ndelay>40)zprintf(PSTR("%d\n"),fi(ndelay));
}
void timer_init()
{
TCCR1A = 0; // Steup timer 1 interrupt to no prescale CTC mode
TIMSK1 = 0;
TCNT1 = 0;
TCCR1B = (1 << CS11); // no prescaler == 0.0625 usec tick | 001 = clk/1
OCR1A = 65500; //start off with a slow frequency.
TIMSK1 |= (1 << OCIE1A); // Enable interrupt
}
#endif // avr timer
/*
ARM TIMER
*/
#ifdef __ARM__
#define USETIMEROK
//HardwareTimer timer1(2);
#define MINDELAY 45000
void tm()
{
//Timer1.pause();
//zprintf(PSTR(".\n"));
if (ndelay2 == 0) {
if (ndelay < 30000) {
ndelay = 30;
coreloopm();
ndelay = fmax(15, ndelay);
} else {
ndelay = fmax(15, ndelay - 30000);
}
} else {
// turn off laser , laser constant burn mode
ndelay = ndelay2;
ndelay2 = 0;
#ifdef laser_pin
digitalWrite(laser_pin, LOW);
#endif
}
Timer1.setOverflow(ndelay >= 30000 ? 30000 : ndelay);
}
void timer_init()
{
/*
Timer2.setMode(TIMER_CH1, TIMER_OUTPUTCOMPARE);
Timer2.setPeriod(LED_RATE); // in microseconds
Timer2.setCompare(TIMER_CH1, 1); // overflow might be small
Timer2.attachInterrupt(TIMER_CH1, handler_led);
*/
Timer1.setMode(TIMER_CH1, TIMER_OUTPUTCOMPARE);
Timer1.setPrescaleFactor(9);
Timer1.setOverflow(1000); // in microseconds
//Timer1.setCompare(TIMER_CH1, 1); // overflow might be small
Timer1.attachInterrupt(TIMER_CH1, tm);
}
#endif // arm
// ---------------------------------------------------------------------------------------------------------
#ifdef ESP8266
#define USETIMEROK
#define MINDELAY 45000
#define usetmr1
void ICACHE_RAM_ATTR tm()
{
noInterrupts();
if (ndelay2 == 0) {
if (ndelay < 30000) {
ndelay = 30;
coreloopm();
ndelay = fmax(30, ndelay);
} else {
ndelay = fmax(30, ndelay - 30000);
}
} else {
// turn off laser , laser constant burn mode
ndelay = ndelay2;
ndelay2 = 0;
#ifdef laser_pin
digitalWrite(laser_pin, LOW);
#endif
}
#ifdef usetmr1
timer1_write((ndelay >= 30000 ? 30000 : ndelay));
#else
timer0_write(ESP.getCycleCount() + 16 * (ndelay >= 30000 ? 30000 : ndelay));
#endif
interrupts();
}
void timer_init()
{
//Initialize Ticker every 0.5s
noInterrupts();
#ifdef usetmr1
timer1_isr_init();
timer1_attachInterrupt(tm);
timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
timer1_write(1000); //120000 us
#else
timer0_isr_init();
timer0_attachInterrupt(tm);
timer0_write(ESP.getCycleCount() + 16 * 1000); //120000 us
#endif
interrupts();
}
#endif // esp8266
void THEISR timer_set(int32_t delay)
{
ndelay = fmin(MINDELAY, delay);
ndelay2 = 0;
}
void THEISR timer_set2(int32_t delay, int32_t delayL)
{
delay = fmin(MINDELAY, delay);
ndelay = fmax(15, delayL); // laser on delay
ndelay2 = fmax(15, delay - delayL); // the rest delay after laser off
}
#endif
//#elif defined(__ARM__)//avr
#ifndef USETIMEROK
#undef USETIMER1
void timer_init() {};
void timer_set(int32_t delay) {};
void timer_set2(int32_t delay, int32_t delayl) {};
#endif
<file_sep>/karya34m/temp.cpp
#include "config_pins.h"
#include "common.h"
#include "temp.h"
#include "timer.h"
#include "motion.h"
uint32_t next_temp;
uint16_t ctemp = 0;
double Setpoint, Input, Output;
int wait_for_temp = 0;
int fan_val = 0;
void setfan_val(int val) {
#ifdef fan_pin
pinMode(fan_pin, OUTPUT);
#ifdef usetmr1
digitalWrite(fan_pin, val);
#else
analogWrite(fan_pin, val);
#endif
// digitalWrite(fan_pin, val);
fan_val = val;
#endif
}
#if defined(temp_pin) && !defined(ISPC)
#include <PID_v1.h>
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, 8, 2, 12, DIRECT); //2, 5, 1, DIRECT);
#if defined(__AVR__) && defined(ISRTEMP)
int vanalog[8];
int adcpin;
ISR (ADC_vect)
{
uint8_t low, high;
// we have to read ADCL first; doing so locks both ADCL
// and ADCH until ADCH is read. reading ADCL second would
// cause the results of each conversion to be discarded,
// as ADCL and ADCH would be locked when it completed.
low = ADCL;
high = ADCH;
vanalog[adcpin] = (high << 8) | low;
/*Serial.print(adcpin);
Serial.print(":");
Serial.print(vanalog[adcpin]);
Serial.write('\n');
*/
} // end of ADC_vect
#endif
void set_temp(float set) {
Setpoint = set;
pinMode(heater_pin, OUTPUT);
#ifdef usetmr1
digitalWrite(heater_pin, 0);
#else
analogWrite(heater_pin, 0);
#endif
}
void init_temp()
{
//initialize the variables we're linked to
//turn the PID on
myPID.SetMode(AUTOMATIC);
next_temp = micros();
set_temp(0);
#ifdef temp_pin
pinMode(temp_pin, INPUT);
#if defined( __AVR__) && defined(ISRTEMP)
ADCREAD(temp_pin)
#elif defined(ESP8266)
//////////////////////
////// added for esp -- under test
///////////////////////////
analogRead(temp_pin);
//adcvalue = analogRead(A0);
// serial.print("VALUE: "+String(adcvalue));
//////////////////////
////// End added for esp -- under test
///////////////////////////
#endif
#endif
}
float read_temp(int32_t temp) {
for (int j = 0; j < NUMTEMPS; j++) {
//Serial.println(pgm_read_word(&(temptable[j][1])));
// Serial.println(temp);
if ( pgm_read_word(&(temptable[j][0])) <= temp ) {
if (( pgm_read_word(&(temptable[j][0])) - temp) == 0){
return float(pgm_read_word(&(temptable[j][1])));
}
else
{ float tempi = pgm_read_word(&(temptable[j][1]))-pgm_read_word(&(temptable[j-1][1]));
float tempo = pgm_read_word(&(temptable[j-1][0]))-pgm_read_word(&(temptable[j][0]));
tempi= (tempi/tempo)*(pgm_read_word(&(temptable[j-1][0]))- temp)+ pgm_read_word(&(temptable[j-1][1]));
return float(tempi);
}
}
}
return 0;
}
int WindowSize = 1500;
unsigned long windowStartTime;
void temp_loop(uint32_t cm)
{
if (cm-next_temp>TEMPTICK) {
next_temp = cm; // each 0.5 second
int v = 0;
#if defined( __AVR__) && defined(ISRTEMP)
// automatic in ESR
ADCREAD(temp_pin)
v = vanalog[temp_pin];
#else
// v = analogRead(temp_pin) >> ANALOGSHIFT;
//zprintf(PSTR("%d\n"),fi(v));
#endif
#ifdef ESP8266
v=analogRead(A0);
#endif
Input = read_temp(v);
#ifdef fan_pin
if ((Input > 80) && (fan_val < 50)) setfan_val(255);
#endif
if (Setpoint > 0) {
#ifdef heater_pin
myPID.Compute();
#ifdef ESP8266
#ifdef usetmr1
/************************************************
turn the output pin on/off based on pid output
************************************************/
unsigned long now = millis();
if (now - windowStartTime > WindowSize)
{ //time to shift the Relay Window
windowStartTime += WindowSize;
}
if (Output*4 > now - windowStartTime) digitalWrite(heater_pin, HIGH);
else digitalWrite(heater_pin, LOW);
//zprintf(PSTR("OUT:%d %W:%d\n"),fi(Output),fi(now-windowStartTime));
#warning USING BANG BANG HEATER
#else
analogWrite(heater_pin, Output * 4);
#warning USING PWM HEATER
#endif
#elif defined __ARM__
analogWrite(heater_pin, Output * 2);
#else
analogWrite(heater_pin, Output * 17 / 20);
#endif
if (wait_for_temp ) {
//zprintf(PSTR("Temp:%f @%f\n"), ff(Input), ff(Output));
}
#endif
}
}
}
int temp_achieved() {
return Input >= Setpoint - 10;
// return fabs(Input - Setpoint) < 10;
}
#else
int temp_achieved() {
return 1;
}
void set_temp(float set) {
}
void init_temp()
{
}
void temp_loop(uint32_t cm)
{
}
#endif
<file_sep>/karya34m/nonlinear.h
/*
=================================================================================================================================================
DELTA PRINTER FUNCTIONS
=================================================================================================================================================
*/
#define SQRT sqrt
#ifdef USETIMER1
#define CORELOOP
#else
#define CORELOOP coreloopm();
#endif
#ifndef NONLINEAR
// LINEAR DRIVE IS SIMPLE
#define Cstepmmx(i) stepmmx[i]
// no scaling
#define XYSCALING
#else
// NONLINEAR HERE
// dummy step/mm for planner, 100 is good i think
#define FIXED2 100.f
#define IFIXED2 1.f/(FIXED2)
#define Cstepmmx(i) FIXED2
// 200 = on G0, 50 on G1 ~ 200 =2mm, 50 = 0.5mm
// Travel : print
// actually this doesnot effect the buffer, so make it as low as minimum (15step) is no problem.
// since the actual motor step maybe not 100 then the minimum is 15
#define STEPPERSEGMENT 50
extern int32_t x2[NUMAXIS];
float sgx[NUMAXIS]; // increment delta each segment
float delta_diagonal_rod;
float DELTA_DIAGONAL_ROD_2;
float delta_radius = (DELTA_RADIUS );
float delta_tower1_x;
float delta_tower1_y;
float delta_tower2_x ;
float delta_tower2_y ;
float delta_tower3_x ;
float delta_tower3_y ;
extern float F_SCALE;
// maybe we should use fixed point to increase performance, or make all already multiplied with the steppermm (steppermm as the pixed point multiplicator)
#define stepsqrt(s,n)
/* ====================================================================================================== *
DELTA
======================================================================================================
*/
#if defined(DRIVE_DELTA)
#define XYSCALING cx2*=xyscale; cy2*=xyscale;
#define NONLINEARHOME cx1 = 0; cy1 = 0; cz1 = ax_home[2];
#define SINGLESEGMENT (ishoming || ((m->dx[0] == 0) && (m->dx[1] == 0)))
// only X and Y cause segmentation
#define STEPSEGMENT fmax(labs(m->dx[0]),labs(m->dx[1]))
void nonlinearprepare() {
DELTA_DIAGONAL_ROD_2 = delta_diagonal_rod * delta_diagonal_rod;
//delta_radius = (DELTA_RADIUS );
delta_tower1_x = (COS(DegToRad(TOWER_X_ANGLE_DEG)) * delta_radius);
delta_tower1_y = (SIN(DegToRad(TOWER_X_ANGLE_DEG)) * delta_radius);
delta_tower2_x = (COS(DegToRad(TOWER_Y_ANGLE_DEG)) * delta_radius);
delta_tower2_y = (SIN(DegToRad(TOWER_Y_ANGLE_DEG)) * delta_radius);
delta_tower3_x = (COS(DegToRad(TOWER_Z_ANGLE_DEG)) * delta_radius);
delta_tower3_y = (SIN(DegToRad(TOWER_Z_ANGLE_DEG)) * delta_radius);
}
void transformdelta( float x, float y, float z, float e) {
#ifdef output_enable
//zprintf(PSTR("transform delta "));
#endif
x2[3] = stepmmx[3] * e;
if (ishoming)
{
// when homing, no transform
x2[0] = int32_t(stepmmx[0] * x);
x2[1] = int32_t(stepmmx[1] * y);
x2[2] = int32_t(stepmmx[2] * z);
} else {
#ifdef ISPC
float ex = x * graphscale;
float ey = y * graphscale;
float ez = z * graphscale;
putpixel (ex + ey * 0.3 + 250, ey * 0.3 - ez + 250, 15);
#endif
x2[0] = stepmmx[0] * (SQRT(DELTA_DIAGONAL_ROD_2
- sqr2(delta_tower1_x - x)
- sqr2(delta_tower1_y - y)
) + z);
CORELOOP
x2[1] = stepmmx[1] * (SQRT(DELTA_DIAGONAL_ROD_2
- sqr2(delta_tower2_x - x)
- sqr2(delta_tower2_y - y)
) + z);
CORELOOP
x2[2] = stepmmx[2] * (SQRT(DELTA_DIAGONAL_ROD_2
- sqr2(delta_tower3_x - x)
- sqr2(delta_tower3_y - y)
) + z);
CORELOOP
//F_SCALE=DELTA_DIAGONAL_ROD_2/(sqr2(delta_radius)+x*x+y*y);
}
#ifdef output_enable
//zprintf(PSTR(": %f %f %f -> %d %d %d\n"), ff(x), ff(y), ff(z), fi(x2[0]), fi(x2[1]), fi(x2[2]));
#endif
}
/* ====================================================================================================== *
DELTASIAN
======================================================================================================
*/
#elif defined(DRIVE_DELTASIAN)
void nonlinearprepare() {
DELTA_DIAGONAL_ROD_2 = delta_diagonal_rod * delta_diagonal_rod;
delta_tower1_x = -DELTA_RADIUS;
delta_tower2_x = +DELTA_RADIUS;
delta_radius = (DELTA_RADIUS );
}
#define NONLINEARHOME cx1 = 0; cy1 = 0; cz1 = ax_home[2];
#define SINGLESEGMENT (ishoming || (m->dx[0] == 0))
// only X cause segmentation
#define STEPSEGMENT labs(m->dx[0])
void transformdelta( float x, float y, float z, float e) {
#ifdef output_enable
zprintf(PSTR("transform delta "));
#endif
x2[3] = stepmmx[3] * e;
if (ishoming)
{
// when homing, no transform
x2[0] = int32_t(stepmmx[0] * x);
x2[1] = int32_t(stepmmx[1] * y);
x2[2] = int32_t(stepmmx[2] * z);
} else {
#ifdef ISPC
float ex = x * graphscale;
float ey = y * graphscale;
float ez = z * graphscale;
putpixel (ex + ey * 0.3 + 250, ey * 0.3 - ez + 250, 15);
#endif
x2[0] = stepmmx[0] * (sqrt(DELTA_DIAGONAL_ROD_2
- sqr2(delta_tower1_x - x)
) + z);
CORELOOP
x2[2] = stepmmx[2] * (sqrt(DELTA_DIAGONAL_ROD_2
- sqr2(delta_tower2_x - x)
) + z);
CORELOOP
x2[1] = int32_t(stepmmx[1] * y);
}
#ifdef output_enable
zprintf(PSTR(": %f %f %f -> %d %d %d\n"), ff(x), ff(y), ff(z), fi(x2[0]), fi(x2[1]), fi(x2[2]));
#endif
}
#endif
#endif // LINEAR
<file_sep>/karya34m/timer.h
#include "motion.h"
#include "config_pins.h"
#include <stdint.h>
#define TMSCALE 1024L
extern int somedelay(int32_t n);
//#define somedelay(n) delayMicroseconds(n);
extern int feedthedog();
#define TEMPTICK 500000
#define timescale 1000000L
#ifdef ISPC
extern uint32_t micros();
#else
#ifdef ESP8266 && WIFISERVER
#define usetmr1
#define TEMPTICK 100000
#endif
#endif // ISPC
#define SUBMOTION 1
#define timescaleLARGE timescale*TMSCALE
extern volatile uint32_t ndelay,ndelay2;
extern uint32_t next_step_time;
extern void timer_init();
extern void timer_set(int32_t delay);
extern void timer_set2(int32_t delay,int32_t delayL);
extern void servo_loop();
extern void servo_init();
extern void servo_set(int us);
#ifndef MASK
/// MASKING- returns \f$2^PIN\f$
#define MASK(PIN) (1 << PIN)
#endif
#ifdef USETIMER1
#ifdef __AVR__
#define MEMORY_BARRIER() __asm volatile( "" ::: "memory" );
#define CLI cli();
#define SEI sei();
#define ATOMIC_START { \
uint8_t save_reg = SREG; \
cli(); \
MEMORY_BARRIER();
#define ATOMIC_END MEMORY_BARRIER(); \
SREG = save_reg; \
}
#endif
#endif
#ifndef CLI
#define CLI
#define SEI
#define MEMORY_BARRIER()
#define ATOMIC_START
#define ATOMIC_END
#endif
<file_sep>/karya34m/motion.h
#ifndef MOTION_H
#define MOTION_H
#ifdef ARDUINO
#include<arduino.h>
#endif
#if defined(__STM32F1__) || defined(STM32_SERIES_F1)
#define __ARM__
#endif
#ifdef ESP32
#define ESP8266
#endif
#if defined(__AVR__) || defined(ESP8266)|| defined(ESP32) || defined (__ARM__)
#else
//#warning This is PC
#define ISPC
#define PROGMEM
#endif
#include<math.h>
#include<stdint.h>
#include "config_pins.h"
#define NUMAXIS 4
#ifdef __AVR__
#define LOWESTDELAY 540 // IF LESS than this microsec then do the subpixel
#else
#define LOWESTDELAY 120 // IF LESS than this microsec then do the subpixel
#endif
typedef struct {
uint8_t cmd ; // 1 bit CMD 0:setdir 1:step 4bit parameter for dir/step, 11 bits for delay , delay*10 0-20480, si min speed is 0.5mm/s for 100step/mm motor
uint16_t dly ; // 1 bit CMD 0:setdir 1:step 4bit parameter for dir/step, 11 bits for delay , delay*10 0-20480, si min speed is 0.5mm/s for 100step/mm motor
} tcmd;
typedef struct {
int8_t status ; // status in bit 01 , planstatus in bit 2 , g0 in bit 4, 4 bit left better use it for fast axis
int laserval;
float dis; // max start speed, maxcorner
#ifdef __AVR__
int16_t ac; // needed for backplanner
uint16_t fs, fn,maxs; // all are in square ! needed to calc real accell
#else
float ac; // needed for backplanner
float fs, fn,maxs; // all are in square ! needed to calc real accell
#endif
//#ifdef NONLINEAR
//float otx[3]; // keep the original coordinate before transform
float dtx[NUMAXIS]; // keep the original coordinate before transform
//#endif
int32_t dx[NUMAXIS]; //original delta before transform
#ifdef ISPC
// for graphics
int col;
#endif
} tmove;
extern float e_multiplier, f_multiplier;
#ifdef ISPC
extern float tick, tickscale, fscale, graphscale;
#endif
extern int32_t mcx[NUMAXIS];
extern tmove *m;
//extern int32_t px[4];
extern int xback[4];
extern uint8_t homingspeed;
extern uint8_t homeoffset[4];
extern int xyjerk, accel;
extern int mvaccel;
extern int maxf[4];
extern int32_t dlp, dl;
extern float stepmmx[4], xyscale;
extern tmove move[NUMBUFFER];
extern float cx1, cy1, cz1, ce01;
extern uint8_t head, tail;
extern int8_t checkendstop;
extern int16_t endstopstatus;
extern float ax_home[NUMAXIS];
//extern int8_t lsx[4];
extern int8_t sx[NUMAXIS];
extern uint32_t cmctr;
extern int8_t RUNNING;
extern int8_t PAUSE;
extern int constantlaserVal;
#define nextbuff(x) ((x) < NUMBUFFER-1 ? (x) + 1 : 0)
#define prevbuff(x) ((x) > 0 ? (x) - 1 : NUMBUFFER-1)
#define degtorad(x) x*22/(7*180);
extern void power_off();
extern int32_t motionrunning;
extern int32_t mctr;
extern int motionloop();
extern int laserOn;
extern void init_pos();
extern int coreloop();
extern void coreloopm();
extern void otherloop(int r);
extern void waitbufferempty();
extern void needbuffer();
extern int32_t startmove();
extern void initmotion();
extern void addmove(float cf, float cx2, float cy2, float cz2, float ce02, int g0 = 1, int rel = 0);
extern void draw_arc(float cf, float cx2, float cy2, float cz2, float ce02, float fI, float fJ, uint8_t isclockwise);
extern float axisofs[4];
#ifdef NONLINEAR
extern float delta_diagonal_rod;
extern float DELTA_DIAGONAL_ROD_2;
extern float delta_radius;
// Compile-time trigonometric functions. See Taylor series.
// Converts degrees to radians.
#define DegToRad(angleDegrees) ((angleDegrees) * M_PI / 180.0)
//Make an angle (in radian) coterminal (0 >= x > 2pi).
//#define COTERMINAL(x) (fmod((x), M_PI*2)) //This causes error since fmod() implementation is different from i386 compiler.
//TODO: Solve coterminality
#define COTERMINAL(x) (x)
// Get quadrant of an angle in radian.
#define QUADRANT(x) ((uint8_t)((COTERMINAL((x))) / M_PI_2) + 1)
//Calculate sine of an angle in radians.
//Formula will be adjusted accordingly to the angle's quadrant.
//Don't worry about pow() function here as it will be optimized by the compiler.
#define SIN0(x) (x)
#define SIN1(x) (SIN0(x) - (pow ((x), 3) / 6))
#define SIN2(x) (SIN1(x) + (pow ((x), 5) / 120))
#define SIN3(x) (SIN2(x) - (pow ((x), 7) / 5040))
#define SIN4(x) (SIN3(x) + (pow ((x), 9) / 362880))
//*
#define SIN(x) (QUADRANT((x)) == 1 ? (SIN4(COTERMINAL((x)))) : \
(QUADRANT((x)) == 2 ? (SIN4(M_PI - COTERMINAL((x)))) : \
(QUADRANT((x)) == 3 ? -(SIN4(COTERMINAL((x)) - M_PI)) : \
-(SIN4(M_PI*2 - COTERMINAL((x)))))))
// */
//#define SIN(x) (SIN4(x))
//Calculate cosine of an angle in radians.
//Formula will be adjusted accordingly to the angle's quadrant.
//Don't worry about pow() function here as it will be optimized by the compiler.
#define COS0(x) 1
#define COS1(x) (COS0(x) - (pow ((x), 2) / 2))
#define COS2(x) (COS1(x) + (pow ((x), 4) / 24))
#define COS3(x) (COS2(x) - (pow ((x), 6) / 720))
#define COS4(x) (COS3(x) + (pow ((x), 8) / 40320))
//*
#define COS(x) (QUADRANT((x)) == 1 ? (COS4(COTERMINAL((x)))) : \
(QUADRANT((x)) == 2 ? -(COS4(M_PI - COTERMINAL((x)))) : \
(QUADRANT((x)) == 3 ? -(COS4(COTERMINAL((x)) - M_PI)) : \
(COS4(M_PI*2 - COTERMINAL((x)))))))
// */
//#define COS(x) COS4((x))
//Must scale by 16 because 2^32 = 4,294,967,296 - giving a maximum squareroot of 65536
//If scaled by 8, maximum movement is 65,536 * 8 = 524,288um, 65,536 * 16 = 1,048,576um
#endif
#define amove addmove
extern void homing();
extern int32_t bufflen();
void docheckendstop();
extern void reset_motion();
extern void preparecalc();
extern tmove* m;
#define fmax(a,b) a<b?b:a
#define fmin(a,b) a>b?b:a
#define domotionloop motionloop();
#endif
<file_sep>/karya34m/data/serial.js
//console.log("App Running");
var wsconnected=0;
var lastw="";
var oktosend=1;
var connectionId = null;
var eline=0;
var okwait=0;
var running=0;
var px=0;var py=0;var pz=0;var pe=0;
function comconnect(){
var bt=document.getElementById('btconnect');
if (bt.innerHTML=="Connect"){
connect(document.getElementById('comport').value);
bt.innerHTML='Disconnect';
} else {
disconnect();
bt.innerHTML='Connect';
}
}
function testlaser(){
sendgcode("M3 S255 P100");
sendgcode("M3 S0");
}
function gcodemove(x,y,z){
var mm=document.getElementById('move').value;
px=px+x*mm;
py=py+y*mm;
pz=pz+z;
sendgcode("G0 F5000 X"+(px)+" Y"+(py)+" Z"+(pz));
}
function gcoderight(){gcodemove(-1,0,0);}
function gcodeleft(){gcodemove(1,0,0);}
function gcodeup(){gcodemove(0,1,0);}
function gcodedown(){gcodemove(0,-1,0);}
function gcodezup(){gcodemove(0,0,1);}
function gcodezdown(){gcodemove(0,0,-1);}
function homing(){
sendgcode("G28");
px=0;
py=0;
pz=0;
pe=0;
}
function setashome2(){
sendgcode("G92 X0 Y0 Z0 E0");
px=0;
py=0;
pz=0;
pe=0;
}
function setashome3(){
sendgcode("G92 X0 Y0 Z2 E0");
px=0;
py=0;
pz=2;
pe=0;
}
function setashome(){
sendgcode("G0 Z0");
setashome2();
}
function hardstop(){
sendgcode("M2");
sendgcode("G0 Z2 F5000");
sendgcode("G0 X0 Y0");
stopit();
}
var comtype=1; // 0 serial, 1 websocket
var egcodes=[];
var debugs=0;
function sendgcode(g){
if (debugs&1)console.log(g);
if (comtype==0){
try {
writeSerial(g+"\n");
} catch (e) {
}
}
if (comtype==1){
ws.send(g+"\n");
}
}
function nextgcode(){
if (comtype==1 && !wsconnected){
//setTimeout(nextgcode,1000); !!!! if crash wait to autoreboot LOL
return;
}; // wait until socket connected
if (okwait) return;
if (!running)return;
while(eline<egcodes.length){
var g=egcodes[eline];
eline++;
if ((g) && (g[0]!=';')) {
setTimeout(sendgcode(g.split(";")[0]),(eline+1)*150);
//sendgcode(g.split(";")[0]);
okwait=1;
return;
}
}
stopit();
}
function stopit(){
var bt=document.getElementById('btexecute');
bt.innerHTML="Execute";
running=0;
okwait=0;
egcodes=[];
}
function execute(gcodes){
egcodes=gcodes.split("\n");
eline=0;
running=egcodes.length;
okwait=0;
nextgcode();
sendgcode("M105");
}
function executegcodes(){
var bt=document.getElementById('btexecute');
if (bt.innerHTML=="Execute") {
execute (document.getElementById('gcode').value);
bt.innerHTML="Stop";
} else {
stopit();
sendgcode("M2");
}
}
function executepgcodes(){execute(document.getElementById('pgcode').value);pz=2;}
function executeicodes(){execute(document.getElementById('icode').value);}
function pause(){
var bt=document.getElementById('btpause');
if (bt.innerHTML=="PAUSE") {
running=0;
sendgcode("M3 S200 P10");
bt.innerHTML="RESUME";
} else {
running=1;
sendgcode("M3 S200");
nextgcode();
bt.innerHTML="PAUSE";
}
}
var ss="";
var eeprom={};
var ineeprom=0;var eppos=0;
var onReadCallback = function(s){
for (var i=0;i<s.length;i++){
if (s[i]=="\n"){
if (debugs&2)console.log(ss);
ss="";
} else ss+=s[i];
if ((s[i]=="\n") || (s[i]==" ")){
if (ineeprom>0){
if (ineeprom==3)eppos=lastw;
if (ineeprom==2)eeprom[eppos]=lastw;
if (ineeprom==1){
var sel=document.getElementById("eepromid");
sel.innerHTML+="<option value=\""+eeprom[eppos]+":"+eppos+"\">"+lastw+"</option>";
}
ineeprom--;
}
if (lastw.toUpperCase().indexOf("EPR:")>=0){
ineeprom=3;
}
if (lastw.toUpperCase().indexOf("T:")>=0){
document.getElementById("info3d").innerHTML=lastw;
}
if (lastw.toUpperCase().indexOf("OK")>=0){
okwait=0;
nextgcode();
}
lastw="";
} else lastw=lastw+s[i];
}
}
var listPorts = function() {
chrome.serial.getDevices(onGotDevices);
};
var onGotDevices = function(ports) {
var s="";
for (var i=0; i<ports.length; i++) {
if (ports[i].path)s=s+"<option value="+ports[i].path+">"+ports[i].path+"</option>";
}
document.getElementById("comport").innerHTML=s;
};
var connect = function(path) {
var options = {bitrate: 115200};
chrome.serial.connect(path, options, onConnect)
};
var onConnect = function(connectionInfo) {
//console.log(connectionInfo);
connectionId = connectionInfo.connectionId;
};
var disconnect = function() {
chrome.serial.disconnect(connectionId, onDisconnect);
};
var onDisconnect = function(result) {
if (result) {
//console.log("Disconnected from the serial port");
} else {
//console.log("Disconnect failed");
}
};
//var setOnReadCallback = function(callback) {
// onReadCallback = callback;
// chrome.serial.onReceive.addListener(onReceiveCallback);
//};
var onReceiveCallback = function(info) {
if (info.connectionId == connectionId && info.data) {
var str = convertArrayBufferToString(info.data);
//console.log(str);
if (onReadCallback != null) {
onReadCallback(str);
}
}
};
var onSend = function(sendInfo) {
//console.log(sendInfo);
}
var writeSerial = function(str) {
chrome.serial.send(connectionId, convertStringToArrayBuffer(str), onSend);
}
// Convert ArrayBuffer to string
var convertArrayBufferToString = function (buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
// Convert string to ArrayBuffer
var convertStringToArrayBuffer = function(str) {
var buf=new ArrayBuffer(str.length);
var bufView=new Uint8Array(buf);
for (var i=0; i<str.length; i++) {
bufView[i]=str.charCodeAt(i);
}
return buf;
}
function changematerial(){
val=getvalue("material");
val=val.split(",");
setvalue("feed",val[0]);
setvalue("repeat",val[1]);
harga=val[2];
if (val.length==4){
document.getElementById("cmode").value=3;
setvalue("zdown",val[3]);
setvalue("tabc",2);
}
if (val.length==3){
document.getElementById("cmode").value=1;
setvalue("zdown",0);
setvalue("tabc",0);
}
}
function modechange(){
val=getvalue("cmode");
if (val==1) {
setvalue("pup","M3 S0");
setvalue("pdn","M3 S255");
}
if (val==2) {
setvalue("pup","M3 S0");
setvalue("pdn","M3 S255");
}
if (val==3) {
setvalue("pup","G0 Z2 F1000");
setvalue("pdn","G0 Z=cncz F60");
setvalue("feed","3");
}
}
//onclick="setashome();"
function initserial(){
try {
chrome.serial.onReceive.removeListener(onReceiveCallback);
chrome.serial.onReceive.addListener(onReceiveCallback);
listPorts();
comtype=0;
} catch (e) {
comtype=-1;
}
}
setclick("btinitser",initserial);
setclick("btconnect",comconnect);
setclick("btsethome",setashome);
setclick("btsethome2",setashome2);
setclick("btsethome3",setashome3);
setclick("bthoming",homing);
setclick("bthardstop",hardstop);
setclick("btinit",executeicodes);
setclick("btpreview",executepgcodes);
setclick("btexecute",executegcodes);
setclick("btpause",pause);
setclick("bthit",testlaser);
setclick("btleft",gcodeleft);
setclick("btup",gcodeup);
setclick("btdn",gcodedown);
setclick("btright",gcoderight);
setclick("btzup",gcodezup);
setclick("btzdn",gcodezdown);
setclick("btrecode",refreshgcode);
setclick("btsend",function(){sendgcode(getvalue("edgcode"));})
setclick("btmotoroff",function(){sendgcode("M84");})
setevent("change","btfile",openFile);
setevent("change","cmode",modechange);
setevent("change","material",changematerial);
// 3d printer
setclick("bt3home",function(){sendgcode("g28");pe=0});
setclick("bt3pla",function(){sendgcode("m104 s180");});
setclick("bt3t0",function(){sendgcode("m104 s0");});
setclick("bt3read",function(){sendgcode("m105");});
setclick("bt3limit",function(){sendgcode("m119");});
setclick("bt3eeprom",function(){
document.getElementById("eepromid").innerHTML="";
sendgcode("m205");
});
setclick("bt3seteeprom",function(){
sendgcode("M206 P"+eppos+" S"+getvalue("eepromval"));
});
setclick("bt3Eup",function(){pe-=1*getvalue("extmm");sendgcode("g0 E"+pe);});
setclick("bt3Edn",function(){pe+=1*getvalue("extmm");sendgcode("g0 E"+pe);});
setevent("change","eepromid",function (){var v=getvalue("eepromid").split(":");setvalue("eepromval",v[0]);eppos=v[1];});
// gcode editor
setclick("btcopy1",function(){copy_to_clipboard('gcode');});
setclick("btcopy2",function(){copy_to_clipboard('pgcode');});
setclick("tracingbt",function(){
tr=document.getElementById('tracing');
tb=document.getElementById('tracingbt');
if (tb.innerHTML=="GCODE SENDER"){
tb.innerHTML="TRACING IMAGE";
tr.hidden=true;
} else {
tb.innerHTML="GCODE SENDER";
tr.hidden=false;
}
});
var stotype=0;
try {
storage=chrome.storage.local;
} catch(e){
stotype=1;
storage=localStorage;
}
function savesetting(){
a=document.getElementsByClassName("saveit");
sett={};
for (var i=0;i<a.length;i++){
sett[a[i].id]=a[i].value;
}
if (stotype==1){
storage.setItem("settings",JSON.stringify(sett));
storage.setItem("text1",text1);
} else {
storage.set({"settings":sett,"text1":text1});
}
}
setclick("btsaveset",savesetting);
if (stotype==0){
try {
storage.get("text1",function(r){text1=r.text1;})
storage.get("settings",function(r){
sett=r.settings;
for (var k in sett){
setvalue(k,sett[k]);
}
refreshgcode();
});
} catch (e) {
}
} else {
text1=storage.text1;
if (text1==undefined)text1="";
if (storage.settings!=undefined){
sett=JSON.parse(storage.settings);
for (var k in sett){
setvalue(k,sett[k]);
}
}
if (text1)refreshgcode();
}
// websocket
function connectwebsock(){
if (window.location.host){
var lastcomtype=comtype;
comtype=1;
function handlemessage(m){
msg=m.data;
onReadCallback(msg);
if (debugs&2)console.log(msg);
}
ws=new WebSocket('ws://'+window.location.host+':81/', ['arduino']);
ws.onerror=function(e){comtype=lastcomtype;} // back to serial if error.
ws.onmessage=handlemessage;
ws.onopen = function(e) {
console.log('Ws Connected!');
a=document.getElementById("status");
a.innerHTML="Web socket:Connected";
wsconnected=1;
nextgcode();
};
ws.onclose = function(e) {
console.log('ws Disconnected!');
a=document.getElementById("status");
a.innerHTML="Web socket:disconnected<button onclick='connectwebsock()'>Reconnect</button>";
wsconnected=0;
};
}
}
window.onload=function(){
a=document.activeElement;
if ((a.tagName=="DIV") && (stotype==1))a.remove();
connectwebsock();
};
<file_sep>/karya34m/serial_avr.h
/** \file
\brief Serial subsystem, AVR specific part.
To be included from serial.c, for details see there.
*/
#if defined CORESERIAL
#include <avr/interrupt.h>
#include "arduino.h"
#include "stdint.h"
#define ASCII_XOFF 19
#define ASCII_XON 17
volatile uint8_t rxhead = 0;
volatile uint8_t rxtail = 0;
volatile uint8_t rxbuf[BUFSIZE];
volatile uint8_t txhead = 0;
volatile uint8_t txtail = 0;
volatile uint8_t txbuf[BUFSIZE];
#ifdef XONXOFF
#define FLOWFLAG_STATE_XOFF 0
#define FLOWFLAG_SEND_XON 1
#define FLOWFLAG_SEND_XOFF 2
#define FLOWFLAG_STATE_XON 4
// initially, send an XON
volatile uint8_t flowflags = FLOWFLAG_SEND_XON;
#endif
/** Initialise serial subsystem.
Set up baud generator and interrupts, clear buffers.
*/
#define xBAUD 115200
void serial_init(float BAUD) {
#define F_CPU 16000000L
if (BAUD > 38401){
UCSR0A = MASK(U2X0);
UBRR0 = (((F_CPU / 8) / BAUD) - 0.5);
}else{
UCSR0A = 0;
UBRR0 = (((F_CPU / 16) /BAUD) - 0.5);
}
UCSR0B = MASK(RXEN0) | MASK(TXEN0);
UCSR0C = MASK(UCSZ01) | MASK(UCSZ00);
UCSR0B |= MASK(RXCIE0) | MASK(UDRIE0);
}
/** Receive interrupt.
We have received a character, stuff it in the RX buffer if we can, or drop
it if we can't. Using the pragma inside the function is incompatible with
Arduinos' gcc.
*/
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#ifdef USART_RX_vect
ISR(USART_RX_vect)
#else
ISR(USART0_RX_vect)
#endif
{
if (buf_canwrite(rx))
buf_push(rx, UDR0);
else {
// Not reading the character makes the interrupt logic to swamp us with
// retries, so better read it and throw it away.
//#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
uint8_t trash;
//#pragma GCC diagnostic pop
trash = UDR0;
}
#ifdef XONXOFF
if (flowflags & FLOWFLAG_STATE_XON && buf_canwrite(rx) <= 16) {
// The buffer has only 16 free characters left, so send an XOFF.
// More characters might come in until the XOFF takes effect.
flowflags = FLOWFLAG_SEND_XOFF | FLOWFLAG_STATE_XON;
// Enable TX interrupt so we can send this character.
UCSR0B |= MASK(UDRIE0);
}
#endif
}
#pragma GCC diagnostic pop
/** Transmit buffer ready interrupt.
Provide the next character to transmit if we can, otherwise disable this
interrupt.
*/
#ifdef USART_UDRE_vect
ISR(USART_UDRE_vect)
#else
ISR(USART0_UDRE_vect)
#endif
{
#ifdef XONXOFF
if (flowflags & FLOWFLAG_SEND_XON) {
UDR0 = ASCII_XON;
flowflags = FLOWFLAG_STATE_XON;
}
else if (flowflags & FLOWFLAG_SEND_XOFF) {
UDR0 = ASCII_XOFF;
flowflags = FLOWFLAG_STATE_XOFF;
}
else
#endif
if (buf_canread(tx))
buf_pop(tx, UDR0);
else
UCSR0B &= ~MASK(UDRIE0);
}
/** Check how many characters can be read.
*/
uint8_t serial_rxchars() {
return buf_canread(rx);
}
/** Read one character.
*/
uint8_t serial_available(){
return (buf_canread(rx));
}
uint8_t serial_popchar() {
uint8_t c = 0;
// It's imperative that we check, because if the buffer is empty and we
// pop, we'll go through the whole buffer again.
if (buf_canread(rx))
buf_pop(rx, c);
#ifdef XONXOFF
if ((flowflags & FLOWFLAG_STATE_XON) == 0 && buf_canread(rx) <= 16) {
// The buffer has (BUFSIZE - 16) free characters again, so send an XON.
flowflags = FLOWFLAG_SEND_XON;
UCSR0B |= MASK(UDRIE0);
}
#endif
return c;
}
/** Send one character.
*/
void serial_writechar(uint8_t data) {
// Check if interrupts are enabled.
if (SREG & MASK(SREG_I)) {
// If they are, we should be ok to block since the tx buffer is emptied
// from an interrupt.
for ( ; buf_canwrite(tx) == 0; ) ;
buf_push(tx, data);
}
else {
// Interrupts are disabled -- maybe we're in one?
// Anyway, instead of blocking, only write if we have room.
if (buf_canwrite(tx))
buf_push(tx, data);
}
// Enable TX interrupt so we can send this character.
UCSR0B |= MASK(UDRIE0);
}
#endif /* defined TEACUP_C_INCLUDE && defined __AVR__ */
<file_sep>/karya34m/common.cpp
#include "common.h"
#include "motion.h"
#include "timer.h"
#ifndef ISPC
// functions for sending decimal
#include<arduino.h>
#include <stdarg.h>
#ifdef CORESERIAL
#include "serial_avr.h"
#endif
#define write_uint8(v, w) write_uint32(v, w)
#define write_int8(v, w) write_int32(v, w)
#define write_uint16(v, w) write_uint32(v, w)
#define write_int16(v, w) write_int32(v, w)
// send one character
/// list of powers of ten, used for dividing down decimal numbers for sending, and also for our crude floating point algorithm
//const uint32_t powers[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
/** write decimal digits from a long unsigned int
\param v number to send
*/
void write_uint32(void (*writechar)(uint8_t),uint32_t v) {
uint8_t e, t;
for (e = DECFLOAT_EXP_MAX; e > 0; e--) {
if (v >= POWERS(e))
break;
}
do
{
for (t = 0; v >= POWERS(e); v -= POWERS(e), t++);
writechar(t + '0');
}
while (e--);
}
/** write decimal digits from a long signed int
\param v number to send
*/
void write_int32(void (*writechar)(uint8_t),int32_t v) {
if (v < 0) {
writechar('-');
v = -v;
}
write_uint32(writechar,v);
}
/** write decimal digits from a long signed int
\param v number to send
*/
void write_char(void (*writechar)(uint8_t),char* v) {
for (int i=0;i<strlen(v);i++){
writechar(v[i]);
}
}
/** write decimal digits from a long unsigned int
\param v number to send
\param fp number of decimal places to the right of the decimal point
*/
void write_uint32_vf(void (*writechar)(uint8_t),uint32_t v, uint8_t fp) {
uint8_t e, t;
for (e = DECFLOAT_EXP_MAX; e > 0; e--) {
if (v >= POWERS(e))
break;
}
if (e < fp)
e = fp;
do
{
for (t = 0; v >= POWERS(e); v -= POWERS(e), t++);
writechar(t + '0');
if (e == fp)
writechar('.');
}
while (e--);
}
/** write decimal digits from a long signed int
\param v number to send
\param fp number of decimal places to the right of the decimal point
*/
void write_int32_vf(void (*writechar)(uint8_t),int32_t v, uint8_t fp) {
if (v < 0) {
writechar('-');
v = -v;
}
write_uint32_vf(writechar,v, fp);
}
#if __SIZEOF_INT__ == 2
#define GET_ARG(T) (va_arg(args, T))
#elif __SIZEOF_INT__ >= 4
#define GET_ARG(T) (va_arg(args, T))
#else
#define GET_ARG(T) (va_arg(args, T))
#endif
void sendf_P(void (*writechar)(uint8_t),PGM_P format_P, ...) {
va_list args;
va_start(args, format_P);
uint16_t i = 0;
uint8_t c = 1, j = 0;
while ((c = pgm_read_byte(&format_P[i++]))) {
if (j) {
switch (c) {
case 'd':
write_int32(writechar,GET_ARG(int32_t));
j = 0;
break;
case 'f':
case 'q':
write_int32_vf(writechar,(int32_t)GET_ARG(uint32_t), 3);
j = 0;
break;
case 's':
write_char(writechar,(char*)GET_ARG(char*));
j = 0;
break;
default:
writechar(c);
j = 0;
break;
}
}
else {
if (c == '%') {
j = 4;
}
else {
writechar(c);
}
}
}
va_end(args);
}
#endif
<file_sep>/karya34m/main.cpp
#include "motion.h"
#include "timer.h"
#include "common.h"
#include<stdint.h>
#ifdef ISPC
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include "gcode.h"
void demo();
void demofile();
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int x, y;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
zprintf(PSTR("Graphics error: %s\n"), grapherrormsg(errorcode));
zprintf(PSTR("Press any key to halt:"));
getch();
exit(1); /* terminate with an error code */
}
zprintf(PSTR("Simple Motion Control with Acceleration, and lookahead planner\n"));
zprintf(PSTR("By <EMAIL>\n"));
initmotion();
struct palettetype pal;
//getpalette(&pal);
for (int i = 0; i < 256; i++) {
//setrgbpalette(i,i,i,i);
}
setcolor(1);
graphscale = 25;
line(0, 400, 600, 400);
line(0, 400 - 50 * fscale, 600, 400 - 50 * fscale);
line(0, 400 - 100 * fscale, 600, 400 - 100 * fscale);
//int8_t z=100;
float v = 10.1234;
zprintf (PSTR("F %f D %d\n"), ff(v), (int32_t)200);
// demofile();
demo();
zprintf (PSTR("WAIT\n"));
waitbufferempty();
zprintf (PSTR("Time:%f\n"), ff(tick / timescale));
getch();
}
void demofile() {
//#define fn "d:/git/hipopotamo.gcode"
//#define fn "d:/3d/5050.gcode"
//#define fn "d:/3d/font.gcode"
//#define fn "d:/git/bowdenlock.gcode"
//#define fn "d:/3d/fish_fossilz.gcode"
//#define fn "d:/3d/cube20.gcode"
//#define fn "d:/3d/bowdenlock.gcode"
//#define fn "d:/3d/gecko.gcode"
//#define fn "d:/3d/foam.gcode"
//#define fn "gcode/gecko.gcode"
#define fn "gcode/fish_fossilz.gcode"
//#define fn "d:/3d/box1cm.gcode"
FILE *file = fopen(fn, "r");
char code[100];
size_t n = 0;
int c;
graphscale = 5;
tickscale = 50;
fscale=20;
if (file == NULL) return; //could not open file
int comment = 0;
long l = 0;
while ((c = fgetc(file)) != EOF) {
//if (l > 35)break;
if (c == ';')comment = 1;
code[n++] = (char) c;
if (c == '\n') {
code[n++] = 0;
l++;
printf("\n%s", code);
if ((l > 1) && !comment)gcode_parse_char(c);
n = 0;
comment = 0;
//getch();
} else
{
if ((l > 1) && !comment)gcode_parse_char(c);
}
}
}
void demo() {
graphscale = 5;
tickscale = 30;
fscale = 30;
int f = 100;
/*
for(int x=1;x<36;x++){
amove(20, sin(x/5.7)*10, cos(x/5.7)*10, 0, 0);
}
for(int x=1;x<36;x++){
amove(20, -50+sin(x/5.7)*10, cos(x/5.7)*10, 0, 0);
}
*/
// amove(50, 10, 0, 0, 1);
// amove(50, 10, 0, 0, 2);
// amove(50, 30, 0, 0, 3);
// amove(80, 30, 0, 0, 0);
// amove(80, 30, 30, 0, 0);
// amove(80, 30, 50, 0, 0);
//amove(40, 50, 20, 0, 0);
//amove(40, 60, 10, 0, 0);
/*
amove(30, 10, -10, 0, 0);
amove(30, 25, 0, 0, 1);
amove(30, 25, 0, 1, 2);
amove(30, 30, 0, 1, 3);
amove(30, 40, -10, 1, 3);
amove(30, 30, 0, 0, 4);
amove(30, 80, 0, 0, 5);
/*
amove(f, 43, 0, 0, 3);
amove(f, 54, 0, 0, 4);
amove(f, 65, 0, 0, 5);
amove(f, 77, 0, 0, 6);
amove(f, 100, 0, 0, 0);
amove(f, 110, 0, 0, 0);
amove(f, 50, 0, 0, 0);
amove(f, 53, 0, 0, 0);
amove(50, 70, 0, 0, 0);
amove(f, 80, 0, 0, 0);
amove(f, 90, 0, 0, 0);
*/
int i;
/*
for (i = 0; i < 5; i++) {
addmove(f, i * 10, 50, 0, 0);
}
addmove(f, 60, 55, 0, 0);
for (i = 5; i > 0; i--) {
addmove(f, i * 10, 60, 0, 0);
}
addmove(f, 0, 65, 0, 0);
for (i = 0; i < 36; i++) {
addmove(f, sin(i * 44.0 / 7 / 36) * 140, -cos(i * 44.0 / 7 / 36) * 40, 0, 1);
}
*/
}
#endif
<file_sep>/karya34m/gcode.cpp
#include "gcode.h"
#include "common.h"
#include "motion.h"
#include "config_pins.h"
#include "timer.h"
#include "temp.h"
#include "motors.h"
#include "eprom.h"
int32_t linecount, lineprocess;
#ifdef USETIMER1
#define MLOOP
#else
#define MLOOP coreloopm();
#endif
#include<stdint.h>
#ifndef ISPC
#include<arduino.h>
#endif
#include "eprom.h"
/// crude crc macro
#define crc(a, b) (a ^ b)
decfloat read_digit;
int sdcardok = 0;
int waitforline = 0;
char g_str[40];
int g_str_c = 0;
GCODE_COMMAND next_target;
uint16_t last_field = 0;
/// list of powers of ten, used for dividing down decimal numbers for sending, and also for our crude floating point algorithm
static float decfloat_to_float(void)
{
float r = read_digit.mantissa;
uint8_t e = read_digit.exponent;
/* uint32_t powers=1;
for (e=1; e<read_digit.exponent;e++) powers*=10;
// e=1 means we've seen a decimal point but no digits after it, and e=2 means we've seen a decimal point with one digit so it's too high by one if not zero
*/
if (e) r = (r /*+ powers[e-1] / 2*/) / POWERS(e - 1);
// if (e) r = (r /*+ powers[e-1] / 2*/) * POWERS(e - 1);
MLOOP
return read_digit.sign ? -r : r;
}
void pausemachine()
{
PAUSE = !PAUSE;
if (PAUSE)zprintf(PSTR("Pause\n"));
else zprintf(PSTR("Resume\n"));
}
void changefilament(float l)
{
#ifdef CHANGEFILAMENT
waitbufferempty();
float backupE = ce01;
float backupX = cx1;
float backupY = cy1;
float backupZ = cz1;
addmove(50, 0, 0, 0, -2, 0, 1); // retract
addmove(50, 0, 0, 30, 0, 0, 1); // move up
addmove(50, 0, 0, 0, -l, 0, 1); // unload filament
waitbufferempty();
checkendstop = 1;
//zprintf(PSTR("change filemant, then push endstop\n"));
while (1) {
docheckendstop();
if (endstopstatus < 0) break;
domotionloop
}
checkendstop = 0;
addmove(5, 0, 0, 0, l + 10, 0, 1); // load filament
addmove(50, 0, 0, -30, 0, 0, 1);
waitbufferempty();
ce01 = backupE;
cx1 = backupX;
cy1 = backupY;
cz1 = backupZ;
#endif
}
uint8_t gcode_parse_char(uint8_t c)
{
uint8_t checksum_char = c;
//Serial.write(c);
// uppercase
if (c >= 'a' && c <= 'z' && !next_target.read_string)
c &= ~32;
// An asterisk is a quasi-EOL and always ends all fields.
if (c == '*') {
//next_target.read_string = 0;
}
// Skip comments and strings.
if (
next_target.read_string == 0
) {
// Check if the field has ended. Either by a new field, space or EOL.
if (last_field && (c < '0' || c > '9') && c != '.') {
switch (last_field) {
case 'G':
next_target.G = read_digit.mantissa;
break;
case 'M':
next_target.M = read_digit.mantissa;
if (next_target.M == 117) next_target.read_string = 1;
break;
case 'X':
next_target.target.axis[X] = decfloat_to_float();
break;
case 'Y':
next_target.target.axis[Y] = decfloat_to_float();
break;
case 'Z':
next_target.target.axis[Z] = decfloat_to_float();
break;
#ifdef ARC_SUPPORT
case 'I':
next_target.I = decfloat_to_float();
break;
case 'J':
next_target.J = decfloat_to_float();
break;
case 'R':
next_target.R = decfloat_to_float();
break;
#endif
case 'E':
next_target.target.axis[E] = decfloat_to_float();
break;
case 'F':
// just use raw integer, we need move distance and n_steps to convert it to a useful value, so wait until we have those to convert it
next_target.target.F = decfloat_to_float() / 60;
MLOOP
break;
case 'S':
next_target.S = decfloat_to_float();
break;
case 'P':
next_target.P = decfloat_to_float();
break;
case '*':
//next_target.checksum_read = decfloat_to_float();
break;
case 'T':
//next_target.T = read_digit.mantissa;
break;
case 'N':
//next_target.N = decfloat_to_float();
break;
}
}
// new field?
if ((c >= 'A' && c <= 'Z') || c == '*') {
last_field = c;
read_digit.sign = read_digit.mantissa = read_digit.exponent = 0;
}
// process character
// Can't do ranges in switch..case, so process actual digits here.
// Do it early, as there are many more digits than characters expected.
if (c >= '0' && c <= '9') {
if (read_digit.exponent < DECFLOAT_EXP_MAX + 1) {
// this is simply mantissa = (mantissa * 10) + atoi(c) in different clothes
read_digit.mantissa = (read_digit.mantissa << 3) +
(read_digit.mantissa << 1) + (c - '0');
if (read_digit.exponent)
read_digit.exponent++;
}
} else {
switch (c) {
// Each currently known command is either G or M, so preserve
// previous G/M unless a new one has appeared.
// FIXME: same for T command
case 'G':
next_target.seen_G = 1;
//next_target.seen_M = 0;
//next_target.M = 0;
break;
case 'M':
next_target.seen_M = 1;
//next_target.seen_G = 0;
//next_target.G = 0;
break;
#ifdef ARC_SUPPORT
case 'I':
next_target.seen_I = 1;
break;
case 'J':
next_target.seen_J = 1;
break;
case 'R':
next_target.seen_R = 1;
break;
#endif
case 'X':
next_target.seen_X = 1;
break;
case 'Y':
next_target.seen_Y = 1;
break;
case 'Z':
next_target.seen_Z = 1;
break;
case 'E':
next_target.seen_E = 1;
break;
case 'F':
next_target.seen_F = 1;
break;
case 'S':
next_target.seen_S = 1;
break;
case 'P':
next_target.seen_P = 1;
break;
case 'T':
next_target.seen_T = 1;
break;
case 'N':
//next_target.seen_N = 1;
break;
case '*':
//next_target.seen_checksum = 0;//1;
break;
// comments
case '[':
next_target.read_string = 1; // Reset by ')' or EOL.
g_str_c = 0;
break;
case ';':
next_target.read_string = 1; // Reset by EOL.
break;
// now for some numeracy
case '-':
read_digit.sign = 1;
// force sign to be at start of number, so 1-2 = -2 instead of -12
read_digit.exponent = 0;
read_digit.mantissa = 0;
break;
case '.':
if (read_digit.exponent == 0)
read_digit.exponent = 1;
break;
#ifdef DEBUG
case ' ':
case '\t':
case 10:
case 13:
// ignore
break;
#endif
default:
#ifdef DEBUG
// invalid
//zprintf(PSTR("?%d\n"), fi(c));
#endif
break;
}
}
} //else if ( next_target.seen_parens_comment == 1 && c == ')')
else {
// store string in g_str from gcode example M206 P450 [ryan widi]
if (c == ']') {
g_str[g_str_c] = 0;
next_target.read_string = 0;
} else {
g_str[g_str_c] = c;
g_str_c++;
}
//next_target.seen_parens_comment = 0; // recognize stuff after a (comment)
}
// end of line
if ((c == 10) || (c == 13)) {
// Assume G1 for unspecified movements.
/* if ( ! next_target.seen_G && ! next_target.seen_M && ! next_target.seen_T &&
(next_target.seen_X || next_target.seen_Y || next_target.seen_Z ||
next_target.seen_E || next_target.seen_F)) {
next_target.seen_G = 1;
next_target.G = 1;
}
*/
MLOOP
process_gcode_command();
// reset variables
uint8_t ok = next_target.seen_G || next_target.seen_M || next_target.seen_T;
next_target.seen_X = next_target.seen_Y = next_target.seen_Z = \
next_target.seen_E = next_target.seen_F = next_target.seen_S = \
next_target.seen_P = next_target.seen_T = \
next_target.seen_G = next_target.seen_M = \
next_target.read_string = g_str_c = 0;
MLOOP
#ifdef ARC_SUPPORT
next_target.seen_R = next_target.seen_I = next_target.seen_J = 0;
#endif
last_field = 0;
read_digit.sign = read_digit.mantissa = read_digit.exponent = 0;
if (next_target.option_all_relative) {
next_target.target.axis[X] = next_target.target.axis[Y] = next_target.target.axis[Z] = 0;
}
if (next_target.option_all_relative || next_target.option_e_relative) {
next_target.target.axis[E] = 0;
}
if (ok) return 2;
return 1;
}
return 0;
}
// implement minimalis code to match teacup
float lastE;
void printposition()
{
zprintf(PSTR("X:%f Y:%f Z:%f E:%f\n"),
ff(cx1), ff(cy1),
ff(cz1), ff(ce01));
}
#define queue_wait() needbuffer()
void delay_ms(uint32_t d)
{
#ifndef ISPC
while (d) {
d--;
somedelay(1000);
}
#else
// delay on pc,
#endif
}
void temp_wait(void)
{
#ifdef heater_pin
wait_for_temp = 1;
int c = 0;
while (wait_for_temp && !temp_achieved()) {
domotionloop
servo_loop();
if (c++ > 20000) {
c = 0;
zprintf(PSTR("T:%f\n"), ff(Input));
//zprintf(PSTR("Heating\n"));
}
}
wait_for_temp = 0;
#endif
}
//int32_t mvc = 0;
static void enqueue(GCODE_COMMAND *) __attribute__ ((always_inline));
inline void enqueue(GCODE_COMMAND *t, int g0 = 1)
{
amove(t->target.F, t->seen_X ? t->target.axis[X] : cx1
, t->seen_Y ? t->target.axis[Y] : cy1
, t->seen_Z ? t->target.axis[Z] : cz1
, t->seen_E ? t->target.axis[E] : ce01
, g0);
}
inline void enqueuearc(GCODE_COMMAND *t, float I, float J, int cw)
{
draw_arc(t->target.F, t->seen_X ? t->target.axis[X] : cx1
, t->seen_Y ? t->target.axis[Y] : cy1
, t->seen_Z ? t->target.axis[Z] : cz1
, t->seen_E ? t->target.axis[E] : ce01
, I, J, cw);
}
void process_gcode_command()
{
uint32_t backup_f;
// convert relative to absolute
if (next_target.option_all_relative) {
next_target.target.axis[X] += cx1;//startpoint.axis[X];
next_target.target.axis[Y] += cy1;//startpoint.axis[Y];
next_target.target.axis[Z] += cz1;//startpoint.axis[Z];
next_target.target.axis[E] += ce01;//startpoint.axis[Z];
}
// E relative movement.
// Matches Sprinter's behaviour as of March 2012.
if (next_target.option_all_relative || next_target.option_e_relative)
next_target.target.e_relative = 1;
else
next_target.target.e_relative = 0;
// The GCode documentation was taken from http://reprap.org/wiki/Gcode .
if (next_target.seen_T) {
//? --- T: Select Tool ---
//?
//? Example: T1
//?
//? Select extruder number 1 to build with. Extruder numbering starts at 0.
//next_tool = next_target.T;
}
// check if buffer is near full
/*
int bl=bufflen();
float spd=1;
if (bl>NUMBUFFER/2) {
spd=(float)NUMBUFFER/(bl*4+2);
}
*/
if (next_target.seen_G) {
uint8_t axisSelected = 0;
//zprintf(PSTR("Gcode %su \n"),next_target.G);
switch (next_target.G) {
case 0:
//? G0: Rapid Linear Motion
//?
//? Example: G0 X12
//?
//? In this case move rapidly to X = 12 mm. In fact, the RepRap firmware uses exactly the same code for rapid as it uses for controlled moves (see G1 below), as - for the RepRap machine - this is just as efficient as not doing so. (The distinction comes from some old machine tools that used to move faster if the axes were not driven in a straight line. For them G0 allowed any movement in space to get to the destination as fast as possible.)
//?
enqueue(&next_target, 1);
break;
case 1:
//? --- G1: Linear Motion at Feed Rate ---
//?
//? Example: G1 X90.6 Y13.8 E22.4
//?
//? Go in a straight line from the current (X, Y) point to the point (90.6, 13.8), extruding material as the move happens from the current extruded length to a length of 22.4 mm.
//?
//next_target.target.axis[E]=0;
// auto retraction change
// thread S parameter as value of the laser, in 3D printer, donot use S in G1 !!
if (next_target.seen_S) {
//laserOn = next_target.S > 0;
//constantlaserVal = next_target.S;
}
enqueue(&next_target, 0);
break;
// G2 - Arc Clockwise
// G3 - Arc anti Clockwise
case 2:
case 3:
#ifdef ARC_SUPPORT
temp_wait();
if (!next_target.seen_I) next_target.I = 0;
if (!next_target.seen_J) next_target.J = 0;
//if (DEBUG_ECHO && (debug_flags & DEBUG_ECHO))
enqueuearc(&next_target, next_target.I, next_target.J, next_target.G == 2);
#endif
break;
case 4:
//? --- G4: Dwell ---
//?
//? Example: G4 P200
//?
//? In this case sit still doing nothing for 200 milliseconds. During delays the state of the machine (for example the temperatures of its extruders) will still be preserved and controlled.
//?
queue_wait();
// delay
if (next_target.seen_P) {
zprintf(PSTR("\n\nPause enabled:next_target.P-%d\n\n"), next_target.P);
// the next statement, takes around 100-110ms to get executed. we will aproximate it as 100ms
// #### MLOOP might be the cause of such a big delay
for (; next_target.P > 0; next_target.P--) {//
MLOOP
delay_ms(5); //
//zprintf(PSTR("Pause 5ms\n"));
zprintf(PSTR("Pause:P-%d\n\n"), next_target.P);
}
}
break;
#ifdef output_enable
case 5:
reset_eeprom();
reload_eeprom();
case 6:
cx1 = 0;
cy1 = 0;
cz1 = 0;
ce01 = 0;
amove(1, 100, 100, 100, 0);
/*
amove(100, 10, 0, 0, 0);
amove(100, 10, 10, 0, 0);
amove(100, 0, 10, 0, 0);
amove(100, 0, 0, 0, 0);
amove(100, 10, 0, 0, 0);
amove(100, 10, 10, 0, 0);
amove(100, 0, 10, 0, 0);
amove(100, 0, 0, 0, 0);
amove(100, 10, 0, 0, 0);
amove(100, 10, 10, 0, 0);
amove(100, 0, 10, 0, 0);
amove(100, 0, 0, 0, 0);
amove(100, 10, 0, 0, 0);
amove(100, 10, 10, 0, 0);
amove(100, 0, 10, 0, 0);
amove(100, 0, 0, 0, 0);
*/
break;
#endif
case 7: // baby step in S in milimeter
int nstep;
/*if (next_target.seen_X) move_motor(0, sx[0], next_target.target.axis[X] * stepmmx[0]);
if (next_target.seen_Y) move_motor(1, sx[1], next_target.target.axis[Y] * stepmmx[1]);
if (next_target.seen_Z) move_motor(2, sx[2], next_target.target.axis[Z] * stepmmx[2]);
if (next_target.seen_S) {
move_motor(0, sx[0], next_target.S * stepmmx[0]);
move_motor(1, sx[1], next_target.S * stepmmx[1]);
move_motor(2, sx[2], next_target.S * stepmmx[2]);
}
float bx,by,bz;
bx=cx1;
by=cy1;
bz=cz1;
if (next_target.seen_Z) addmove(50,bx,by,next_target.Z+bz,ce01);
cx1=bx;
cy1=by;
cz1=bz;*/
break;
case 28:
homing();
next_target.target.axis[X] = cx1;
next_target.target.axis[Y] = cy1;
next_target.target.axis[Z] = cz1;
next_target.target.axis[E] = ce01;
printposition();
break;
case 90:
//? --- G90: Set to Absolute Positioning ---
//?
//? Example: G90
//?
//? All coordinates from now on are absolute relative to the origin
//? of the machine. This is the RepRap default.
//?
//? If you ever want to switch back and forth between relative and
//? absolute movement keep in mind, X, Y and Z follow the machine's
//? coordinate system while E doesn't change it's position in the
//? coordinate system on relative movements.
//?
// No wait_queue() needed.
next_target.option_all_relative = 0;
break;
case 91:
//? --- G91: Set to Relative Positioning ---
//?
//? Example: G91
//?
//? All coordinates from now on are relative to the last position.
//?
// No wait_queue() needed.
next_target.option_all_relative = 1;
break;
case 92:
//? --- G92: Set Position ---
//?
//? Example: G92 X10 E90
//?
//? Allows programming of absolute zero point, by reseting the current position to the values specified. This would set the machine's X coordinate to 10, and the extrude coordinate to 90. No physical motion will occur.
//?
queue_wait();
if (next_target.seen_X) {
cx1 = next_target.target.axis[X];
axisSelected = 1;
};
if (next_target.seen_Y) {
cy1 = next_target.target.axis[Y];
axisSelected = 1;
};
if (next_target.seen_Z) {
cz1 = next_target.target.axis[Z];
axisSelected = 1;
};
if (next_target.seen_E) {
lastE = ce01 = next_target.target.axis[E];
axisSelected = 1;
};
if (axisSelected == 0) {
cx1 = next_target.target.axis[X] =
cy1 = next_target.target.axis[Y] =
cz1 = next_target.target.axis[Z] =
ce01 = next_target.target.axis[E] = 0;
}
init_pos();
break;
// unknown gcode: spit an error
default:
zprintf(PSTR("E:G%d\nok\n"), next_target.G);
return;
}
} else if (next_target.seen_M) {
//uint8_t i;
switch (next_target.M) {
/*#ifndef ISPC
case 200: // keybox action
if (next_target.seen_P) {
zprintf(PSTR("DOKEY:%d\n"), next_target.P);
switch (next_target.P) {
KBOX_DO_ACT
}
}
break;
#endif
*/
case 0:
//? --- M0: machine stop ---
//?
//? Example: M0
//?
//? http://linuxcnc.org/handbook/RS274NGC_3/RS274NGC_33a.html#1002379
//? Unimplemented, especially the restart after the stop. Fall trough to M2.
//?
case 2:
// stop and clear all buffer
if (m) {
RUNNING = 0;
waitbufferempty();
printposition();
}
break;
case 25:
// stop and clear all buffer
pausemachine();
break;
case 84: // For compatibility with slic3rs default end G-code.
//? --- M2: program end ---
//?
//? Example: M2
//?
//? http://linuxcnc.org/handbook/RS274NGC_3/RS274NGC_33a.html#1002379
//?
queue_wait();
//for (i = 0; i < NUM_HEATERS; i++)temp_set(i, 0);
power_off();
zprintf(PSTR("\nstop\n"));
break;
/* case 6:
//? --- M6: tool change ---
//?
//? Undocumented.
//tool = next_tool;
break;
*/
// M3/M101- extruder on M3 S -> PWM output to heated pin
// M4 are special, usually to make spindle counter clockwise and we dont have implementation, but we use it for laser
// mode : constant laser burn per step
// M4 Sxxx 0: disable 1:enable
// if defined, M3 Sxxx, xxx will define how manu microseconds laser will on on each step.
// xxx will limit the G1 maximum feedrate
//
case 4:
// already implemented using value = 255 = cutting
//constantlaser = next_target.S == 1;
break;
case 5:
// already implemented using value = 255 = cutting
//constantlaser = next_target.S == 1;
next_target.seen_S=1;
next_target.S=0;
case 3:
#ifdef LASERMODE
// if no S defined then full power
if (!next_target.seen_S)next_target.S = 255;
laserOn = next_target.S > 0;
constantlaserVal = next_target.S;
if (laserOn) zprintf(PSTR("LASERON\n"));
if (next_target.seen_P) {
if (m)waitbufferempty();
delay(100);
//pinMode(laser_pin, OUTPUT);
zprintf(PSTR("PULSE LASER\n"));
digitalWrite(laser_pin, HIGH);
delay(next_target.P);
}
digitalWrite(laser_pin, LOW);
#endif
break;
/* case 101:
//? --- M101: extruder on ---
//?
//? Undocumented.
temp_wait();
// enable the laser or spindle
break;
// M5/M103- extruder off
case 5:
case 103:
//? --- M103: extruder off ---
//?
//? Undocumented.
// disable laser/spindle
break;
*/
#ifdef servo_pin
case 300:
waitbufferempty();
setfan_val(255); // turn on power
zprintf(PSTR("Servo:%d\n"), fi(next_target.S));
//pinMode(servo_pin,OUTPUT);
servo_set(next_target.S * (2000 / 180));
if (!next_target.seen_P)next_target.P = 1000; // 1 second wait
// wait loop
uint32_t mc;
mc = millis();
while ((millis() - mc) < next_target.P) {
domotionloop
}
setfan_val(0); // turn off power
break;
#endif
case 104:
set_temp(next_target.S);
break;
case 105:
zprintf(PSTR("T:%f\n"), ff(Input));
//zprintf(PSTR("B:%d/%d\n"), fi(bufflen()),fi(NUMBUFFER));
break;
case 109:
set_temp(next_target.S);
temp_wait();
break;
case 7:
case 107:
// set laser pwm off
#ifdef fan_pin
setfan_val(0);
#endif
break;
case 106:
// set laser pwm on
#ifdef fan_pin
setfan_val(next_target.S);
#endif
break;
case 112:
//? --- M112: Emergency Stop ---
//?
//? Example: M112
//?
//? Any moves in progress are immediately terminated, then the printer
//? shuts down. All motors and heaters are turned off. Only way to
//? restart is to press the reset button on the master microcontroller.
//? See also M0.
//?
// stop and clear all buffer
RUNNING = 0;
break;
case 114:
//? --- M114: Get Current Position ---
//?
//? Example: M114
//?
//? This causes the RepRap machine to report its current X, Y, Z and E coordinates to the host.
//?
//? For example, the machine returns a string such as:
//?
//? <tt>ok C: X:0.00 Y:0.00 Z:0.00 E:0.00</tt>
//?
#ifdef ENFORCE_ORDER
// wait for all moves to complete
queue_wait();
#endif
printposition();
break;
case 115:
// zprintf(PSTR("FIRMWARE_NAME:Repetier_1.9 FIRMWARE_URL:null PROTOCOL_VERSION:1.0 MACHINE_TYPE:teacup EXTRUDER_COUNT:1 REPETIER_PROTOCOL:\n"));
zprintf(PSTR("FIRMWARE_NAME:Repetier_1.9\n"));
break;
case 119:
//? --- M119: report endstop status ---
//? Report the current status of the endstops configured in the
//? firmware to the host.
docheckendstop();
zprintf(PSTR("END:"));
zprintf(endstopstatus < 0 ? PSTR("HI ") : PSTR("LOW "));
zprintf(PSTR("\n"));
break;
// unknown mcode: spit an error
#ifdef USE_EEPROM
#ifndef SAVE_RESETMOTION
case 502:
reset_eeprom();
#endif
case 205:
reload_eeprom();
#endif
case 503:
zprintf(PSTR("EPR:3 145 %f Xhome\n"), ff(ax_home[0]));
zprintf(PSTR("EPR:3 149 %f Y\n"), ff(ax_home[1]));
zprintf(PSTR("EPR:3 153 %f Z\n"), ff(ax_home[2]));
zprintf(PSTR("EPR:3 3 %f StepX\n"), ff(stepmmx[0]));
zprintf(PSTR("EPR:3 7 %f Y\n"), ff(stepmmx[1]));
zprintf(PSTR("EPR:3 11 %f Z\n"), ff(stepmmx[2]));
zprintf(PSTR("EPR:3 0 %f E\n"), ff(stepmmx[3]));
zprintf(PSTR("EPR:2 15 %d FeedX\n"), fi(maxf[0]));
zprintf(PSTR("EPR:2 19 %d Y\n"), fi(maxf[1]));
zprintf(PSTR("EPR:2 23 %d Z\n"), fi(maxf[2]));
zprintf(PSTR("EPR:2 27 %d E\n"), fi(maxf[3]));
zprintf(PSTR("EPR:3 181 %d Jerk\n"), fi(xyjerk));
zprintf(PSTR("EPR:3 51 %d Accel\n"), fi(accel));
zprintf(PSTR("EPR:3 67 %d MVAccel\n"), fi(mvaccel));
zprintf(PSTR("EPR:3 177 %d FHome\n"), fi(homingspeed));
zprintf(PSTR("EPR:3 185 %f XYscale\n"), ff(xyscale));
#ifdef NONLINEAR
zprintf(PSTR("EPR:3 157 %f RodL\n"), ff(delta_diagonal_rod));
zprintf(PSTR("EPR:3 161 %f RodH\n"), ff(delta_radius));
#endif
zprintf(PSTR("EPR:3 165 %f Xofs\n"), ff(axisofs[0]));
#ifdef DRIVE_XYYZ
zprintf(PSTR("EPR:3 169 %f Y1ofs\n"), ff(axisofs[1]));
zprintf(PSTR("EPR:3 173 %f Y2ofs\n"), ff(axisofs[2]));
#else
zprintf(PSTR("EPR:3 169 %f Yofs\n"), ff(axisofs[1]));
zprintf(PSTR("EPR:3 173 %f Zofs\n"), ff(axisofs[2]));
#endif
#ifdef USE_BACKLASH
zprintf(PSTR("EPR:3 80 %f Xbcklsh\n"), fi(xback[0]));
zprintf(PSTR("EPR:3 84 %f Y\n"), fi(xback[1]));
zprintf(PSTR("EPR:3 88 %f Z\n"), fi(xback[2]));
zprintf(PSTR("EPR:3 92 %f E\n"), fi(xback[3]));
#endif
break;
#ifdef WIFISERVER
// show wifi
case 504:
// zprintf(PSTR("Wifi AP 400:%s PWD 450:%s mDNS 470:%s telID 380:%s\n"), wifi_ap, wifi_pwd, wifi_dns, wifi_telebot);
break;
#endif
#ifdef USE_EEPROM
case 206:
if (next_target.seen_X)next_target.S = next_target.target.axis[X];
int32_t S_F;
S_F = (next_target.S * 1000);
int32_t S_I;
S_I = (next_target.S);
if (next_target.seen_P)
switch (next_target.P) {
#define eprom_wr(id,pos,val){\
case id:\
eepromwrite(pos, val);\
break;\
}
eprom_wr(145, EE_xhome, S_F);
eprom_wr(149, EE_yhome, S_F);
eprom_wr(153, EE_zhome, S_F);
eprom_wr(0, EE_estepmm, S_F);
eprom_wr(3, EE_xstepmm, S_F);
eprom_wr(7, EE_ystepmm, S_F);
eprom_wr(11, EE_zstepmm, S_F);
eprom_wr(15, EE_max_x_feedrate, S_I);
eprom_wr(19, EE_max_y_feedrate, S_I);
eprom_wr(23, EE_max_z_feedrate, S_I);
eprom_wr(27, EE_max_e_feedrate, S_I);
eprom_wr(51, EE_accelx, S_I);
eprom_wr(67, EE_mvaccelx, S_I);
eprom_wr(177, EE_homing, S_I);
eprom_wr(181, EE_jerk, S_I);
eprom_wr(185, EE_xyscale, S_F);
#ifdef NONLINEAR
eprom_wr(157, EE_rod_length, S_F);
eprom_wr(161, EE_hor_radius, S_F);
#endif
eprom_wr(165, EE_towera_ofs, S_F);
eprom_wr(169, EE_towerb_ofs, S_F);
eprom_wr(173, EE_towerc_ofs, S_F);
#ifdef USE_BACKLASH
eprom_wr(80, EE_xbacklash, S_F);
eprom_wr(84, EE_ybacklash, S_F);
eprom_wr(88, EE_zbacklash, S_F);
eprom_wr(92, EE_ebacklash, S_F);
#endif
#ifdef WIFISERVER
case 380:
eepromwritestring(380, g_str);
break;
case 400:
eepromwritestring(400, g_str);
break;
case 450:
eepromwritestring(450, g_str);
break;
case 470:
eepromwritestring(470, g_str);
break;
#endif
}
reload_eeprom();
break;
#endif
case 220:
//? --- M220: Set speed factor override percentage ---
if ( ! next_target.seen_S)
break;
// Scale 100% = 100
f_multiplier = next_target.S * 0.01;
MLOOP
break;
case 221:
//? --- M220: Set speed factor override percentage ---
if ( ! next_target.seen_S)
break;
// Scale 100% = 256
e_multiplier = next_target.S * 0.01;
MLOOP
break;
case 600: // change filament M600 Sxxx S = length mm to unload filament, it will add 10mm when load, click endstop to resume
changefilament(next_target.S);
break;
// default:
//zprintf(PSTR("E:M%d\nok\n"), next_target.M);
} // switch (next_target.M)
} // else if (next_target.seen_M)
} // process_gcode_command()
void init_gcode()
{
next_target.target.F = 50;
next_target.option_all_relative = 0;
#ifdef USE_EEPROM
eeprominit
#endif
}
<file_sep>/karya34m/common.h
#ifndef COMMON_H
#define COMMON_H
#include "motion.h"
#include "config_pins.h"
#define BUFSIZE 64
#define buf_canread(buffer) ((buffer ## head - buffer ## tail ) & \
(BUFSIZE - 1))
#define buf_pop(buffer, data) do { \
data = buffer ## buf[buffer ## tail]; \
buffer ## tail = (buffer ## tail + 1) & \
(BUFSIZE - 1); \
} while (0)
#define buf_canwrite(buffer) ((buffer ## tail - buffer ## head - 1) & \
(BUFSIZE - 1))
#define buf_push(buffer, data) do { \
buffer ## buf[buffer ## head] = data; \
buffer ## head = (buffer ## head + 1) & \
(BUFSIZE - 1); \
} while (0)
#define MASK(PIN) (1 << PIN)
//const float powers[] = {1.f, 0.1f, 0.01f,0.001f,0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f};;
//#define POWERS(e) (powers[e])
//#define POWERS(e) (float)pgm_read_float(&(powers[e]))
const int32_t PROGMEM powers[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};;
#define POWERS(e) (int32_t)pgm_read_dword(&(powers[e]))
#define DECFLOAT_EXP_MAX 7
#ifndef ISPC
//#define output_enable
// AVR specific code here
//#include <avr/pgmspace.h>
#include <arduino.h>
#ifdef CORESERIAL
extern uint8_t serial_popchar();
extern void serial_writechar(uint8_t data);
extern void serial_init(float BAUD);
extern uint8_t serial_available();
#define serialwr serial_writechar
#define serialrd(s) s=serial_popchar()
#define serialav() serial_available()
#define serialinit(baud) serial_init(baud)
#else
//#ifdef __ARM__
#ifdef WIFISERVER
extern void wifiwr(uint8_t s);
static void serialwr(uint8_t s){Serial.write(s);wifiwr(s);}
#else
static void serialwr(uint8_t s){Serial.write(s);}
#endif
static void serialwr0(uint8_t s){Serial.write(s);}
//#else
//#define serialwr Serial.write
//#endif
#define serialrd(s) s=Serial.read()
#define serialav() Serial.available()
#define serialinit(baud) Serial.begin(baud)
#endif
void sendf_P(void (*writechar)(uint8_t),PGM_P format_P, ...);
// No __attribute__ ((format (printf, 1, 2)) here because %q isn't supported.
//#define xprintf(...) sendf_P(serial_writechar, __VA_ARGS__)
//#define sersendf_P(...) sendf_P(serial_writechar, __VA_ARGS__)
#define zprintf(...) sendf_P(serialwr, __VA_ARGS__)
#define xprintf(...) sendf_P(serialwr0, __VA_ARGS__)
#define ff(f) int32_t(1000.f*f)
#define fg(f) int32_t(100.f*f)
#define fi(f) (int32_t)f
#else // ispc
#define output_enable
#include<stdio.h>
#include<stdint.h>
#define PROGMEM
#define PGM_P const char *
#define PSTR(s) ((const PROGMEM char *)(s))
#define pgm_read_byte(x) (*((uint8_t *)(x)))
#define pgm_read_word(x) (*((uint16_t *)(x)))
#define pgm_read_dword(x) (*((uint32_t *)(x)))
#define pgm_read_float(x) (*((float *)(x)))
static void serial_writechar(uint8_t data) {
printf("%c", (char)data);
}
#define ff(f) (float(f))
#define fg(f) (int32_t(f))
#define fi(f) int32_t(f)
#define sersendf_P printf
#define xprintf printf
#define zprintf printf
#endif
#endif // common_h
<file_sep>/karya34m/eprom.h
#ifndef EEPROM_H
#define EEPROM_H
#include "motion.h"
#include "common.h"
#if defined(ESP8266)
#include <EEPROM.h>
#define EEMEM
#define eepromwrite(p,val) EEPROM.put(p, (int32_t)val)
static int32_t eepromread(int p){
int32_t val;
EEPROM.get(p, val);
return val;
}
static void eepromwritestring(int p,char* str){
byte l=strlen(str);
EEPROM.put(p,l);
for (int i=0;i<l;i++){
p++;
EEPROM.put(p,str[i]);
}
}
static int eepromreadstring(int p,char* str){
int i;
byte l;
EEPROM.get(p,l);
for (i=0;i<l;i++){
p++;
EEPROM.get(p,str[i]);
}
str[l]=0;
}
#define eepromcommit EEPROM.commit()
#define eeprominit EEPROM.begin(512);
#elif defined(__ARM__) // esp8266
#include <EEPROM.h>
#define EEMEM
static int32_t eepromread(int p)
{
int32_t r;
uint16_t* b;
b=(uint16_t*)&r;
EEPROM.read(p,b);p+=2;b++;
EEPROM.read(p,b);
//zprintf(PSTR("Read eeprom %d %d\n"),fi(p),fi(r));
return r;
}
static void eepromwrite(int p,int32_t val)
{
uint16_t* b;
b=(uint16_t*)&val;
EEPROM.update(p,*b);p+=2;b++;
EEPROM.update(p,*b);
//zprintf(PSTR("Write eeprom %d %d\n"),fi(p),fi(val));
}
#define eepromcommit
#define eeprominit EEPROM.PageBase0 = 0x801F000; EEPROM.PageBase1 = 0x801F800; EEPROM.PageSize = 0x400;EEPROM.init();
#endif //
#ifndef __AVR__
/*
#define EE_home 145
#define EE_home 149
#define EE_home 153
#define EE_accelx 51
#define EE_accely 55
#define EE_accelz 59
#define EE_accele 63
#define EE_mvaccelx 67
#define EE_mvaccely 71
#define EE_mvaccelz 75
#define EE_max_x_feedrate 15
#define EE_max_y_feedrate 19
#define EE_max_z_feedrate 23
#define EE_max_e_feedrate 27
#define EE_xstepmm 3
#define EE_ystepmm 7
#define EE_zstepmm 11
#define EE_estepmm 0
#define EE_xbacklash 80
#define EE_ybacklash 84
#define EE_zbacklash 88
#define EE_ebacklash 92
*/
#define EE_xhome 0
#define EE_yhome 5
#define EE_zhome 10
#define EE_accelx 15
#define EE_accely 20
#define EE_accelz 25
#define EE_accele 35
#define EE_mvaccelx 40
#define EE_mvaccely 45
#define EE_mvaccelz 50
#define EE_max_x_feedrate 55
#define EE_max_y_feedrate 60
#define EE_max_z_feedrate 65
#define EE_max_e_feedrate 70
#define EE_xstepmm 75
#define EE_ystepmm 80
#define EE_zstepmm 85
#define EE_estepmm 90
#define EE_xbacklash 115
#define EE_ybacklash 120
#define EE_zbacklash 125
#define EE_ebacklash 130
#define EE_homing 135
#define EE_towera_ofs 140
#define EE_towerb_ofs 145
#define EE_towerc_ofs 150
#ifdef NONLINEAR
#define EE_hor_radius 155
#define EE_rod_length 160
#endif
#define EE_jerk 165
#define EE_xyscale 170
#ifdef POWERFAILURE
#define EE_lastline 200
#endif
#define EE_telebot 380
#define EE_wifi_ap 400
#define EE_wifi_pwd 450
#define EE_wifi_dns 470
#else
extern float EEMEM EE_xhome;
extern float EEMEM EE_yhome;
extern float EEMEM EE_zhome;
extern int32_t EEMEM EE_homing;
extern int32_t EEMEM EE_jerk;
extern float EEMEM EE_xyscale;
extern int32_t EEMEM EE_accelx;
extern int32_t EEMEM EE_mvaccelx;
extern int32_t EEMEM EE_max_x_feedrate;
extern int32_t EEMEM EE_max_y_feedrate;
extern int32_t EEMEM EE_max_z_feedrate;
extern int32_t EEMEM EE_max_e_feedrate;
extern float EEMEM EE_xstepmm;
extern float EEMEM EE_ystepmm;
extern float EEMEM EE_zstepmm;
extern float EEMEM EE_estepmm;
#ifdef NONLINEAR
extern float EEMEM EE_hor_radius;
extern float EEMEM EE_rod_length;
#endif
extern float EEMEM EE_towera_ofs;
extern float EEMEM EE_towerb_ofs;
extern float EEMEM EE_towerc_ofs;
#ifdef USE_BACKLASH
extern int32_t EEMEM EE_xbacklash;
extern int32_t EEMEM EE_ybacklash;
extern int32_t EEMEM EE_zbacklash;
extern int32_t EEMEM EE_ebacklash;
#endif
#ifdef POWERFAILURE
extern int32_t EEMEM EE_lastline;
#endif
#endif
extern void reload_eeprom();
extern void reset_eeprom();
//extern char wifi_ap[40];
//extern char wifi_pwd[20];
//extern char wifi_dns[20];
//extern char wifi_telebot[20];
#endif // EEPROM_H
<file_sep>/karya34m/motion.cpp
#include "motion.h"
#include "gcode.h"
#include "common.h"
#include "config_pins.h"
#include "timer.h"
#include "temp.h"
#include <stdint.h>
#ifndef ISPC
#include<arduino.h>
#include "eprom.h"
#else
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#endif
// bikin pusing !, buat check TIMER di AVR, malah freeze
//#define DEBUGLOOP
#ifdef DEBUGLOOP
#define LOOP_IN(n) zprintf(PSTR("LOOP %d IN "),fi(n));
#define LOOP_OUT(n) zprintf(PSTR("LOOP %d OUT "),fi(n));
#else
#define LOOP_IN(n)
#define LOOP_OUT(n)
#endif
// JERK Setting
#define MINCORNERSPEED 0 // minimum cornering speed
#define MINSTEP 0
// Centripetal
//#define JERK1 //centripetal corner , still not good, back to repetier style jerk
#define DEVIATE 5//;0.02*50 - for centripetal corner safe speed
// repetier 1
#define JERK2 //repetier style jerk
//#define JERK2A //repetier style jerk
//#define JERKSTEP 30
#ifdef USETIMER1
#ifdef ESP8266
#define CLOCKCONSTANT 5000000.f // tick/seconds
#define DSCALE 0 // use 5Mhz timer shift 0bit
#define DIRDELAY 20 // usec
#endif
#else // usetimer1
#define CLOCKCONSTANT 1000000.f // tick/seconds
#define DSCALE 0 // 1mhz use micros shift 3bit
#define DIRDELAY 2
#endif
#define X 0
#define Y 1
#define Z 2
#define E 3
int constantlaserVal = 0;
int laserOn = 0, isG0 = 1;
uint8_t homingspeed;
int xback[4];
uint8_t head, tail, tailok;
int maxf[4];
float xyscale, f_multiplier, e_multiplier;
int xyjerk, accel;
int i;
int mvaccel;
float ax_home[NUMAXIS];
float stepdiv, stepdiv2;
float wstepdiv2;
int32_t totalstep;
uint32_t bsdx[NUMAXIS];
int8_t sx[NUMAXIS];
int32_t dlp, dl, dln;
int8_t checkendstop, xctstep, yctstep, zctstep, ectstep, xcheckevery, ycheckevery, zcheckevery, echeckevery;
int16_t endstopstatus;
int8_t ishoming;
float axisofs[4] = {0, 0, 0, 0};
float F_SCALE = 1;
int8_t RUNNING = 1;
int8_t PAUSE = 0;
float stepmmx[4];
float cx1, cy1, cz1, ce01;
tmove move[NUMBUFFER];
#define sqr2(n) (n)*(n)
#include "nonlinear.h"
// to calculate delay from v^2, fast invsqrt hack
#ifdef __AVR__
//#define FASTINVSQRT // less precice speed faster 4us
float InvSqrt(float x)
{
#ifdef FASTINVSQRT
int32_t* i = (int32_t*)&x; // store floating-point bits in integer
*i = 0x5f335a86 - (*i >> 1); // initial guess for Newton's method
#else // if FAST then bypass newtons method
float xhalf = 0.5f * x;
int32_t i = *(int32_t*)&x; // store floating-point bits in integer
i = 0x5f375a86 - (i >> 1); // initial guess for Newton's method
x = *(float*)&i; // convert new bits into float
x = x * (1.5f - xhalf * x * x); // One round of Newton's method , disable if want faster but not precise
#endif
return x;
}
#else
// other CPU use normal SQRT
#define InvSqrt(f) 1.0/sqrt(f)
#endif
//#define xInvSqrt(n) n>1?stepdiv2*InvSqrt(n):stepdiv
#define xInvSqrt(n) n>0.25?stepdiv2*InvSqrt(n):2*stepdiv2
#define sqrt32(n) sqrt(n)
/*
=================================================================================================================================================
RESET_MOTION
=================================================================================================================================================
Reset all variable
*/
// keep last direction to enable backlash if needed
void reset_motion()
{
// 650bytes code
homingspeed = HOMINGSPEED;
xyjerk = XYJERK;
xyscale = 1;
ishoming = 0;
cmctr = 0;
e_multiplier = f_multiplier = 1;
checkendstop = 0;
endstopstatus = 0;
xcheckevery = CHECKENDSTOP_EVERY * stepmmx[0];
ycheckevery = CHECKENDSTOP_EVERY * stepmmx[1];
zcheckevery = CHECKENDSTOP_EVERY * stepmmx[2];
echeckevery = CHECKENDSTOP_EVERY * stepmmx[3];
head = tail = tailok = 0;
cx1 = 0;
cy1 = 0;
cz1 = 0;
ce01 = 0;
#ifdef ISPC
tick = 0;
#endif
#ifndef SAVE_RESETMOTION
#ifdef NONLINEAR
delta_diagonal_rod = DELTA_DIAGONAL_ROD;
delta_radius = DELTA_RADIUS;
#endif
maxf[0] = XMAXFEEDRATE;
maxf[1] = YMAXFEEDRATE;
maxf[2] = ZMAXFEEDRATE;
maxf[3] = E0MAXFEEDRATE;
accel = XACCELL;
mvaccel = XMOVEACCELL;
stepmmx[0] = XSTEPPERMM;
stepmmx[1] = YSTEPPERMM;
stepmmx[2] = ZSTEPPERMM;
stepmmx[3] = E0STEPPERMM;
ax_home[0] = XMAX;
ax_home[1] = YMAX;
ax_home[2] = ZMAX;
xback[0] = MOTOR_X_BACKLASH;
xback[1] = MOTOR_Y_BACKLASH;
xback[2] = MOTOR_Z_BACKLASH;
xback[3] = MOTOR_E_BACKLASH;
#endif
}
void preparecalc()
{
#ifdef NONLINEAR
nonlinearprepare();
#endif
}
int32_t mcx[NUMAXIS];
/*
=================================================================================================================================================
MOTOR CLASS
=================================================================================================================================================
*/
#define FASTAXIS(n) ((n->status >> 4)&3)
//if(m)coreloop();
#include "motors.h"
int mb_ctr;
int32_t bufflen()
{
mb_ctr = head >= tail ? head - tail : (NUMBUFFER + head) - tail; // 5+0 - 4
return mb_ctr;
}
void power_off()
{
motor_0_OFF();
motor_1_OFF();
motor_2_OFF();
motor_3_OFF();
}
/*
=================================================================================================================================================
PREPARERAMP
=================================================================================================================================================
Bertujuan mengkalkulasi berapa tangga aselerasi awal (rampup) dan akhir (rampdown)
rampup belum tentu speed naik, bisa jadi speed turun.
Profil dari gerakan ditentukan oleh fs (fstart), fn (f nominal), fe (f end)
dengan aselerasi yang ditentukan, maka dihitung berapa rampup, dan down
Apabila rampup dan down bertemu, atau melebihi jarak totalstep, maka perlu dikalkulasi lagi fs,fn dan fe supaya ramp bisa terpenuhi
Untuk rampdown, harusnya rekursif ke belakang apabila tidak cukup jarak rampdown. namun implementasi sekarang
hanya melakukan kalkulasi ulang aselerasi supaya rampdown maksimal ya sama dengan totalstep
24-4-2018, i change the math of ramp calculation using mm distance
* */
float currdis, prevdis, fe;
#ifdef NONLINEAR
float rampv;
float istepmmx[4];
float rampseg, rampup, rampdown;
#else
int32_t rampseg, rampup, rampdown;
#define rampv 1
#endif
#define sqr(x) x*x
#define ramplenq(oo,v0,v1,stepa) if (v1>v0)oo=(v1-v0)*stepa;
#define speedat(v0,a,s,stp) (a * s / stp + v0)
/*#define ramplen(oo,v0,v1,a,stepmm) oo=((int32_t)v1-(int32_t)v0)*stepmm/(a);
#define accelat(v0,v1,s) ((int32_t)v1 - (int32_t)v0 ) / (2 * s)
#define ramplenmm(oo,v0,v1,a) oo=(((int32_t)v1-(int32_t)v0)<<5)/(a);
#define speedatmm(v0,a,s) ((((int32_t)a * s)>>5) + (int32_t)v0)
*/
void prepareramp(int32_t bpos)
{
//#define preprampdebug
tmove *m, *next;
m = &move[bpos];
//if (m->status & 4)return; // already calculated
int faxis = FASTAXIS(m);
int32_t ytotalstep = labs(m->dx[faxis]);
#define stepmm Cstepmmx(faxis)
float stepa = stepmm / (m->ac);
CORELOOP
if (bpos != (head)) {
next = &move[nextbuff(bpos)];
fe = next->fs;
} else fe = 0;
rampup = rampdown = 0;
ramplenq(rampup, m->fs, m->fn, stepa);
ramplenq(rampdown, fe, m->fn, stepa);
#ifdef preprampdebug
zprintf(PSTR("\n========1========\nRU:%d Rd:%d Ts:%d\n"), rampup, rampdown, ytotalstep);
zprintf(PSTR("FS:%f AC:%f FN:%f FE:%f\n"), ff(m->fs), ff(m->ac), ff(m->fn), ff(fe));
#endif
if (rampup + rampdown > ytotalstep) {
// if crossing and have rampup
int32_t r = ((rampdown + rampup) - ytotalstep) >> 1;
rampup -= r;
rampdown -= r;
if (rampup < 0)rampup = 0;
if (rampdown < 0)rampdown = 0;
if (rampdown > ytotalstep)rampdown = ytotalstep;
if (rampup > ytotalstep)rampup = ytotalstep;
m->fn = speedat(m->fs, m->ac, rampup, stepmm);
}
CORELOOP
#ifdef preprampdebug
zprintf(PSTR("========FINAL========\nRU:%d Rd:%d\n"), rampup, rampdown);
zprintf(PSTR("FS:%f AC:%f FN:%f FE:%f\n"), ff(m->fs), ff(m->ac), ff(m->fn), ff(fe));
#endif
m->status |= 4;
CORELOOP
}
/*
=================================================================================================================================================
PLANNER
=================================================================================================================================================
dipanggil oleh untuk mulai menghitung dan merencakanan gerakan terbaik
kontrol mbelok adalah cara mengontrol supaya saat menikung, kecepatan dikurangi sehingga tidak skip motornya
*/
float currf[5], prevf[5];
float lastf = 0;
void backforward()
{
int h;
// now back planner
h = head; //
//h=prevbuff(head);
if (h == tailok) {
return;
}
tmove *next, *curr;
curr = &move[h];
curr->fs = fmin(curr->maxs, (curr->ac * curr->dis));
h = prevbuff(h);
while (h != tailok) {
next = curr;
curr = &move[h];
if (curr->fs != curr->maxs) {
float fs = next->fs + (curr->ac * curr->dis);
//zprintf(PSTR("back. %d\n"),fs);
if (fs < curr->maxs) {
curr->fs = fs;
} else {
curr->fs = curr->maxs;
}
}
h = prevbuff(h);
}
// forward
//h=nextbuff(tailok);
//if (h==head) {
// return;
//}
h = tailok;
next = &move[h];
h = nextbuff(tailok);
while (h != head) {
curr = next;
next = &move[h];
if (curr->fs < next->fs) {
float fs = curr->fs + (curr->ac * curr->dis);
//zprintf(PSTR("Forw. %d\n"),fs);
if (fs < next->fs) {
next->fs = fs;
tailok = h;
}
curr->fn = fmin(fs, curr->fn);
}
if (next->fs == next->maxs) tailok = h;
h = nextbuff(h);
}
CORELOOP
}
float mmdis[4];
void planner(int32_t h)
{
// mengubah semua cross feedrate biar optimal secepat mungkin
int32_t p;
tmove *curr;
tmove *prev;
curr = &move[h];
float scale = 1;
int32_t xtotalstep = abs(curr->dx[FASTAXIS(curr)]);
memcpy(prevf, currf, sizeof prevf);
currf[4] = curr->fn;
for (int i = 0; i < NUMAXIS; i++) {
//prevf[i] = currf[i];
currf[i] = 0;
if (curr->dx[i] != 0) {
float cdx = curr->fn * mmdis[i];
float scale2 = float(maxf[i]) * curr->dis / fabs(cdx);
if (scale2 < scale) scale = scale2;
currf[i] = float(cdx) / curr->dis;
CORELOOP
}
}
// update all speed and square it up, after this all m->f are squared !
#ifdef output_enable
zprintf (PSTR("Fratio :%f\n"), ff(scale));
#endif
scale *= curr->fn;
curr->fn = (scale * scale);
#ifdef output_enable
zprintf (PSTR("FN :%d\n"), fi(curr->fn));
#endif
//#define JERK1
//if (bufflen() < 1) return;
//p = prevbuff(h);
//prev = &move[p];
//if ((prev->status & 3) == 2)return;// if already planned
// ==================================
// Centripetal corner max speed calculation, copy from other firmware
float max_f = MINCORNERSPEED * MINCORNERSPEED;
if (bufflen() > 1) {
max_f = fmax(currf[4], prevf[4]);
#ifdef JERK2A
float jerk = max_f * 0.7 * (1 - (currf[0] * prevf[0] + currf[1] * prevf[1] + currf[2] * prevf[2]) / ((currf[4] * prevf[4])));
#else
int32_t fdx = currf[0] - prevf[0];
int32_t fdy = currf[1] - prevf[1];
int32_t fdz = currf[2] - prevf[2];
float jerk = sqrt(fdx * fdx + fdy * fdy + fdz * fdz);
#endif
CORELOOP
float factor = 1;
if (jerk > xyjerk) {
factor = float(xyjerk) / jerk; // always < 1.0!
CORELOOP
if (factor * max_f * 2.0 < xyjerk) {
// factor = xyjerk / (2.0 * max_f);
CORELOOP
}
}
//if (jerk > XYJERK) max_f = XYJERK * max_f / jerk;
//jerk = abs(fdz) ;
//if (jerk > ZJERK) max_f = ZJERK * max_f / jerk;
max_f = fmax(max_f * factor, MINCORNERSPEED);
CORELOOP
#ifdef output_enable
zprintf (PSTR("JERK:%d FACTOR:%f\n"), fi(jerk), ff(factor));
zprintf (PSTR("XMF:%d\n"), fi(max_f));
#endif
max_f *= max_f;
}
//max_f=20;
curr->maxs = fmin(curr->fn, lastf);
curr->maxs = fmin(curr->maxs, max_f);
#ifdef output_enable
zprintf(PSTR("maxs. %d\n"), ff(curr->maxs));
#endif
lastf = curr->fn;
//zprintf(PSTR(">> currfs,max %d %d\n"),fi(curr->fs),fi(curr->maxs));
backforward();
//zprintf(PSTR(">> currfs,max %d %d\n"),fi(curr->fs),fi(curr->maxs));
}
/*
=================================================================================================================================================
ADDMOVE
=================================================================================================================================================
Rutin menambahkan sebuah vektor ke dalam buffer gerakan
*/
int32_t x1[NUMAXIS], x2[NUMAXIS];
tmove *m;
#ifdef ISPC
float fctr, tick;
float tickscale, fscale, graphscale;
#endif
int32_t f;
float ta, acup, acdn, oacup, oacdn;
int32_t mctr, xtotalseg;
uint8_t fastaxis;
uint32_t nextmicros;
uint32_t nextdly;
uint32_t nextmotoroff;
float otx[NUMAXIS]; // keep the original coordinate before transform
int8_t repos = 0;
#ifdef USE_BACKLASH
int ldir[NUMAXIS] = {0, 0, 0, 0};
#endif
void addmove(float cf, float cx2, float cy2, float cz2, float ce02, int g0, int rel)
{
needbuffer();
#ifdef SHARE_EZ
if (cz2 != cz1) ce02 = ce01; // zeroing the E movement if Z is moving and ZE share direction pin
#endif
int32_t x2[NUMAXIS];
XYSCALING
if (head == tail) {
//zprintf(PSTR("Empty !\n"));
}
#ifdef output_enable
zprintf(PSTR("\n\nADDMOVE\nTail:%d Head:%d \n"), fi(tail), fi(head));
zprintf(PSTR("F:%f From X:%f Y:%f Z:%f\n"), ff(cf), ff(cx1), ff(cy1), ff(cz1));
zprintf(PSTR("To X:%f Y:%f Z:%f\n"), ff(cx2), ff(cy2), ff(cz2));
#endif
tmove *curr;
curr = &move[nextbuff(head)];
curr->status = g0 ? 8 : 0; // reset status:0 planstatus:0 g0:g0
if (rel) {
cx2 += cx1;
cy2 += cy1;
cz2 += cz1;
ce02 += ce01;
}
#ifdef ISPC
curr->col = 2 + (head % 4) * 4;
#endif
// this x2 is local
mmdis[0] = cx2 - cx1;
mmdis[1] = cy2 - cy1;
mmdis[2] = cz2 - cz1;
mmdis[3] = ce02 - ce01;
curr->dis = sqrt(sqr2(mmdis[0]) + sqr2(mmdis[1]) + sqr2(mmdis[2]) + sqr2(mmdis[3]));
#ifndef NONLINEAR
x2[0] = (int32_t)(cx2 * Cstepmmx(0)) - (int32_t)(cx1 * Cstepmmx(0)) ;
x2[1] = (int32_t)(cy2 * Cstepmmx(1)) - (int32_t)(cy1 * Cstepmmx(1)) ;
x2[2] = (int32_t)(cz2 * Cstepmmx(2)) - (int32_t)(cz1 * Cstepmmx(2)) ;
#else
x2[0] = (cx2 - cx1) * Cstepmmx(0);
x2[1] = (cy2 - cy1) * Cstepmmx(1);
x2[2] = (cz2 - cz1) * Cstepmmx(2);
#endif
CORELOOP
x2[3] = (ce02 - ce01) * Cstepmmx(3) * e_multiplier;
#if defined( DRIVE_COREXY)
// 2 = z axis + xy H-gantry (x_motor = x+y, y_motor = y-x)
// borrow cx1,cy1 for calculation
int32_t da = x2[0] + x2[1];
int32_t db = x2[1] - x2[0];
x2[0] = da;
x2[1] = db;
#elif defined(DRIVE_COREXZ)
// 8 = y axis + xz H-gantry (x_motor = x+z, z_motor = x-z)
int32_t da = x2[0] + x2[2];
int32_t db = x2[0] - x2[2];
x2[0] = da;
x2[2] = db;
#elif defined(DRIVE_XYYZ)
// copy dZ to dE and dY to dZ, for CNC with 2 separate Y axis at homing.
if (ishoming) {
// when homing the z will threat as normal cartesian Z that can be homing normally.
} else {
//
x2[3] = x2[2];
x2[2] = x2[1];
}
#elif defined(NONLINEAR)
// nothing to do
#endif
// if no axis movement then dont multiply by multiplier
if (g0 || ishoming || ((x2[0] == 0) && (x2[1] == 0) && (x2[2] == 0)) ) {} else cf *= f_multiplier;
#ifdef __AVR__
if (cf > 100)cf = 100; // prevent max speed
#endif
CORELOOP
curr->fn = cf; //curr->fn *= curr->fn;
curr->fs = 0;
//curr->planstatus = 0; //0: not optimized 1:fixed
//calculate delta
int32_t dd;
dd = 0;
int faxis = 0;
// calculate the delta, and direction
for (int i = 0; i < NUMAXIS; i++) {
#define delta x2[i]
#ifdef USE_BACKLASH
int dir;
if (delta < 0)dir = -1;
else if (delta > 0)dir = 1;
else dir = 0;
// if there is movement and have save last dir, and last dir <> current dir then add backlash
if ((ldir[i] != 0) && (dir != 0) && (ldir[i] != dir)) {
// add backlash steps to this axis
//zprintf(PSTR("backlash %d %d\n"),fi(i),fi(xback[i]));
// i think we should not doing backlash like this,
// we should directly add to cmd buffer with step delay is
delta += xback[i] * Cstepmmx(i) / 1000 * dir;
}
// if no movement, then dont save direction
if (dir != 0)ldir[i] = dir;
#endif
curr->dx[i] = delta;
delta = abs(delta);
if (delta > dd) {
dd = delta;
faxis = i;
}
}
CORELOOP
// if zero length then cancel
if (dd > MINSTEP) {
#ifdef output_enable
zprintf(PSTR("Totalstep AX%d %d\n"), (int32_t)faxis, (int32_t)curr->dx[faxis]);
#endif
curr->status |= faxis << 4;
curr->ac = 2 * (g0 ? mvaccel : accel);
//zprintf(PSTR("F:%f A:%d\n"), ff(cf), fi(curr->ac));
if (head == tail) {
otx[0] = cx1;
otx[1] = cy1;
otx[2] = cz1;
otx[3] = ce01;
curr->status |= 128;
}
// Laser
curr->laserval = laserOn ? constantlaserVal : 0;
head = nextbuff(head);
curr->status |= 1; // 0: finish 1:ready
// planner are based on cartesian coord movement on the motor
planner(head);
//#ifdef NONLINEAR
// we keep the original target coordinate, to get correct stop position when a HARD STOP performed
cx1 = curr->dtx[0] = cx2; // save the target, not the original
cy1 = curr->dtx[1] = cy2;
cz1 = curr->dtx[2] = cz2;
ce01 = curr->dtx[3] = ce02;
/*#else
cx1 = cx2;
cy1 = cy2;
cz1 = cz2;
ce01 = ce02;
#endif
*/
}
}
#define N_ARC_CORRECTION
#ifdef ARC_SUPPORT
/*
ARC using Float implementation
*/
uint32_t approx_distance(uint32_t dx, uint32_t dy)
{
uint32_t min, max, approx;
// If either axis is zero, return the other one.
if (dx == 0 || dy == 0) return dx + dy;
if ( dx < dy ) {
min = dx;
max = dy;
} else {
min = dy;
max = dx;
}
approx = ( max * 1007 ) + ( min * 441 );
if ( max < ( min << 4 ))
approx -= ( max * 40 );
// add 512 for proper rounding
return (( approx + 512 ) >> 10 );
}
void draw_arc(float cf, float cx2, float cy2, float cz2, float ce02, float fI, float fJ, uint8_t isclockwise)
{
#define debug0
uint32_t radius = approx_distance(labs(fI), labs(fJ));
// int acceleration_manager_was_enabled = plan_is_acceleration_manager_enabled();
// plan_set_acceleration_manager_enabled(false); // disable acceleration management for the duration of the arc
float cx = cx1 + fI ;
float cy = cy1 + fJ ;
#ifdef debug1
zprintf(PSTR("Arc I, J,R:%d,%d,%d\n"), fI, fJ, radius);
zprintf(PSTR("go cX cY:%d %d\n"), cx, cy);
#endif
//uint32_t linear_travel = 0; //target[axis_linear] - position[axis_linear];
float ne = ce01;
uint32_t extruder_travel = (ce02 - ce01) * Cstepmmx(3) * e_multiplier;
float r_axis0 = -fI; // Radius vector from center to current location
float r_axis1 = -fJ;
float rt_axis0 = cx2 - cx;
float rt_axis1 = cy2 - cy;
#ifdef debug1
sersendf_P(PSTR("go rX rY:%lq %lq\n"), r_axis0 * 1000, r_axis1 * 1000);
sersendf_P(PSTR("go rtX rtY:%lq %lq\n"), rt_axis0 * 1000, rt_axis1 * 1000);
#endif
// CCW angle between position and target from circle center. Only one atan2() trig computation required.
float angular_travel = atan2(r_axis0 * rt_axis1 - r_axis1 * rt_axis0, r_axis0 * rt_axis0 + r_axis1 * rt_axis1);
if ((!isclockwise && angular_travel <= 0.00001) || (isclockwise && angular_travel < -0.000001)) {
angular_travel += 2.0f * M_PI;
}
if (isclockwise) {
angular_travel -= 2.0f * M_PI;
}
uint32_t millimeters_of_travel = fabs(angular_travel) * radius; //hypot(angular_travel*radius, fabs(linear_travel));
if (millimeters_of_travel < 1) {
return;// treat as succes because there is nothing to do;
}
uint32_t segments = fmax(1, millimeters_of_travel >> 11);
float theta_per_segment = angular_travel / segments;
float extruder_per_segment = (extruder_travel) / segments;
float cos_T = 2.0 - theta_per_segment * theta_per_segment;
float sin_T = theta_per_segment * 0.16666667 * (cos_T + 4.0);
cos_T *= 0.5;
float sin_Ti;
float cos_Ti;
float r_axisi;
uint16_t i;
int8_t count = 0;
// Initialize the linear axis
//arc_target[axis_linear] = position[axis_linear];
// Initialize the extruder axis
for (i = 1; i < segments; i++) {
// Increment (segments-1)
if (count < N_ARC_CORRECTION) { //25 pieces
// Apply vector rotation matrix
r_axisi = r_axis0 * sin_T + r_axis1 * cos_T;
r_axis0 = r_axis0 * cos_T - r_axis1 * sin_T;
r_axis1 = r_axisi;
count++;
} else {
// Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
// Compute exact location by applying transformation matrix from initial radius vector(=-offset).
cos_Ti = cos(i * theta_per_segment);
sin_Ti = sin(i * theta_per_segment);
r_axis0 = -fI * cos_Ti + fJ * sin_Ti;
r_axis1 = -fI * sin_Ti - fJ * cos_Ti;
count = 0;
}
// Update arc_target location
float nx = cx + r_axis0;
float ny = cy + r_axis1;
ne += extruder_per_segment;
//move.axis[E] = extscaled>>4;
addmove(cf, nx, ny, cz2, ne);
}
// Ensure last segment arrives at target location.
addmove(cf, cx2, cy2, cz2, ce02);
}
#endif
#ifdef NONLINEAR
void calculate_delta_steps();
#endif
static uint32_t cmdly;
int jerkctr = 0;
#ifdef ISPC
float xs[4] = {0, 0, 0, 0};
float gx, gy, lx, ly;
int pcsx[4];
#define graphstep(ix) xs[ix] +=pcsx[ix]
void dographics()
{
if (cmdly < DIRDELAY) {
zprintf(PSTR("Odd delay:%d\n"), cmdly);
return;
}
// this might be wrong because the last cmd maybe is from previous segment which have different step/mm
f = stepdiv / cmdly;
//f = sqrt(ta);
//f = sqrt(ta)/stepdiv2;
tick = tick + cmdly; //1.0/timescale;
int32_t c;
// color by segment
c = (tail & 3) + 10;
if (jerkctr > 0)c = 1;
// color by speed
//c = (f - 20) * 4;
//float cf = float(timescale) / dl;
//pset (tick*tickscale+10,400-f*fscale),c
#define realpos1(i) (xs[i] / stepmmx[i])
if (tick * tickscale / timescale > 600) {
gx = 0;
tick = 0;
}
//putpixel (tick * tickscale / timescale + 30, 450 - fscale * cf, c - 8);
lx = gx;
ly = gy;
gx = tick * tickscale / timescale + 10;
gy = 480 - fscale * f * 0.1;
setcolor(c);
putpixel (gx, gy, c);
//line(lx, ly, gx, gy);
//zprintf(PSTR("X:%f Y:%f\n"), ff(gx), ff(gy));
setcolor(0);
line(gx + 1, 480 - 1, gx + 1, 480 - 100);
gy = 480 - fscale * 100 * 0.1;
setcolor(1);
line(0, gy, 200, gy);
#ifdef NONLINEAR
float ex = realpos1(0) * graphscale;
float ey = realpos1(1) * graphscale;
float ez = realpos1(2) * graphscale;
#if defined( DRIVE_DELTASIAN)
circle (150, 251 - ex + 0, 5);
circle (350, 251 - ez + 0, 5);
circle (251 + ey * 0.1, 251 + ey * 0.1 + 0, 5);
circle (150, 249 - ex + 0, 5);
circle (350, 249 - ez + 0, 5);
circle (249 + ey * 0.1, 249 + ey * 0.1 + 0, 5);
setcolor(9);
circle (150, 250 - ex + 0, 5);
setcolor(12);
circle (350, 250 - ez + 0, 5);
setcolor(14);
circle (250 + ey * 0.1, 250 + ey * 0.1 + 0, 5);
#elif defined( DRIVE_DELTA)
circle(150, 251 + ex + 0, 5);
circle (350, 251 + ey + 0, 5);
circle (250, 201 + ez + 0, 5);
circle (150, 249 + ex + 0, 5);
circle (350, 249 + ey + 0, 5);
circle (250, 199 + ez + 0, 5);
setcolor(9);
circle (150, 250 + ex + 0, 5);
setcolor(12);
circle (350, 250 + ey + 0, 5);
setcolor(14);
circle (250, 200 + ez + 0, 5);
#endif
#else
float ex = realpos1(0) * graphscale;
float ey = realpos1(1) * graphscale;
float ez = realpos1(2) * graphscale;
//putpixel (ex + 320, ey + 150, c);
putpixel (ex + ey * 0.3 + 320, ey * 0.3 - ez + 150, c);
#endif
}
#else
#define graphstep(ix)
#endif
/*
=================================================================================================================================================
MOTIONLOOP
=================================================================================================================================================
*/
void otherloop(int r);
uint32_t cm, ocm, mctr2, dlmin, dlmax;
int32_t timing = 0;
/*
=================================================================================================================================================
COMMAND BUFFER
=================================================================================================================================================
*/
#define NUMCMDBUF 70
#define nextbuffm(x) ((x) < NUMCMDBUF-1 ? (x) + 1 : 0)
static volatile uint32_t cmddelay[NUMCMDBUF], cmd0;
static volatile uint8_t cmhead = 0, cmtail = 0, cmcmd, cmbit = 0;
static volatile int cmdlaserval = 0;
static int8_t mo = 0;
#define cmdfull (nextbuffm(cmhead)==cmtail)
#define cmdnotfull (nextbuffm(cmhead)!=cmtail)
#define cmdempty (cmhead==cmtail)
static volatile int nextok = 0, laserwason = 0;
int sendwait = 0;
static THEISR void decodecmd()
{
if (cmdempty) {
return;
}
uint32_t cmd = cmddelay[cmtail];
cmcmd = cmd & 1;
if (cmcmd) {
cmbit = (cmd >> 1) & 15;
// inform if non move is in the buffer
//if (cmcmd && (cmbit==0))zprintf(PSTR("X"));
cmdly = (cmd >> 5) >> DSCALE;
} else {
cmbit = (cmd >> 1) & 255;
cmdly = DIRDELAY >> DSCALE;
cmdlaserval = (cmd >> 9) >> DSCALE;
//zprintf(PSTR("int %d\n"), fi(cmdlaserval));
}
/*Serial.print("X ");
Serial.print(cmd);
Serial.print(":");
Serial.print(cmdly);
Serial.print(":");
Serial.println(cmdlaserval);
*/
nextok = 1;
cmtail = nextbuffm(cmtail);
#ifdef USETIMER1
timer_set(cmdly);
#ifdef LASERMODE
if (Setpoint == 0) {
if (cmcmd) {
//zprintf(PSTR("%d\n"), fi(cmdlaserval));
laserwason = cmdlaserval > 0;
if (laserwason) {
// if laserval is 255 then we know its the full power / cutting
if ((cmdlaserval < 255)) {
int las = cmdlaserval * (CLOCKCONSTANT / 1000000);
//zprintf(PSTR("int %d\n"), fi(las));
//delayMicroseconds(las);
//digitalWrite(laser_pin,LOW);
//timer_set(cmdly-las*(CLOCKCONSTANT / 1000000));
timer_set2(cmdly, las);
}// else
digitalWrite(laser_pin, laserwason);
} else digitalWrite(laser_pin, LOW);
}
}
#endif
#endif
}
uint32_t mc, dmc, cmctr;
void THEISR coreloopm()
{
if (PAUSE) {
#ifdef USETIMER1
timer_set(1000);
#endif
return;
}
//dmc=(micros()-mc); mc=micros();
if (!nextok) {
decodecmd();
//return;
if (!nextok) return;
}
#ifdef USETIMER1
{
#elif defined(ISPC)
{
#else
cm = micros();
if (cm - nextmicros >= cmdly) {
nextmicros = cm;
#endif
if (cmcmd) { // 1: move
if (cmbit & 8) {
ectstep++;
motor_3_STEP();
}
if (cmbit & 1) {
cmctr++;
xctstep++;
motor_0_STEP();
}
if (cmbit & 2) {
yctstep++;
motor_1_STEP();
}
if (cmbit & 4) {
zctstep++;
motor_2_STEP();
}
pinCommit();
//somedelay(1) ;
motor_0_UNSTEP();
motor_1_UNSTEP();
motor_2_UNSTEP();
motor_3_UNSTEP();
pinCommit();
//STEPDELAY ;
#ifdef ISPC
if (cmbit & 1)graphstep(0);
if (cmbit & 2)graphstep(1);
if (cmbit & 4)graphstep(2);
if (cmbit & 8)graphstep(3);
dographics();
#endif
if (checkendstop) { // check endstop every 30 step
if ((xctstep >= xcheckevery) || (yctstep >= ycheckevery) || (zctstep >= zcheckevery) || (ectstep >= echeckevery) ) {
xctstep = yctstep = zctstep = ectstep = 0;
docheckendstop();
if (endstopstatus < 0) {
cmtail = cmhead;
nextok = 0;
return; // no more move and clear cmdbuffer if endstop hit/
}
}
}
} else { // 0: set dir
if (cmbit & 2) motor_0_DIR((cmbit & 1) ? -1 : 1);
if (cmbit & 8) motor_1_DIR((cmbit & 4) ? -1 : 1);
if (cmbit & 32) motor_2_DIR((cmbit & 16) ? -1 : 1);
if (cmbit & 128) motor_3_DIR((cmbit & 64) ? -1 : 1);
pinCommit();
#ifdef ISPC
pcsx[0] = (cmbit & 1) ? 1 : -1;
pcsx[1] = (cmbit & 4) ? 1 : -1;
pcsx[2] = (cmbit & 16) ? 1 : -1;
pcsx[3] = (cmbit & 64) ? 1 : -1;
#endif
}
// next command
nextok = 0;
decodecmd();
}
}
//
/* idea:
merge a non move
*/
int ldelay = 0;
static void pushcmd()
{
// wait until a buffer freed
while (cmdfull) {
#ifdef USETIMER1
MEMORY_BARRIER();
#endif
CORELOOP
}
// if move cmd, and no motor move, save the delay
if ( (cmd0 & 1) && !(cmd0 & (15 << 1))) {
ldelay += cmd0 >> 5;
} else {
cmhead = nextbuffm(cmhead);
cmddelay[cmhead] = cmd0 + (ldelay << 5);
ldelay = 0;
}
}
void newdircommand(int laserval)
{
// change dir command
cmd0 = 0;//DIRDELAY << 6;
cmd0 |= (laserval << 9);
if (sx[0] > 0)cmd0 |= 2;
if (sx[1] > 0)cmd0 |= 8;
if (sx[2] > 0)cmd0 |= 32;
if (sx[3] > 0)cmd0 |= 128;
// TO know whether axis is moving
if (bsdx[0] > 0)cmd0 |= 4;
if (bsdx[1] > 0)cmd0 |= 16;
if (bsdx[2] > 0)cmd0 |= 64;
if (bsdx[3] > 0)cmd0 |= 256;
ldelay = 0;
pushcmd();
}
/* ================================================================================================================
BRESENHAM CORE
this need to move to interrupt for smooth movement
================================================================================================================
*/
#define bresenham(ix)\
if ((mcx[ix] -= bsdx[ix]) < 0) {\
cmd0 |=2<<ix;\
mcx[ix] += totalstep;\
}
#ifdef INTERPOLATEDELAY
#define CALCDELAY dl = ((dl<<4)+(dlp-dl))>>4; // hack, linear interpolation of the delay
//#define CALCDELAY dl = (dlp+dl)>>1; // hack, linear interpolation of the delay
#else
#define CALCDELAY dl = dlp;
#endif
// ===============================
float _ac = 0;
float lastac = 0;
float jerkv = 0;
float pta = 0;
int coreloop1()
{
#ifdef output_enable
if (mctr == 10)zprintf(PSTR("DLY:%d \n"), fi(cmdly));
#else
//if(mctr==10)zprintf(PSTR("DLY:%d \n"), fi(cmdly));
#endif
if (!m || (mctr <= 0)) {
return 0;
}
if (cmdfull) {
//zprintf(PSTR("F\n"));
} else {
cmd0 = 1; //step command
bresenham(0);
bresenham(1);
bresenham(2);
bresenham(3);
// next speed
float newac = 0;
if ((rampup -= rampv) > 0) {
newac = acup;
// _ac = acup;
} else if ((rampdown -= rampv) < 0) {
newac = acdn;
// _ac = acdn;
}
if (lastac != newac) {
// calculate jerk value
#ifdef JERKSTEP
if (mctr > JERKSTEP) {
jerkv = (newac - lastac) / JERKSTEP;
jerkctr = JERKSTEP;
} else
#endif
_ac = newac;
lastac = newac;
//zprintf(PSTR("jerkv %f\n"),ff(jerkv));
}
// // calculate new delay only if we accelerating
UPDATEDELAY:
if (jerkctr-- > 0) {
_ac += jerkv;
//zprintf(PSTR("ac %f\n"),ff(_ac));
}
if (_ac) {
ta += _ac;
if (ta < 0.05)ta = 0.05;
//zprintf(PSTR("%d\n"),fi(ta));
// if G0 update delay not every step to make the motor move faster
//if (m->status & 8) {
#ifdef UPDATE_F_EVERY
nextdly += dl;
if (nextdly > UPDATE_F_EVERY) {
nextdly -= UPDATE_F_EVERY;
dlp = xInvSqrt(ta); //*F_SCALE;
};
#else
dlp = xInvSqrt(ta); //*F_SCALE;
#endif
} else dlp = dln; //
CALCDELAY
cmd0 |= (dl) << 5;
if (mctr < 20) {
///*
//zprintf(PSTR("V:%f DL:%d\n"),ff(ta),fi(dl));
//Serial.print(":");
//Serial.println(dl);
//*/
}
pushcmd();
mctr--;
CORELOOP
//if (mctr == 0)zprintf(PSTR("\n"));
#ifdef output_enable
//zprintf(PSTR("Rampv:%f \n"), ff(rampv));
//zprintf(PSTR("%d "), dl);
//zprintf(PSTR("MCTR:%d \n"), mctr);
// write real speed too
dlmin = fmin(dl, dlmin);
dlmax = fmax(dl, dlmax);
if (mctr2++ % 29 == 0) {
//zprintf(PSTR("%f "), ff(sqrt(ta)));
//zprintf(PSTR("%d "), dl);
//zprintf(PSTR("RU:%f RD:%f \n"), ff(rampup), ff(rampdown));
//printf(PSTR("D:%d RD:%f "), ff(rampup), ff(rampdown));
//zprintf(PSTR("dmin:%d dmax:%d "), fi(dlmin), fi(dlmax));
//zprintf(PSTR("Fmin:%d Fmax:%d\n"), fi(stepdiv / dlmax), fi(stepdiv / dlmin));
//zprintf(PSTR("F:%d\n"), fi(stepdiv/dlmin));
dlmin = 1000000;
dlmax = 0;
}
#endif
#ifndef ISPC
//if (mctr % 10 == 0)zprintf(PSTR("%d "), fi(mctr));
//if (mctr % 4 == 0) zprintf(PSTR("F:%d "), fi(stepdiv/dl));
//if (mctr2++ % 20 == 0) Serial.println("");
#endif
// if (mctr % 10 == 0)zprintf(PSTR("endstp %d\n"),fi(checkendstop));
if (checkendstop || (!RUNNING)) {
// docheckendstop();
//zprintf(PSTR("%d \n"),fi(mctr));
if ((endstopstatus < 0) || (!RUNNING)) {
//zprintf(PSTR("Endstop hit"));
if (!RUNNING) {
// need to calculate at least correct next start position based on
// mctr
#ifdef HARDSTOP
float p = mctr;
p /= totalstep;
//p=1-p;
cx1 = m->dtx[0] - p * m->dx[0] / Cstepmmx(0);
cy1 = m->dtx[1] - p * m->dx[1] / Cstepmmx(1);
cz1 = m->dtx[2] - p * m->dx[2] / Cstepmmx(2);
ce01 = m->dtx[3] - p * m->dx[3] / Cstepmmx(3);
zprintf(PSTR("Stopped!\n"));
#endif
}
endstopstatus = 0;
m->status = 0;
mctr = 0;
m = 0;
head = tail;
//cmhead=cmtail;
RUNNING = 1;
return 0;
}
}
return 1;
}
return 0;
}
int busy = 0;
// ===============================================
int cctr = 0;
int motionloop()
{
if (cctr++ > 100000) {
cctr = 0;
//Serial.println(ndelay);
}
if (busy ) {
zprintf(PSTR("Busy\n"));
return 0;
}
busy = 1;
CORELOOP
int r;
if (!m ) r = startmove();
else {
r = coreloop1();
//if (mctr > 0)
}
// for auto start motion when idle
otherloop(r);
busy = 0;
return r;
}
void otherloop(int r)
{
cm = micros();
// NON TIMER
// zprintf(PSTR("%d\n"),fi(dmc));
if (m) {
nextmotoroff = cm;
if (mctr == 0) {
#ifdef NONLINEAR
// delta need to check if totalseg
if (xtotalseg > 0) {
// next segment
// calculate next bresenham
calculate_delta_steps();
} else
#endif //delta
{
// coreloop ended, check if there is still move ahead in the buffer
//zprintf(PSTR("Finish:\n"));
m->status = 0;
//if (m->fe == 0)f = 0;
m = 0;
r = startmove();
}
}
}
#ifndef ISPC
// this both check take 8us
temp_loop(cm);
#ifdef motortimeout
if (!m && (cm - nextmotoroff >= motortimeout)) {
nextmotoroff = cm;
power_off();
}
#endif // motortimeout
#ifdef ESP8266
feedthedog();
#endif
#endif // ispc
}
/*
=================================================================================================================================================
STARTMOVE
=================================================================================================================================================
Mulai menjalankan 1 unit di buffer gerakan terakhir
*/
int subp = 1, laxis;
//float ts;
float xc[NUMAXIS];
int32_t estep;
// this part must calculated in parts to prevent single long delay
//=================================================================================================================
void calculate_delta_steps()
{
#ifdef NONLINEAR
#ifdef ISPC
//zprintf(PSTR("\nSEG PRECALC %d\n"), s);
#endif
// STEP 1
xtotalseg --;
memcpy(xc, m->dtx, sizeof xc);
memcpy(x1, x2, sizeof x1);
// STEP 2
if (xtotalseg) {
#define PSEGMENT(i) xc[i] -= xtotalseg * sgx[i];
PSEGMENT(0)
PSEGMENT(1)
PSEGMENT(2)
PSEGMENT(3)
}
// STEP 3
transformdelta(xc[0], xc[1], xc[2], xc[3]);
// STEP 4
// ready for movement
totalstep = 0;
for (int i = 0; i < 4; i++) {
int32_t d = x2[i] - x1[i];
if (d < 0) {
bsdx[i] = -d;
sx[i] = -1;
} else {
bsdx[i] = d;
sx[i] = 1;
}
totalstep = fmax(bsdx[i], totalstep);
}
// modify the sx?? m->mcx and totalstep for this segment
// STEP 5 FINAL
mcx[0] = mcx[1] = mcx[2] = mcx[3] = 0;
// convert from virtual step/mm value to original step/mm value
stepdiv2 = wstepdiv2 * rampv;
acup = oacup * rampv;
acdn = oacdn * rampv;
#ifdef output_enable
//zprintf(PSTR("\nX:%d %d %d \n"), fi(bsdx[0]), fi(bsdx[1]), fi(bsdx[2]));
//zprintf(PSTR("Segm:%d Step:%d rampv:%f\n"), fi(xtotalseg), fi(totalstep), ff(rampv));
#endif
#else // nonlinear
for (int i = 0; i < 4; i++) {
if (m->dx[i] > 0) {
bsdx[i] = (m->dx[i]);
sx[i] = 1;
} else {
bsdx[i] = -(m->dx[i]);
sx[i] = -1;
}
}
#endif // nonlinear
// lets do the subpixel thing.
// calculate the microseconds betwen step,
dln = xInvSqrt((m->fn ));
#ifdef SUBPIXELMAX
int u;
for (u = 2; u <= (SUBPIXELMAX); u++) {
if (LOWESTDELAY * u > dln) {
break;
}
}
u--;
subp = u;
//zprintf(PSTR("Subpixel %d %d ->"),fi(u),fi(dln));
if (u > 1) {
totalstep *= u;
acup /= u;
acdn /= u;
stepdiv2 /= u;
stepdiv /= u;
dln /= u;
//if (m->laserval < 255)m->laserval = m->laserval / u + 1;
#ifdef NONLINEAR
rampv /= u;
#endif
}
//zprintf(PSTR(" %d\n"),fi(dln));
#endif
//
mctr = totalstep ;
newdircommand(!isG0 ? m->laserval : 0);
#ifdef ISPC
fctr = 0;
m->col++;
#endif
}
int32_t startmove()
{
if (cmdfull)return 0;
if ((head == tail)) {
//Serial.println("?");
//m = 0; wm = 0; mctr = 0; // thi cause bug on homing delta
if (!sendwait && (cmdempty)) {
// send one time, is buffer is emspy after running
#ifdef LASERMODE
if (Setpoint == 0) {
digitalWrite(laser_pin, LOW);
laserwason = 0;
}
#endif
zprintf(PSTR("wait\n"));
sendwait = 1;
}
return 0;
}
sendwait = 0;
// last calculation
if (m ) return 0; // if empty then exit
#ifdef output_enable
zprintf(PSTR("\nSTARTMOVE\n"));
#endif
// STEP 1
int t = nextbuff(tail);
// prepare ramp (for last move)
prepareramp(t);
m = &move[t];
isG0 = m->status & 8;
laxis = fastaxis;
fastaxis = FASTAXIS(m);
totalstep = labs(m->dx[fastaxis]);
// recalculate acceleration for up and down, to minimize rounding error
acup = acdn = 0;
// 24-4-2018
// Now need to convert mm rampup to step rampup
if (rampup)acup = float((m->fn - m->fs )) / rampup; //(fmax(1,m->rampup-acramp));
if (rampdown)acdn = -float((m->fn - fe )) / rampdown; //(fmax(1,m->rampdown-acramp));
oacup = acup;
oacdn = acdn;
#ifdef NONLINEAR
// DELTA HERE
//STEP
// if homing or just z move then no segmentation
if (SINGLESEGMENT) xtotalseg = 1;
else {
xtotalseg = 1 + (( STEPSEGMENT ) / STEPPERSEGMENT);
}
// if from halt, then need to transform first point, if not then next first point is previous point
if (m->status & 128) {
transformdelta(otx[0], otx[1], otx[2], otx[3]);
}
// STEP
ts = 1.f / (xtotalseg);
rampseg = (float)(totalstep) * ts;
ts *= IFIXED2;
#define CSGX(i) sgx[i] = float(m->dx[i]) * ts;
CSGX(0)
CSGX(1)
CSGX(2)
CSGX(3)
#ifdef output_enable
zprintf(PSTR("\nTotalSeg:%d RampSeg:%f Sx:%f Sy:%f Sz:%f\n"), fi(xtotalseg), ff(rampseg), ff(sgx[0]), ff(sgx[1]), ff(sgx[2]));
zprintf(PSTR("Dx:%d Dy:%d Dz:%d\n"), fi(m->dtx[0]), fi(m->dtx[1]), fi(m->dtx[2]));
#endif
#endif
// STEP
ta = m->fs ;
stepdiv = CLOCKCONSTANT / (Cstepmmx(fastaxis));
stepdiv2 = wstepdiv2 = stepdiv;
m->status &= ~3;
m->status |= 2;
if (f == 0) nextmicros = micros();// if from stop
#ifdef output_enable
zprintf(PSTR("SUB:%d FS:%f TA:%f FE:%f RAMP:%d %d ACC:%f %f\n"), fi(subp), ff(m->fs), ff(m->fn), ff(fe), fi(rampup), fi(rampdown), ff(acup), ff(acdn));
#endif
// rampup = m->rampup ;
rampdown = totalstep - rampup - rampdown ;
mctr2 = mcx[0] = mcx[1] = mcx[2] = mcx[3] = 0; //mctr >> 1;
tail = t;
#ifdef output_enable
/*
zprintf(PSTR("Start tail:%d head:%d\n"), fi(tail), fi(head));
zprintf(PSTR("RU:%d Rd:%d Ts:%d\n"), fi(rampup), fi(rampdown), fi(totalstep));
zprintf(PSTR("FS:%f FN:%f AC:%f \n"), ff(m->fs), ff(m->fn), ff(m->ac));
zprintf(PSTR("TA,ACUP,ACDN:%d,%d,%d \n"), fi(ta), fi(acup), fi(acdn));
zprintf(PSTR("DX:%d DY:%d DZ:%d DE:%d \n"), fi(m->dx[0]), fi(m->dx[1]), fi(m->dx[2]), fi(m->dx[3]));
*/
//zprintf(PSTR("Last %f %f %f \n"), ff(px[0] / stepmmx[0]), ff(px[1] / stepmmx[0]), ff(px[2] / stepmmx[0]));
//zprintf(PSTR("sx %d %d %d \n"), fi(sx[0]), fi(sx[1]), fi(sx[2]));
//zprintf(PSTR("Status:%d \n"), fi(m->status));
#endif
calculate_delta_steps();
#ifdef SUBPIXELMAX
rampup *= subp;
rampdown *= subp;
#endif
dlp = xInvSqrt(ta);
return 1;
}
/*
=================================================================================================================================================
DOCHECKENDSTOP
=================================================================================================================================================
*/
#ifdef INVERTENDSTOP
#define ENDCHECK !
#else
#define ENDCHECK
#endif
#define ENDPIN INPUT_PULLUP
void docheckendstop()
{
// AVR specific code here
// read end stop
#ifndef ISPC
#ifdef limit_pin
int nc = 0;
endstopstatus = 0;
for (int d = 0; d < 3; d++) {
if (ENDCHECK dread(limit_pin))nc++;
}
if (nc > 1)endstopstatus = -1;
#endif
#else
// PC
#endif
}
/*
=================================================================================================================================================
HOMING
=================================================================================================================================================
*/
void homing()
{
// clear buffer
addmove(100, 0, 0, cz1, ce01);
waitbufferempty();
ishoming = 1;
cx1 = 0;
cy1 = 0;
cz1 = 0;
ce01 = 0;
x2[0] = x2[1] = x2[2] = x2[3] = 0;
int32_t stx[NUMAXIS];
// stx[0] = stx[1] = stx[2] = stx[3] = 0;
int32_t tx[NUMAXIS];
// tx[0] = tx[1] = tx[2] = tx[3] = 0;
#define mmax HOMING_MOVE
#define smmax ENDSTOP_MOVE
int vx[4] = { -1, -1, -1, -1};
for (int t = 0; t < NUMAXIS; t++) {
if (ax_home[t] > 1)vx[t] = 1;
if (ax_home[t] < 1)vx[t] = 0;
tx[t] = mmax * vx[t];
stx[t] = smmax * vx[t];
}
// fast check every 31 step
//zprintf(PSTR("Homing to %d %d %d\n"), tx[0], tx[1], tx[2]);
// move away before endstop
#ifdef DRIVE_XYYZ
checkendstop = 0;
addmove(homingspeed, -stx[0], -stx[1], -stx[2], -stx[3], 1, 1);
waitbufferempty();
checkendstop = 31;
addmove(homingspeed, 0, tx[1], tx[2], 0, 1, 1);
waitbufferempty();
checkendstop = 0;
addmove(homingspeed, 0, -stx[1], -stx[2], 0, 1, 1);
waitbufferempty();
checkendstop = 31;
addmove(homingspeed, tx[0], 0, 0, tx[3], 1, 1);
#else
checkendstop = 31;
addmove(homingspeed, tx[0], tx[1], tx[2], tx[3], 1, 1);
#endif
// now slow down and check endstop once again
waitbufferempty();
float xx[NUMAXIS];
#define moveaway(e,F) {\
if (vx[e]) {\
xx[0]=xx[1]=xx[2]=xx[3]=0;\
xx[e] = - stx[e];\
checkendstop = 0;\
addmove(F, xx[0], xx[1], xx[2], xx[3],1,1);\
waitbufferempty();\
}\
}
#define xcheckendstop(e,F) {\
xx[0] = xx[1] = xx[2] = 0; \
xx[e] = tx[e]; \
addmove(F, xx[0], xx[1], xx[2], xx[3], 1, 1); \
checkendstop = 1; \
waitbufferempty(); \
xx[e] = - stx[e] + axisofs[e]; \
addmove(F, xx[0], xx[1], xx[2], xx[3], 1, 1); \
checkendstop = 0; \
waitbufferempty(); \
}
for (int e = 0; e < NUMAXIS; e++) {
moveaway(e, homingspeed);
}
for (int e = 0; e < NUMAXIS; e++) {
if (vx[e]) {
// check endstop again fast
xcheckendstop(e, 25);
xcheckendstop(e, 15);
}
}
checkendstop = ce01 = 0;
#ifdef NONLINEAR
NONLINEARHOME
#else // NONLINEAR
if (vx[0] > 0) cx1 = ax_home[0];
else cx1 = 0;
if (vx[1] > 0) cy1 = ax_home[1];
else cy1 = 0;
if (vx[2] > 0) cz1 = ax_home[2];
else cz1 = 0;
#endif // NONLINEAR
//zprintf(PSTR("Home to:X:%f Y:%f Z:%f\n"), ff(cx1), ff(cy1), ff(cz1));
ishoming = 0;
init_pos();
}
/*
=================================================================================================================================================
WAITBUFFEREMPTY
=================================================================================================================================================
waitbufferempty
Proses semua gerakan di buffer, dan akhiri dengan deselerasi ke 0
*/
void waitbufferempty()
{
//if (head != tail)prepareramp(head);
startmove();
#ifdef output_enable
zprintf(PSTR("Wait %d\n"), fi(mctr));
#endif
MEMORY_BARRIER()
LOOP_IN(2)
domotionloop
while ((head != tail) || m) { //(tail == otail) //
domotionloop
servo_loop();
MEMORY_BARRIER()
//zprintf(PSTR("->%d\n"), fi(mctr));
}
LOOP_OUT(2)
#ifdef output_enable
zprintf(PSTR("Empty"));
#endif
}
/*
=================================================================================================================================================
NEEDBUFFER
=================================================================================================================================================
loop sampai da buffer yang bebas
*/
void needbuffer()
{
if (nextbuff(head) == tail) {
#ifdef output_enable
zprintf(PSTR("Wait %d / %d \n"), fi(tail), fi(head));
#endif
//wait current move finish
int t = tail;
LOOP_IN(3)
MEMORY_BARRIER()
while (t == tail) {
domotionloop
servo_loop();
MEMORY_BARRIER()
//zprintf(PSTR("%d\n"), fi(mctr));
}
//zprintf(PSTR("Done\n"));
LOOP_OUT(1)
#ifdef output_enable
zprintf(PSTR("Done %d / %d \n"), fi(tail), fi(head));
#endif
}
}
void faildetected()
{
#ifdef POWERFAILURE
// save the print last line only if printing using SDCARD
if (sdcardok == 2) {
motor_0_OFF();
motor_1_OFF();
motor_2_OFF();
motor_3_OFF();
setfan_val(0);
set_temp(0);
// save last gcode in eeprom
eepromwrite(EE_lastline, fi(lineprocess));
delay(1000);
checkendstop = 31;
//void addmove(float cf, float cx2, float cy2, float cz2, float ce02, int g0, int rel)
addmove(200, -2000, 0, 0, 0, 1, 1);
waitbufferempty();
}
#endif
}
/*
=================================================================================================================================================
initmotion
=================================================================================================================================================
inisialisasi awal, wajib
*/
void init_pos()
{
}
void initmotion()
{
#ifdef __ARM__
disableDebugPorts();
#endif
reset_motion();
preparecalc();
dl = 5000;
#ifdef ISPC
tickscale = 60;
fscale = 2;
graphscale = 4;
#endif
motor_0_INIT();
motor_1_INIT();
motor_2_INIT();
motor_3_INIT();
motor_0_INIT2();
motor_1_INIT2();
motor_2_INIT2();
motor_3_INIT2();
#ifndef ISPC
#ifdef POWERFAILURE
pinMode(powerpin, INPUT_PULLUP);
attachInterrupt(powerpin, faildetected, CHANGE);
#endif
#ifdef LASERMODE
pinMode(laser_pin, OUTPUT);
digitalWrite(laser_pin, LOW);
#endif
#ifdef limit_pin
pinMode(limit_pin, ENDPIN);
#endif
pinMotorInit
#endif
}
<file_sep>/karya34m/motors.h
#include "motion.h"
#include<stdint.h>
#ifndef MOTOR_H
#define MOTOR_H
#include "config_pins.h"
#ifndef ISPC
#include<arduino.h>
#else
#include <stdlib.h>
#endif
static int8_t lsx[4] = {0, 0, 0, 0};
#ifndef ISPC
#if defined(USEDIO) && defined(__AVR__)
#include <DIO2.h>
#define dwrite(pin,v) digitalWrite2(pin,v)
#define dread(pin) digitalRead2(pin)
#define pinmode(pin,m) pinMode2(pin,m)
#else
#define dwrite(pin,v) digitalWrite(pin,v)
#define dread(pin) digitalRead(pin)
#define pinmode(pin,m) pinMode(pin,m)
#endif
#endif //ispc
#ifdef USE_SHIFTREG
static byte srdata = 0;
#define xdigitalWrite(pin,v) if(v)srdata|=1 << pin;else srdata &=~(1 << pin);
//#define pinCommit() digitalWrite(pinlatch,LOW);shiftOut(pindata,pinclock,MSBFIRST,srdata);digitalWrite(pinlatch,HIGH);
//Fast shiftout ESP8266 D0 as LATCH
#ifdef ESP8266
#define pinH(pin) GPOS = (1 << pin)
#define pinL(pin) GPOC = (1 << pin)
static void pinCommit() {
// USE D0 as latch
GP16O |= 1;
#define pushbit(i)if (srdata&i)pinH(pindata);else pinL(pindata);pinL(pinclock);pinH(pinclock);
//GP16O |= 1;GP16O &= ~1;
for (int i = 7; i >= 0; i--) {
pushbit(1 << i);
}
GP16O &= ~1;
}
#endif
#define xpinMode(p,v)
#define pinMotorInit pinMode(pindata,OUTPUT);pinMode(pinlatch,OUTPUT);pinMode(pinclock,OUTPUT);
#else
#define xpinMode(p,v) pinmode(p,v)
#define xdigitalWrite(p,v) dwrite(p,v)
#define pinMotorInit
#define pinCommit()
#endif
#define DUMMYMOTOR(AX,PENABLE,PDIR,PSTEP)\
inline void motor_##AX##_INIT(){}\
inline void motor_##AX##_INIT2(){}\
inline void motor_##AX##_ON(){}\
inline void motor_##AX##_OFF() {}\
inline void motor_##AX##_DIR(int d){}\
inline void motor_##AX##_STEP(){}\
inline void motor_##AX##_UNSTEP(){}
#ifndef ISPC
static uint8_t bsteps = 0;
#define STEPDELAY
//somedelay(10);
#define STEPDIRDELAY
//somedelay(10);
#define MOTOR(AX,PDIR,PSTEP)\
inline void motor_##AX##_INIT(){xpinMode(PDIR, OUTPUT);xpinMode(PSTEP, OUTPUT);}\
inline void motor_##AX##_STEP(){ xdigitalWrite(PSTEP,1);}\
inline void motor_##AX##_UNSTEP(){ xdigitalWrite(PSTEP,0);}\
inline void motor_##AX##_DIR(int d){ if(!d)return;motor_##AX##_ON();xdigitalWrite(PDIR,(d*MOTOR_##AX##_DIR)>0?1:0);STEPDIRDELAY;}\
#define MOTOREN(AX,PENABLE)\
inline void motor_##AX##_ON() { xdigitalWrite(PENABLE,0);}\
inline void motor_##AX##_OFF() { xdigitalWrite(PENABLE,1);}\
inline void motor_##AX##_INIT2() {xpinMode(PENABLE, OUTPUT);xdigitalWrite(PENABLE,1);}\
#define MOTOREN0(AX)\
inline void motor_##AX##_ON(){}\
inline void motor_##AX##_OFF() {}\
inline void motor_##AX##_INIT2() {}\
/*
#else
#define STEPDELAY
#define STEPDIRDELAY
// PC just use dummy
#define MOTOR(AX,PDIR,PSTEP)\
inline void motor_##AX##_INIT(){zprintf(PSTR("Motor ##AX## Init\n"));}\
inline void motor_##AX##_STEP(){ zprintf(PSTR("Motor ##AX## step\n"));}\
inline void motor_##AX##_UNSTEP(){ zprintf(PSTR("Motor ##AX## unstep"\n));}\
inline void motor_##AX##_DIR(int d){ zprintf(PSTR("Motor ##AX## Dir %d\n"),d);}\
#define MOTOREN(AX,PENABLE)\
inline void motor_##AX##_ON(){ zprintf(PSTR("Motor ##AX## Enable\n"));}\
inline void motor_##AX##_OFF() { zprintf(PSTR("Motor ##AX## Disable\n"));}\
*/
#endif
#ifdef xstep
#ifdef xenable
MOTOREN(0, xenable)
#else
MOTOREN0(0)
#endif
MOTOR(0, xdirection, xstep)
#else
DUMMYMOTOR(0, 0, 0, 0)
#endif
#ifdef ystep
#ifdef yenable
MOTOREN(1, yenable)
#else
MOTOREN0(1)
#endif
MOTOR(1, ydirection, ystep)
#else
DUMMYMOTOR(1, 0, 0, 0)
#endif
#ifdef zstep
#ifdef zenable
MOTOREN(2, zenable)
#else
MOTOREN0(2)
#endif
MOTOR(2, zdirection, zstep)
#else
DUMMYMOTOR(2, 0, 0, 0)
#endif
#ifdef e0step
#ifdef e0enable
MOTOREN(3, e0enable)
#else
MOTOREN0(3)
#endif
MOTOR(3, e0direction, e0step)
#else
DUMMYMOTOR(3, 0, 0, 0)
#endif
static void move_motor(int n, int oldir, long nstep) {
switch (n) {
case 0: motor_0_ON(); motor_0_DIR(nstep); break;
case 1: motor_1_ON(); motor_1_DIR(nstep); break;
case 2: motor_2_ON(); motor_2_DIR(nstep); break;
case 3: motor_3_ON(); motor_3_DIR(nstep); break;
}
nstep = abs(nstep);
if (nstep)
while (nstep--) {
switch (n) {
case 0: motor_0_STEP(); break;
case 1: motor_1_STEP(); break;
case 2: motor_2_STEP(); break;
case 3: motor_3_STEP(); break;
}
somedelay(150);
switch (n) {
case 0: motor_0_UNSTEP(); break;
case 1: motor_1_UNSTEP(); break;
case 2: motor_2_UNSTEP(); break;
case 3: motor_3_UNSTEP(); break;
}
}
switch (n) {
case 0: motor_0_DIR(oldir); break;
case 1: motor_1_DIR(oldir); break;
case 2: motor_2_DIR(oldir); break;
case 3: motor_3_DIR(oldir); break;
}
}
#ifndef ISPC
#endif
#endif //mototh
<file_sep>/karya34m/gcode.h
#ifndef GCODE_H
#define GCODE_H
#include<stdint.h>
#include "motion.h"
#include "config_pins.h"
static const uint8_t X = 0;
static const uint8_t Y = 1;
static const uint8_t Z = 2;
static const uint8_t E = 3;
static const uint8_t E0 = 3;
static const uint8_t E1 = 4;
//#define uint8_t X =0
//#define Y 1
//#define Z 2
//#define E 3
//#define E0 3
//#define E1 4
//#define DEBUG
#if defined(USE_SDCARD) && defined(SDCARD_CS)
// generic sdcard add about 800uint8_t ram and 8kb code
#ifdef ESP8266 || __ARM__
#include <SPI.h>
#include <SD.h>
#else
#include "SdFat.h"
extern SdFat SD;
#endif
#endif
typedef struct {
uint32_t mantissa; ///< the actual digits of our floating point number
uint8_t exponent : 7; ///< scale mantissa by \f$10^{-exponent}\f$
uint8_t sign : 1; ///< positive or negative?
} decfloat;
typedef struct {
float axis[NUMAXIS];
float F;
//float f_multiplier;
uint8_t e_relative : 1; ///< bool: e axis relative? Overrides all_relative
} TARGET;
/// this holds all the possible data from a received command
typedef struct {
uint8_t seen_G : 1;
uint8_t seen_M : 1;
uint8_t seen_X : 1;
uint8_t seen_Y : 1;
uint8_t seen_Z : 1;
uint8_t seen_E : 1;
uint8_t seen_F : 1;
uint8_t seen_S : 1;
uint8_t seen_P : 1;
uint8_t seen_T : 1;
//uint8_t seen_N : 1;
#ifdef ARC_SUPPORT
uint8_t seen_I : 1;
uint8_t seen_J : 1;
uint8_t seen_R : 1;
#endif
//uint8_t seen_checksum : 1; ///< seen a checksum?
//uint8_t seen_semi_comment : 1; ///< seen a semicolon?
//uint8_t seen_parens_comment : 1; ///< seen an open parenthesis
uint8_t read_string : 1; ///< Currently reading a string.
uint8_t option_all_relative : 1; ///< relative or absolute coordinates?
uint8_t option_e_relative : 1; ///< same for e axis (M82/M83)
//uint32_t N; ///< line number
//uint32_t N_expected; ///< expected line number
float S; ///< S word (various uses)
uint16_t P; ///< P word (various uses)
uint8_t G; ///< G command number
uint16_t M; ///< M command number
TARGET target; ///< target position: X, Y, Z, E and F
#ifdef ARC_SUPPORT
float I;
float J;
float R;
#endif
uint8_t T; ///< T word (tool index)
//uint8_t checksum_read; ///< checksum in gcode command
//uint8_t checksum_calculated; ///< checksum we calculated
} GCODE_COMMAND;
extern int32_t linecount,lineprocess;
extern int waitforline;
extern char g_str[40];
extern int g_str_c;
#ifdef USE_SDCARD
extern File myFile;
extern void demoSD();
#else
static void demoSD() {}
#endif
extern void changefilament(float l);
extern void process_gcode_command();
extern uint8_t gcode_parse_char(uint8_t c);
extern void init_gcode();
extern int sdcardok;
#endif
<file_sep>/karya34m/data/costy-x.js
function getvalue(el){
return document.getElementById(el).value;
}
function setvalue(el,val){
document.getElementById(el).value=val;
}
function setevent(ev,bt,act){
document.getElementById(bt).addEventListener(ev, act,false);
}
function setclick(bt,act){
setevent("click",bt,act);
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
var div = ""; //= document.getElementById('mytext');
var area_dimension = document.getElementById('area_dimension');
var div1; // = document.getElementById('mytext1');
var text1;
function mround(x) {
return Math.round(x * 100.0) / 100.0;
}
var X1 = 0;
var Y1 = 0;
var lenmm = 0;
var lastf = 0;
var x1 = 0;
var y1 = 0;
var xmin = 100000;
var ymin = 100000;
var xmax = 0;
var ymax = 0;
var sxmin = 100000;
var symin = 100000;
var sxmax = 0;
var symax = 0;
var calcmax=0;
var gcodes = [];
var harga=1000;
var cncz=0;
function gcoden(g, f, x2, y2) {
div = div + 'G' + g + ' F' + (f) + ' X' + mround(x2) + ' Y' + mround(y2) + '\n';
x1 = x2;
y1 = y2;
lastf = f;
xmin = Math.min(xmin, x2);
ymin = Math.min(ymin, y2);
xmax = Math.max(xmax, x2);
ymax = Math.max(ymax, y2);
}
function gcode0(f, x2, y2) {
gcoden(0, f, x2, y2);
}
function gcode1(f, x2, y2) {
x1 -= x2;
y1 -= y2;
lenmm = lenmm + Math.sqrt(x1 * x1 + y1 * y1);
gcoden(1, f, x2, y2);
}
var sgcodes = [];
var jmltravel=0;
function draw_line(num, lcol, lines) {
if (sxmax < sxmin);
var dpm = 440.0 / (sxmax);
dpm = Math.min(dpm, 440.0 / (symax));
var x = lx / dpm;
var y = ly / dpm;
var cxmin = 100000;
var cymin = 100000;
var cxmax = 0;
var cymax = 0;
var n = 0;
var sc=1;
if (document.getElementById("flipx").checked)sc=-1;
var ro=1;
if (document.getElementById("rotate").checked)ro=-1;
var c = document.getElementById("myCanvas1");
//alert(c);
var ctx = c.getContext("2d");
ctx.font = "8px Arial";
var g = 0;
var X1=0;
var Y1=0;
for (var i=0;i<lines.length;i++){
g = i;
x=lines[i][1];
y=lines[i][2];
if (ro==-1){
xx=x;
x=y;
y=xx;
}
if (sc==-1)x=sxmax-x;
if (g >= 0) {
ctx.beginPath();
if (g == 0) {X1=x*dpm;Y1=y*dpm;jmltravel++;ctx.strokeStyle = "#FFeeee";}
if (g > 0) ctx.strokeStyle = lcol;
cxmin = Math.min(cxmin, x);
cymin = Math.min(cymin, y);
cxmax = Math.max(cxmax, x);
cymax = Math.max(cymax, y);
ctx.moveTo(lx, ly);
lx = x * dpm;
ly = y * dpm;
ctx.lineTo(lx, ly);
ctx.stroke();
}
//ctx.endPath();
}
ctx.beginPath();
ctx.moveTo(lx, ly);
ctx.lineTo(X1, Y1);
ctx.stroke();
//+" W:"+mround(cxmax-cxmin)+" H:"+mround(cymax-cymin)+" "
if (cxmin < cxmax) ctx.fillText("#" + num,dpm*((cxmax-cxmin)/2+cxmin),dpm*cymax+10);
}
var lastz=0;
function lines2gcode(num,data,z,cuttabz) {
// the idea is make a cutting tab in 4 posisiton,:
//
var len=Math.abs(data[0]);
if (len<50)cuttabz=z;
var lenc=0;
var cuttablen=8;
var cut=[];
if (len>150) {
lc=len/4;
} else {
lc=len/2;
}
slc=lc/2;
cut[0]=lc-slc - cuttablen;
cut[1]=lc*2-slc - cuttablen;
cut[2]=lc*3-slc - cuttablen;
cut[3]=lc*4-slc - cuttablen;
cutat=0;
var X1=data[2];
var Y1=data[3];
var lines=data[4];
var sc=1;
if (document.getElementById("flipx").checked){
sc=-1;
X1=sxmax-X1;
}
var ro=1;
if (document.getElementById("rotate").checked){
ro=-1;
XX=X1;
X1=Y1;
Y1=XX;
}
var lx=X1;
var ly=Y1;
// turn off tool and move up if needed
var cmd = getvalue('cmode');
var pw1 = 1;
var pw2 = 0;//getvalue('pwm');
var pup = getvalue('pup');
var pdn = getvalue('pdn');
var f1 = getvalue('trav') * 60;
var f2 =getvalue('feed') * 60;
if (cmd == 2) {
pw1 = pw2;
f1 = f2;
}
div="";
if (sxmax < sxmin) return cdiv;
// deactivate tools and move to cut position
div = div + "\n;SHAPE #"+num+"\n";
if (pw2) div = div + "M106 S" + pw1 + "\n";
div = div + pup + '\n';
if (cmd==2){
gcode0(f1,X1,0);
}
gcode0(f1,X1,Y1);
div = div + "G0 Z"+lastz+"\n";
lastz=z;
// activate tools and prepare the speed
if (pw2) div = div + "M106 S" + pw2 + "\n";
div = div + pdn.replace("=cncz",mround(z)) + '\n';
var incut=0;
for (var i=0;i<lines.length;i++){
x=lines[i][1];
y=lines[i][2];
if (sc==-1){
x=sxmax-x;
}
if (ro==-1){
xx=x;
x=y;
y=xx;
}
var iscut=0;
if ((cuttabz>z) && (cutat<4)) {
// if cut1 is in lenc and lencnext then cut the line
// and dont increase the i counter
if ((cut[cutat]>=lenc) && (cut[cutat]<=lines[i][3])){
// split lines
iscut=1;
dx=x-lx;
dy=y-ly;
llen=lines[i][3]-lenc;
lcut=cut[cutat]-lenc;
x=lx+dx*(lcut/llen);
y=ly+dy*(lcut/llen);
lenc=cut[cutat];
//lines[i][1]=x;
//lines[i][2]=y;
//lines[i][3]-=lcut;
if ((incut==1)){
incut=0;
cutat++;
} else {
incut=1;
cut[cutat]+=cuttablen;
}
}
}
gcode1(f2, x, y);
lx=x;
ly=y;
if (iscut){
if (incut==1){
// move up
div = div + pdn.replace("=cncz",mround(cuttabz)) + '\n';
} else {
// move back down
div = div + pdn.replace("=cncz",mround(z)) + '\n';
}
i--;
} else {
lenc=lines[i][3];
}
}
//close loop
gcode1(f2, X1, Y1);
if (cmd == 2) {
// if foam mode must move up
gcode0(f1,X1,0);
}
gcode0(f1,X1,Y1);
return div;
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function gcode_verify() {
var c = document.getElementById("myCanvas1");
//alert(c);
lx = 0;
ly = 0;
jmltravel=0;
var ctx = c.getContext("2d");
var sfinal = 0;
ctx.clearRect(0, 0, c.width, c.height);
for (var i = 0; i < sgcodes.length; i++) {
draw_line(i + 1, getRandomColor(), sgcodes[i][4]);
sfinal += Math.abs(sgcodes[i][0]);
}
//sfinal+=jmltravel*10;
ctx.font = "12px Arial";
w=mround((xmax - xmin)/10);
h=mround((ymax - ymin)/10);
ctx.fillText("W:" + w + " H:" + h + " Luas:"+mround(w*h)+" cm2", 0, c.height - 20);
var menit=mround((sfinal+jmltravel*10) / getvalue('feed') / 60.0);
var re = getvalue("repeat");
menit=menit*re;
area_dimension.innerHTML = 'Total Length =' + mround(sfinal) + "mm Time:" + menit + " menit <br>Biaya Cut:" + Math.round(menit*1500)+" bahan:"+mround(w*h*harga)+" TOTAL:"+mround(menit*1500+w*h*harga);
}
function sortedgcode() {
sgcodes = [];
sxmax=xmax;
symax=ymax;
sxmin=xmin;
symin=ymin;
xmax=-10000;
ymax=-10000;
xmin=100000;
ymin=100000;
var sm = -1;
var divs = '';
var lx=0;
var ly=0;
for (var j = 0; j < gcodes.length; j++) {
var cs = -1;
var bg = 10000000;
for (var i = 0; i < gcodes.length; i++) {
var dx=gcodes[i][2]-lx;
var dy=gcodes[i][3]-ly;
var dis=Math.sqrt(dx*dx+dy*dy)+gcodes[i][0];
if ((gcodes[i][0] > 0) && (dis < bg)) {
cs = i;
bg = dis;
}
}
// smalles in cs
if (cs >= 0) {
sgcodes.push(gcodes[cs]);
gcodes[cs][0]=-gcodes[cs][0];
lx=gcodes[cs][2];
ly=gcodes[cs][3];
divs = divs + gcodes[cs][1];
}
}
var re = getvalue("repeat");
s = "";//;Init machine\n;===============\nM206 P80 S20 ;x backlash\nM206 P84 S20 ;y backlash\nM206 P88 S20 ;z backlash\n;===============\n";
cncdeep=- getvalue("zdown");
cncz=cncdeep/re;
var cuttab=0;
lastz=0;
var cmd = getvalue('cmode');
cuttab=cncdeep+getvalue("tabc")*1;
for (var i = 0; i < re; i++) {
for (var j=0;j<sgcodes.length;j++){
s += lines2gcode(j+1,sgcodes[j],cncz,cuttab);
}
cncz+=cncdeep/re;
}
s=s+getvalue("pup");
s = s + '\nG00 F3000 Y0 \n G00 X0\n';
setvalue("gcode",s);
sc=1;
if (document.getElementById("flipx").checked) sc=-1;
setvalue("pgcode",getvalue("pup")+"\nM3 S255 P10\nG0 F10000 X" + mround(sc*xmin) + " Y" + mround(ymin) + "\nM3 S255 P10\nG0 X" + mround(sc*xmax) + "\nM3 S255 P10\nG0 Y" + mround(ymax) + "\nM3 S255 P10\nG0 X" + mround(sc*xmin) + " \nM3 S255 P10\nG0 Y" + mround(ymin) + "\n");
}
////////////////////////////////////////////////////////////////////////////////////////////
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
var lines=[];
function myFunction(scale1) {
//text1=Potrace.getSVG(1);
//alert(text1);
var contor = 0;
var xincep = 0;
var yincep = 0;
var p1x = 0;
var p1y = 0;
var p2x = 0;
var p2y = 0;
var xsfar = 0;
var ysfar = 0;
var n1 = 0;
lines=[];
var scale = 25.4 / getvalue('scale');
if (scale1) scale = 1;
//var division = document.getElementById('division').value;
//path d="M111.792 7.750 C 109.785 10.407,102.466 13.840,100.798 12.907 C
//document.getElementById("gsvg").value=text1;
var cmd = getvalue('cmode');
var pw1 = 1;
var pw2 = 0;//getvalue('pwm');
var pup = getvalue('pup');
var pdn = getvalue('pdn');
var f1 = getvalue('trav') * 60;
var f2 =getvalue('feed') * 60;
var det=getvalue('feed')/15.0;
if (cmd == 2) {
pw1 = pw2;
f1 = f2;
}
//alert(cmd);
var n = text1.indexOf(' d="M');
n = n + 5;
var handleM = 1;
var X1 = 0;
var Y1 = 0;
xmin = 100000;
ymin = 100000;
xmax = 0;
ymax = 0;
gcodes = [];
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
div = "";
lenmm = 0;
var cnts = 0;
var line=[];
//alert(div.innerHTML);
while (1) {
if (handleM) {
var mm = ' ';
if (text1.charAt(n) == ' ') {
mm = ',';
n = n + 1;
}
var res = scale * parseFloat(text1.slice(n, n + 10)); // '111.792 7.'
//res=res*scale;
//alert(res);
xincep = res;
var n = text1.indexOf(mm, n + 1);
n = n + 1; //7.750 C
var res = scale * parseFloat(text1.slice(n, n + 10));
//res=res*scale;
//alert(res);
yincep = res;
cnts = cnts + 1;
// close shape loop
if (cnts > 1) {
gcode1(f2, X1, Y1);
line.push([f2,X1,Y1,lenmm]);
if (cmd == 2) {
// if foam mode must move up
div = div + 'G00 Y0 \n';
}
gcodes.push([lenmm, div,X1,Y1,line]);
lines.push(line);
}
line=[];
div = "";
lenmm = 0;
// deactivate tools and move to cut position
div = div + "\n;SHAPE\n";
if (pw2) div = div + "M106 S" + pw1 + "\n";
div = div + pup + '\n';
X1 = xincep;
Y1 = yincep;
gcode0(f1, X1, Y1);
// activate tools and prepare the speed
if (pw2) div = div + "M106 S" + pw2 + "\n";
div = div + pdn + '\n';
div = div + 'G01 F' + f2 + '\n';
lastf = f2;
handleM = 0;
}
var n = text1.indexOf(' ', n + 1);
cr = text1.charAt(n + 1);
if ((cr >= '0') && (cr <= '9')) {
var n2 = text1.indexOf(' ', n + 2);
var xy = text1.slice(n + 1, n2).split(',');
p1x = xy[0] * scale;
p1y = xy[1] * scale;
gcode1(f2, p1x, p1y);
line.push([f2,p1x,p1y,lenmm]);
} else if (cr == 'H') {
var n2 = text1.indexOf(' ', n + 3);
var xy = text1.slice(n + 3, n2);
p1x = xy * scale;
gcode1(f2, p1x, y1);
line.push([f2,p1x,y1,lenmm]);
n = n + 3;
} else if (cr == 'V') {
var n2 = text1.indexOf(' ', n + 3);
var xy = text1.slice(n + 3, n2);
p1y = xy * scale;
gcode1(f2, y1, p1y);
line.push([f2,y1,p1y,lenmm]);
n = n + 3;
} else if (cr == 'C') {
//path d="M111.792 7.750 C 109.785 10.407,102.466 13.840,100.798 12.907 C
var res = scale * parseFloat(text1.slice(n + 2, n + 10));
//res=res*scale;
//alert(res);
p1x = res;
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//alert(res);
p1y = res;
var n = text1.indexOf(',', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//alert(res);
p2x = res;
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//alert(res);
p2y = res;
var n = text1.indexOf(',', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//alert(res);
xsfar = res;
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//alert(res);
ysfar = res;
//*****************************
var a = p1x - xincep
var b = p1y - yincep
var a = Math.sqrt(a * a + b * b);
var b = p2x - p1x
var c = p2y - p1y
var b = Math.sqrt(b * b + c * c);
var c = xsfar - p2x
var d = ysfar - p2y
var c = Math.sqrt(c * c + d * d);
//g=1/((a+b+c)*division);
g = det / (a + b + c);
a = a + b + c;
//alert('dist ='+a+' pezzi='+g);
//******************************
for (i = 0; i < 1; i += g) {
var x = bezierx(i, xincep, p1x, p2x, xsfar);
var y = beziery(i, yincep, p1y, p2y, ysfar);
gcode1(lastf, x, y);
line.push([lastf,x, y,lenmm]);
}
//******************************************************************
xincep = xsfar;
yincep = ysfar;
} else if (cr == 'L') { //alert("este L");
//div.innerHTML = div.innerHTML +'(este linie) \n\n\n';
var res = scale * parseFloat(text1.slice(n + 2, n + 10));
//res=res*scale;
p1x = res;
//console.log(res);
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//console.log(res);
p1y = res;
gcode1(lastf, p1x, p1y);
line.push([lastf,p1x, p1y,lenmm]);
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//console.log(res);
p2x = res;
var n = text1.indexOf(' ', n + 3);
var res = scale * parseFloat(text1.slice(n + 1, n + 10));
//res=res*scale;
//console.log(res);
p2y = res;
gcode1(lastf, p2x, p2y);
line.push([lastf,p2x, p2y,lenmm]);
xincep = p2x;
yincep = p2y;
} else if (cr == 'M') {
//console.log("este M");
n = n + 2;
handleM = 1;
} else if (text1.slice(n + 1, n + 5) == ' d="M') {
//console.log("este M");
n = n + 5;
handleM = 1;
} else if (n < 1) {
//console.log("lenght depasit");
break;
} else {
console.log("unknown :"+text1.slice(n + 1, n + 10));
var n = text1.indexOf(' d="M', n + 1);
if (n < 1) break;
n = n + 5;
handleM = 1;
}
} //sfarsit while
// close loop
if (cnts > 0) {
gcode1(f2, X1, Y1);
line.push([lastf,X1, Y1,lenmm]);
if (cmd == 2) {
// for foam, must move up first
div = div + 'G00 Y0 \n';
}
gcodes.push([lenmm, div,X1,Y1,line]);
div = "";
}
sortedgcode();
} //sfarsit myFunction
//*****************************************************
function bezierx(t, p0, p1, p2, p3) {
var s = 1 - t;
var x = s * s * s * p0 + 3 * (s * s * t) * p1 + 3 * (t * t * s) * p2 + t * t * t * p3;
return x;
}
function beziery(t, p0, p1, p2, p3) {
var s = 1 - t;
var y = s * s * s * p0 + 3 * (s * s * t) * p1 + 3 * (t * t * s) * p2 + t * t * t * p3;
return y;
}
//***********************************************
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function() {
var dataURL = reader.result;
//var output = document.getElementById('output');
//output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
Potrace.loadImageFromFile(input.files[0]);
Potrace.process(function() {
//displayImg();
//displaySVG(scale);
text1 = Potrace.getSVG(1);//.toUpperCase();
refreshgcode();
});
};
// handle paste image
// We start by checking if the browser supports the
// Clipboard object. If not, we need to create a
// contenteditable element that catches all pasted data
if (!window.Clipboard) {
var pasteCatcher = document.createElement("div");
// Firefox allows images to be pasted into contenteditable elements
pasteCatcher.setAttribute("contenteditable", "");
// We can hide the element and append it to the body,
pasteCatcher.style.opacity = 0;
document.body.appendChild(pasteCatcher);
// as long as we make sure it is always in focus
pasteCatcher.focus();
document.addEventListener("click", function() {
pasteCatcher.focus();
});
}
// Add the paste event listener
window.addEventListener("paste", pasteHandler);
/* Handle paste events */
function pasteHandler(e) {
// We need to check if event.clipboardData is supported (Chrome)
if (e.clipboardData) {
// Get the items from the clipboard
var items = e.clipboardData.items;
if (items) {
// Loop through all items, looking for any kind of image
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") !== -1) {
// We need to represent the image as a file,
var blob = items[i].getAsFile();
// and use a URL or webkitURL (whichever is available to the browser)
// to create a temporary URL to the object
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
// The URL can then be used as the source of an image
createImage(source, blob);
}
}
}
// If we can't handle clipboard data directly (Firefox),
// we need to read what was pasted from the contenteditable element
} else {
// This is a cheap trick to make sure we read the data
// AFTER it has been inserted.
setTimeout(checkInput, 1);
}
}
/*
window.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
*/
window.addEventListener('Xdrop', function(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i = 0, file; file = files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.tipe = file.type;
reader.onload = function(event) {
var dataURL = reader.result;
//event.target.result;
//var output = document.getElementById('output');
//output.src = dataURL;
if (reader.tipe.indexOf("svg") !== -1) {
text1 = event.target.result;//.toUpperCase();
myFunction(1);
gcode_verify();
} else {}
};
if (file.type.indexOf("svg") !== -1) {
reader.readAsText(file);
} else {
reader.readAsDataURL(file);
Potrace.loadImageFromFile(file);
Potrace.process(function() {
//displayImg();
//displaySVG(scale);
text1 = Potrace.getSVG(1);//.toUpperCase();
refreshgcode();
});
}
}
}
});
/* Parse the input in the paste catcher element */
function checkInput() {
// Store the pasted content in a variable
var child = pasteCatcher.childNodes[0];
// Clear the inner html to make sure we're always
// getting the latest inserted content
pasteCatcher.innerHTML = "";
if (child) {
// If the user pastes an image, the src attribute
// will represent the image as a base64 encoded string.
if (child.tagName === "IMG") {
createImage(child.src);
}
}
}
/* Creates a new image from a given source */
function createImage(source, blob) {
var pastedImage = new Image();
//clear gcode
pastedImage.onload = function() {
Potrace.loadImageFromFile(blob);
Potrace.info.alphamax = getvalue("smooth");
Potrace.process(function() {
//displayImg();
//displaySVG(scale);
text1 = Potrace.getSVG(1);//.toUpperCase();
refreshgcode();
});
}
pastedImage.src = source;
}
function createSVG(source, blob) {
//displaySVG(scale);
text1 = blob;
refreshgcode();
}
function refreshgcode() {
myFunction(0);
gcode_verify();
savesetting();
}
function copy_to_clipboard(id) {
document.getElementById(id).select();
document.execCommand('copy');
}
<file_sep>/karya34m/boards.h
/*
============================================================================================
NAMEBOARD
============================================================================================
#ifdef BOARD_NAMEBOARD
// motors PIN
#define xenable 2
#define xdirection 6
#define xstep 4
#define yenable 7
#define ydirection 9
#define ystep 8
#define zenable 10
#define zdirection A5
#define zstep A4
#define e0enable 11
#define e0direction A2
#define e0step A3
// ENDSTOPS PIN, can be using just 1 pin
#define limit_pin 0
#define temp_pin 6
#define temp2_pin 6
#define heater_pin 3
#define heater2_pin 3
#define DRIVE_XYYZ
#define DRIVE_COREXY
#define DRIVE_COREXZ
#define DRIVE_DELTA
#define DRIVE_DELTASIAN
#define ISRTEMP // avr reading using interrupt
#define USETIMER1 // using timer1 or other timer (implemented timer1 on avr)
#define CORESERIAL // reduce code on AVR
#define OLEDDISPLAY // still WIP
#define SDCARD_CS // pin for SDCARD
#define KBOX_PIN // 4 key Kontrolbox using analog pin and serial resistors
#define MOTOR_0_DIR 1 // 1: normal -1:inverted
#define MOTOR_1_DIR 1 // 1: normal -1:inverted
#define MOTOR_2_DIR 1 // 1: normal -1:inverted
#define MOTOR_3_DIR 1 // 1: normal -1:inverted
#define USE_EEPROM
*/
/*
============================================================================================
TARANTHOLE
============================================================================================
*/
#ifdef BOARD_TARANTHOLE
#define xenable 2
#define xdirection 6
#define xstep 4
#define yenable 7
#define ydirection 9
#define ystep 8
#define zenable 10
#define zdirection A5
#define zstep A4
#define e0enable 11
#define e0direction A2
#define e0step A3
#define limit_pin 13
#define temp_pin 6
#define heater_pin 3
/*
============================================================================================
////////////////////////////////////////////////////////////
////////////K34M Board
///////////////////////////////////////////////////////////////
============================================================================================
*/
#elif defined(BOARD_K34M)
//
// Added static const uint8_t definition for D0-D10
//
//static const uint8_t D0 = 16;
//static const uint8_t D1 = 5;
//static const uint8_t D2 = 4;
//static const uint8_t D3 = 0;
//static const uint8_t D4 = 2;
//static const uint8_t D5 = 14;
//static const uint8_t D6 = 12;
//static const uint8_t D7 = 13;
//static const uint8_t D8 = 15;
//static const uint8_t D9 = 3;h
//static const uint8_t D10 = 1;
//
#define ESP8266
#define xdirection 14
#define xstep 0
#define ydirection 12
#define ystep 2
// z and e have same direction pin, we think that normally slicer never move z and e together.. we hope we are right :D
#define zdirection 13
#define zstep 16
#define e0direction 13
#define e0step 4
#define limit_pin 15
#define temp_pin A0
#define heater_pin 5
//#define laser_pin D1
//#define fan_pin D1 // To be used for plama relay/contact
//#define INVERTENDSTOP
#define NUMBUFFER 20 // increased buffer from 20 to 80
////////////////////////////////////////////////////////////
////////////End K34M Board
///////////////////////////////////////////////////////////////
#else
#error No BOARD Defined !
#endif
<file_sep>/README.md
# K34M
Fork/based on https://github.com/ryannining/karyacontroller a dedicated board and code for esp8266 and in future esp32
Using D1 mini from wemos and in future d1 mini esp32 from eht modules
Board for cover multiple Maker needs compatible with that gcode machines.
cnc,plotter, 3dprinter,plasma cutter,foam cutter..etc.
Why bigger size of original karyacontroller:
- for improve wiring for no have cables on steppers or other cables on boad.
- cooling use uniqe fan80mm for cold stepper and esp.
- have space for eventual next updates or for move on esp32 and 8 steppers
### board features:
- Dimension of board 80x80
- 4 stepper max
- 1 power output (with logical pwm near)
- 1 thermoresistor 100k
- 1 endstop line (pullup or pulldown)
- 1 full external output pins
- 1 configuration pins(for 4 stepper indipendent or dir E-Z in common)
- mount holes for using standard unique 80mm
### Limits and alternative solution:
image of demo board

image of pins

### Configuration pins
> Full 4° Axis without no endstops

That configuration need for use 4° (E Driver) driver fully indipendent. For have that configuration need lose use of endstop.
That configuration are usefull for 4° axis Foam cutter cnc
>4° Axis with endstops

That configuration use E DIR in common with Z DIR that permit use board for CNC 3DPrinters plotter and so on most common configuration for any build.
Board currenlty in shippping to italy need wait for testing and we release gerber original easyeda project and cleaned code .
<file_sep>/karya34m/config_pins.h
/*
============================================================================================
AVR
============================================================================================
*/
#include "motion.h"
#ifndef ISPC
#include<arduino.h>
//Known board in boards.h
#define xenable -1
#define yenable -1
#define zenable -1
#define e0enable -1
#define ISRTEMP // 120bytes check board.h
#define MOTOR_0_DIR -1 // 1: normal -1:inverted
#define MOTOR_1_DIR -1 // 1: normal -1:inverted
#define MOTOR_2_DIR -1 // 1: normal -1:inverted
#define MOTOR_3_DIR 1 // 1: normal -1:inverted
#define THEISR
// ====== ESP32 ====================================================
#if defined(ESP32)
#define BOARD_ESP32VN3D
#define THEISR ICACHE_RAM_ATTR
//#define SUBPIXELMAX 6 // multiple axis smoothing / AMASS maximum subpixel
// ====== ESP8266 ====================================================
#elif defined(ESP8266)
//#define SUBPIXELMAX 6 // multiple axis smoothing / AMASS maximum subpixel
#define THEISR ICACHE_RAM_ATTR
#define ANALOGSHIFT 0 // 10bit adc ??
#define BOARD_K34M
#endif
#include "boards.h"
#define USE_EEPROM
#else
// for PC no pins
#endif
/*
============================================================================================
CONFIGURATION
============================================================================================
*/
//#define ARC_SUPPORT // 3kb
#define USEDIO // 750bytes this can save almost 20us each bresenham step, is a MUST if not using timer!
//#define USE_BACKLASH // 400bytes code
#define USETIMER1 // Work in progress // 98 bytes// FLASH SAVING
//#define SAVE_RESETMOTION // 1000 bytes code, no reset motion, need EEPROM
//#define LCDDISPLAY 0x3F // more than 2.5K , simple oled controller
#define CORESERIAL // smaller footprint 500byte, only AVR
#define CHANGEFILAMENT //580byte
#define HARDSTOP // allow to stop in the middle of movement, and still keep the current position, great for CNC
#define WIFISERVER
//#define TELEGRAM
// ==========================================================
#define INTERPOLATEDELAY // slower 4-8us
#ifdef powerpin
#define POWERFAILURE
#endif
// lets assume if not laser_pin not defined use the heater_pin
#ifdef laser_pin
#define LASERMODE
#elif defined(heater_pin)
// to make sure all board can be user for laser engraving
#define laser_pin heater_pin
#define LASERMODE
#endif
#define UPDATE_F_EVERY 2000 //us = 250 tick/sec acceleration change
#ifndef ISPC
//#define SUBPIXELMAX 6 // multiple axis smoothing / AMASS maximum subpixel
#else
//#define SUBPIXELMAX 4
#endif
//#undef SDCARD_CS
#ifdef SDCARD_CS
#define USE_SDCARD
#endif
// ESP8266
#if defined(ESP8266) && !defined(USE_SHIFTREG)
#define SHARE_EZ
#endif
//#ifndef ESP8266
//
//
//Disabled webserver for testing purposes
//
#ifdef ESP8266
//#undef WIFISERVER
#endif
#ifndef __AVR__
// not implemented on non AVR
#undef USEDIO
#undef ISRTEMP
#undef CORESERIAL
//#undef LCDDISPLAY
//#undef USETIMER1
#endif
#ifdef ISPC
// not implemented on PC
#undef USETIMER1
#undef LASERMODE
#undef SAVE_RESETMOTION
#endif
//#define motortimeout 10000000 // 10 seconds
//#define DRIVE_XYYZ // dual Y individual homing
//#define DRIVE_COREXY
//#define DRIVE_COREXZ
//#define DRIVE_DELTA
//#define DRIVE_DELTASIAN
#ifdef DRIVE_DELTA
#define NONLINEAR
#endif
#ifdef DRIVE_DELTASIAN
#define NONLINEAR
#endif
#define TOWER_X_ANGLE_DEG 210
#define TOWER_Y_ANGLE_DEG 330
#define TOWER_Z_ANGLE_DEG 90
#define DELTA_DIAGONAL_ROD 180
#define DELTA_RADIUS 85
// Motion configuration
#define CHECKENDSTOP_EVERY 0.05 // mm this translate to 200step if step/mm is 4000, must lower than 255 (byte size)
#define HOMINGSPEED 60
#define XOFFSET 0
#define YOFFSET 0
#define ZOFFSET 0
#define EOFFSET 0
#define XYJERK 22
#define XACCELL 40
#define XMOVEACCELL 40
#define XMAXFEEDRATE 240
#define YMAXFEEDRATE 240
#define ZMAXFEEDRATE 240
#define E0MAXFEEDRATE 10
//106.66,213.3332,1066.6666,174.864
#define XSTEPPERMM 106.66//1780//131//178
#define YSTEPPERMM 213.3332//125//175//125
#define ZSTEPPERMM 1066.6666//1020//1020 //420
#define E0STEPPERMM 174.864//340//380
#ifndef NUMBUFFER
#define NUMBUFFER 80//20
#endif
#define XMAX 150//1200
#define YMAX 125//1800
#define ZMAX 120
#define MOTOR_X_BACKLASH 0 // MOTOR 0 = X, 1= Y 2=Z 3=E
#define MOTOR_Y_BACKLASH 0
#define MOTOR_Z_BACKLASH 0
#define MOTOR_E_BACKLASH 0
//#define AUTO_MOTOR_Z_OFF
//#define INVERTENDSTOP // uncomment for normally open
#define ENDSTOP_MOVE 3 //2mm move back after endstop hit, warning, must
#define HOMING_MOVE 2000
// KontrolBox a series resistor with switch to a analog PIN
// MCU only
#ifndef ISPC
/*
MACROS for KBOXKontroller
*/
#define KBOX_KEY_CHECK(k) case KBOX_KEY##k##_R : lkey = k;kdl=500;break;
//#define KBOX_SHOW_VALUE
#define KBOX_KEY1_R 0 ... 10
#define KBOX_KEY2_R 500 ... 530
#define KBOX_KEY3_R 670 ... 695
#define KBOX_KEY4_R 750 ... 780
#define KBOX_DO_CHECK KBOX_KEY_CHECK(1) KBOX_KEY_CHECK(2) KBOX_KEY_CHECK(3) KBOX_KEY_CHECK(4)
#ifdef KBOX_PIN
#define KBOX_KEY4_ACTION zprintf(PSTR("HOMING\n"));homing();
#define KBOX_KEY3_ACTION zprintf(PSTR("HEATING\n"));set_temp(190);
#define KBOX_KEY2_ACTION if (sdcardok) {sdcardok = sdcardok == 1 ? 2 : 1;zprintf(PSTR("SD\n"));} else demoSD();
#define KBOX_KEY1_ACTION RUNNING=0;sdcardok=0;zprintf(PSTR("STOP\n"));power_off();
#define KBOX_KEY_ACT(k) case k: zprintf(PSTR("Act %d\n"),k); KBOX_KEY##k##_ACTION ;break;
#define KBOX_DO_ACT KBOX_KEY_ACT(1) KBOX_KEY_ACT(2) KBOX_KEY_ACT(3) KBOX_KEY_ACT(4)
#else // no controller
//#define KBOX_DO_ACT
#endif
#endif
<file_sep>/karya34m/backup.cpp
/*
*
=========================
#ifdef DRIVE_DELTA
void addmoveDELTA(float cf, float cx2, float cy2 , float cz2, float ce02, int g0 , int rel)
{
// create delta segments if needed
int32_t dist;
// deltas
dist = approx_distance(labs(cx2 - cx1), labs(cy2 - cy1)); //,labs(diff.axis[Z]));
if (dist < 2) {
addmove(cf, cx2, cy2, cz2, ce02, g0, rel);
return;
}
float df[4], cx[4];
float sc = 1.0f / dist;
df[0] = float(cx2 - cx1) * sc;
df[1] = float(cy2 - cy1) * sc;
df[2] = float(cz2 - cz1) * sc;
df[3] = float(ce02 - ce01) * sc;
int segment_total = dist;
zprintf(PSTR("Dist:%d Segmen:%d\n"), fi(dist), fi(segment_total));
if ((df[X] == 0 && df[Y] == 0))
{
addmove(cf, cx2, cy2, cz2, ce02, g0, rel);
return;
} else {
//if you do all segments, rounding error reduces total - error will accumulate
for (int s = 1; s < segment_total; s++) {
addmove(cf, cx1 + (s * df[0]), cy1 + (s * df[1]), cz1 + (s * df[2]), ce01 + (s * df[3]), g0, rel);
}
//last bit to make sure we end up at the unsegmented target
//segment = *target;
//addmove(cf,cx2,cy2,cz2,ce02,g0,rel);
}
}
#endif
uint32_t approx_distance_3(uint32_t dx, uint32_t dy, uint32_t dz) {
uint32_t min, med, max, approx;
if ( dx < dy ) {
min = dy;
med = dx;
} else {
min = dx;
med = dy;
}
if ( dz < min ) {
max = med;
med = min;
min = dz;
} else if ( dz < med ) {
max = med;
med = dz;
} else {
max = dz;
}
approx = ( max * 860 ) + ( med * 851 ) + ( min * 520 );
if ( max < ( med << 1 )) approx -= ( max * 294 );
if ( max < ( min << 2 )) approx -= ( max * 113 );
if ( med < ( min << 2 )) approx -= ( med * 40 );
// add 512 for proper rounding
return (( approx + 512 ) >> 10 );
}
uint32_t approx_distance(uint32_t dx, uint32_t dy) {
uint32_t min, max, approx;
// If either axis is zero, return the other one.
if (dx == 0 || dy == 0) return dx + dy;
if ( dx < dy ) {
min = dx;
max = dy;
} else {
min = dy;
max = dx;
}
approx = ( max * 1007 ) + ( min * 441 );
if ( max < ( min << 4 ))
approx -= ( max * 40 );
// add 512 for proper rounding
return (( approx + 512 ) >> 10 );
}
Problems:
we dont know exact step needed from start to end
so, we need to change the ramping acceleration calculation
my idea is to stretch, so make the rampup and rampdown as float, and decrease it using a floating number
for linear system it decrease by 1, but for non linear, it will interpolate the decrease, so on segment calculation
need to change the decreasing value
totalseg=number segment
int segno =-1 // for first calc become 0
float sgx = deltax/stepmmx[fastaxis]
float sgy = deltay/stepmmx[fastaxis]
float sgz = deltaz/stepmmx[fastaxis]
float sge = deltae/stepmmx[fastaxis]
int mctr =0 (to trigger first calculation) stepmmx decreasing if reach zero reset to stepmmx ,segno ++
LOOP
if mctr<= 0 && totalseg>0
{
newx=segno++ * sgx + x[0]
...
transformdelta newx,...
deltax=newx-currentx
...
// reset bresenham direction
mtotalstep= biggest delta
mcx[0]=totalstep/2
currentx=newx
...
segctr=stepmmx[fastaxis]
} else {
// segment bresenham
}
*/
| 6d26e23481086455022dbc302cf2a911d3cc890e | [
"JavaScript",
"C",
"C++",
"Markdown"
] | 22 | C++ | exilaus/K34M | 554a75edd72f51ffede7fe32a5382d4b9257e943 | d796a8f325d40b93ef9e0345594e57f7d28860c2 |
refs/heads/master | <repo_name>zhilixue/resume<file_sep>/js/index.js
let loadingRender = (function ($) {
let $loadingBox = $('.loadingBox'),
$run = $loadingBox.find('.run');
//=>我们需要处理的图片
let imgList = ["img/icon.png", "img/zf_concatAddress.png", "img/zf_concatInfo.png", "img/zf_concatPhone.png", "img/zf_course.png", "img/zf_course1.png", "img/zf_course3.png", "img/zf_course5.png", "img/zf_course4.png", "img/zf_course2.png", "img/zf_course6.png", "img/zf_cube1.png", "img/zf_cube2.png", "img/zf_cube3.png", "img/zf_cube4.png", "img/zf_cube5.png", "img/zf_cube6.png", "img/zf_cubeBg.jpg", "img/zf_cubeTip.png", "img/zf_messageArrow1.png", "img/zf_messageArrow2.png", "img/zf_messageChat.png", "img/zf_messageKeyboard.png", "img/zf_messageLogo.png", "img/zf_messageStudent.png", "img/zf_outline.png", "img/zf_phoneBg.jpg", "img/zf_phoneDetail.png", "img/zf_phoneListen.png", "img/zf_phoneLogo.png", "img/zf_return.png", "img/zf_style1.jpg", "img/zf_style2.jpg", "img/zf_style3.jpg", "img/zf_styleTip1.png", "img/zf_styleTip2.png", "img/zf_teacher1.png", "img/zf_teacher2.png", "img/zf_teacher3.jpg", "img/zf_teacher4.png", "img/zf_teacher5.png"];
//=>控制图片加载进度
let total = imgList.length-3,
cur = 0;
let computed = function () {
imgList.forEach(function (item) {
let tempImg = new Image;
tempImg.src = item;
tempImg.onload = function () {
tempImg = null;
cur++;
runFn();
}
});
};
//=>计算滚动条加载长度
let runFn = function () {
$run.css('width', cur / total * 100 + '%');
if (cur >= total) {
let delayTimer = setTimeout(()=> {
$loadingBox.remove();
phoneRender.init();
clearTimeout(delayTimer);
}, 1500);
}
};
return {
init: function () {
$loadingBox.css('display', 'block');
computed();
}
}
})(Zepto);
let phoneRender=(function ($) {
let $phoneBox=$('.phoneBox'),
$time=$phoneBox.find(".time"),
$listen=$phoneBox.find(".listen"),
$listenTouch=$listen.find(".touch"),
$detail=$phoneBox.find(".detail"),
$detailTouch=$detail.find(".touch");
let audioBell=$("#audioBell")[0];
let audioSay=$("#audioSay")[0];
let $phonePlan=$.Callbacks();
$phonePlan.add(function () {
$listen.remove();
$detail.css('transform','translateY(0)')
});
//listen-touch
$phonePlan.add(function () {
audioBell.pause();
audioSay.play();
$time.css('display','block');
let sayTimer=setInterval(()=>{
let duration=audioSay.duration,
current=audioSay.currentTime;
let minute=Math.floor(current/60);
let second=Math.floor(current-minute*60);
minute<10?minute="0"+minute:null;
second<10?second="0"+second:null;
$time.html(`${minute}:${second}`)
//播放结束
if(current>duration){
clearInterval(sayTimer)
enterNext()
}
},1000)
})
$phonePlan.add(()=> {
$detailTouch.tap(enterNext)
})
// 进入下一个区域
let enterNext=function(){
audioSay.pause();
$phoneBox.remove();
messageRender.init()
}
return{
init:function () {
$phoneBox.css('display', 'block');
audioBell.play();
$listenTouch.tap($phonePlan.fire)
}
}
})(Zepto)
// merssage
let messageRender=(function () {
let $messageBox=$(".messageBox"),
$talkBox=$messageBox.find(".talkBox"),
$talkList=$talkBox.find("li"),
$keyBord=$messageBox.find(".keyBord"),
$keyBordText=$keyBord.find("span"),
$submit=$keyBord.find(".submit"),
musicAudio=$('#musicAudio')[0];
let $plan=$.Callbacks()
//控制消息列表逐条显示
let step=-1,
autoTimer=null,
interval=1500,
offset=0;
$plan.add(()=>{
autoTimer=setInterval(()=>{
step++;
let $cur= $talkList.eq(step);
$cur.css({opacity:1,transform:"translateY(0)"})
//当第三条完全展示之后立即调取键盘(dtep==2&当前li显示的动画已经完成)
if(step===2){
$cur.one("transitionend",()=>{
$keyBord.css("transform","translateY(0)").one("transitionend",textMove)
})
clearInterval(autoTimer)
}
if(step>=4){
offset+=-$cur[0].offsetHeight
$talkBox.css(
`transform`,`translateY(${offset}px)`
)
}
if(step>=$talkList.length-1){
clearInterval(autoTimer);
let dalayTimer=setTimeout(()=>{
musicAudio.pause()
$messageBox.remove()
cubeRender.init();
clearTimeout(dalayTimer)
},interval)
}
},interval)
})
//控制文字及其打印机
let textMove=function(){
let text=$keyBordText.html()
$keyBordText.css("display","block").html("");
let timer=null,
n=-1;
timer=setInterval(()=>{
if(n>=text.length){
//打印机效果完成,让发送按钮显示(并且给发送绑定事件)
$keyBordText.html(text)
$submit.css("display","block").tap(()=>{
$keyBordText.css("display","none")
$keyBord.css("transform","translateY(3.7rem)")
$plan.fire()//此时计划表中只有一个方法,从新通知
})
clearInterval(timer);
return
}
n++;
$keyBordText[0].innerHTML+=text.charAt(n)
},500)
}
return {
init:function () {
$messageBox.css("display","block");
musicAudio.play()
$plan.fire()
}
}
})()
// cube
//只要在移动端实现滑动操作,都需要把浏览器默认滑动行为禁止掉
$(document).on('touchstart touchmove touchend',function (e) {
e.preventDefault()
})
let cubeRender=(function ($) {
let $cubeBox=$(".cubeBox"),
$box=$cubeBox.find(".box")
let touchBegin=function(e){
let point=e.changedTouches[0];
$(this).attr({
strX:point.clientX,
strY:point.clientY,
isMove:false,
changeX:0,
changeY:0
})
}
let touching=function(e){
let point=e.changedTouches[0];
let $this=$(this);
let changeX=point.clientX-parseFloat($this.attr("strX")),
changeY=point.clientY-parseFloat($this.attr("strY"));
if(Math.abs(changeX)>10||Math.abs(changeY)>10){
$this.attr({
isMove:true,
changeX:changeX,
changeY:changeY
})
}
}
let touchEnd=function (e) {
let point=e.changedTouches[0];
$this=$(this);
let isMove=$this.attr("isMove"),
changeX=parseFloat($this.attr("changeX")),
changeY=parseFloat($this.attr("changeY")),
rotateX=parseFloat($this.attr("rotateX")),
rotateY=parseFloat($this.attr("rotateY"));
if(isMove=="false") return;
rotateX=rotateX-changeY/3;
rotateY=rotateY+changeX/3;
$this.css(`transform`,`scale(0.6) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`).attr({
rotateX:rotateX,
rotateY:rotateY
})
}
return{
init:function(){
$cubeBox.css("display","block")
$box.attr({
rotateX:-30,
rotateY:45
}).on({
touchstart:touchBegin,
touchmove:touching,
touchend:touchEnd
})
$box.find('li').tap(function () {
$cubeBox.css('display','none');
let index=$(this).index();
detailRender.init(index)
})
}
}
})(Zepto)
let detailRender=(function () {
let $detailBox=$(".detailBox");
let $returnLink=$detailBox.find(".returnLink"),
$cubeBox=$(".cubeBox");
let swipeExample=null;
let $makisuBox=$("#makisuBox")
let change=function(example){
let {slides:slideAry,activeIndex}=example;
//page1单独的处理
if(activeIndex==0){
$makisuBox.makisu({
slector:"dd",
speed:0.5,
overlap:.6
})
$makisuBox.makisu("open")
} else{
$makisuBox.makisu({
slector:"dd",
speed:0,
overlap:0
})
$makisuBox.makisu("close")
}
//当前活动块设置id,其它块移除
[].forEach.call(slideAry,(item,index)=>{
if(index==activeIndex){
item.id="page"+(activeIndex+1)
return
}
item.id=null;
})
}
return{
init:function(index=0){
$detailBox.css("display","block");
//init swiper
if(!swipeExample){
$returnLink.tap(()=>{
$detailBox.css("display","none")
$cubeBox.css("display","block")
})
swipeExample=new Swiper(".swiper-container",{
effect:"coverflow",
onInit:change,
onTransitionEnd:change
});
}
index=index>5?5:index;
swipeExample.slideTo(index,0);//运动到指定索引的slide位置,第二个参数是SPEED,我们设置0让其立即运动到指定位置
}
}
})()
loadingRender.init() | 054fd6dcd2f89d3503add4c9ee82d375d6f2ca6c | [
"JavaScript"
] | 1 | JavaScript | zhilixue/resume | 29d3292e6d11f79cd09122fe88f125b774421ab2 | 66cee57ba242dec689b62d72a808618d2b2786cd |
refs/heads/main | <repo_name>utkarshmaken/springlearn<file_sep>/src/main/java/utkarsh/maken/springlearn/bootstrap/BootStrapData.java
package utkarsh.maken.springlearn.bootstrap;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import utkarsh.maken.springlearn.model.Author;
import utkarsh.maken.springlearn.model.Book;
import utkarsh.maken.springlearn.model.Publisher;
import utkarsh.maken.springlearn.repositories.AuthorRepository;
import utkarsh.maken.springlearn.repositories.BookRepository;
import utkarsh.maken.springlearn.repositories.PublisherRepository;
@Component
public class BootStrapData implements CommandLineRunner {
private final AuthorRepository authorRepository;
private final BookRepository bookRepository;
private final PublisherRepository publisherRepository;
public BootStrapData(AuthorRepository authorRepository, BookRepository bookRepository, PublisherRepository publisherRepository) {
this.authorRepository = authorRepository;
this.bookRepository = bookRepository;
this.publisherRepository = publisherRepository;
}
@Override
public void run(String... args) throws Exception {
Publisher publisher = new Publisher();
publisher.setName("McGraw");
publisher.setCity("Dhanbad");
publisher.setState("JH");
publisher.setAddressLine1("Katras");
publisherRepository.save(publisher);
Author norman = new Author("Norman", "<NAME>");
Book positive = new Book("The Power of Positive Thinking", "123321");
norman.getBooks().add(positive);
positive.getAuthors().add(norman);
positive.setPublisher(publisher);
publisher.getBooks().add(positive);
authorRepository.save(norman);
bookRepository.save(positive);
publisherRepository.save(publisher);
System.out.println("Started in Bootstrap");
System.out.println("Total number of books = " + bookRepository.count());
System.out.println("Publishers count = " + publisherRepository.count());
}
}
| 0425d26160bf9b455d56abc59847cb928b5a94ef | [
"Java"
] | 1 | Java | utkarshmaken/springlearn | 6a2dbd9e102dda6976f68cb0c4f2100bf6843f0a | 88659ceca41f34443d0428bdbfba0703ebd2af57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.