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>XZolon/cosc190as1<file_sep>/README.md
cosc195as1
==========
COSC195 AS 1
<file_sep>/BlackJackActivity/src/com/siast/cst/blackjackactivity/Player.java
package com.siast.cst.blackjackactivity;
import java.util.Vector;
public class Player
{
Vector<Card> cards;
public Player()
{
cards = new Vector<Card>();
}
public void addCard( Card c )
{
cards.add( c );
}
// NOTE: Modified to include Soft Ace functionality
public int getScore()
{
int score = 0;
int aces = 0;
for( Card c : cards )
{
score += c.getValue();
if (c.getValue() == 11)
{
aces += 1;
}
}
while (score > 21 && aces > 0)
{
score -= 10;
aces -= 1;
}
return score;
}
public Vector<Card> removeCards()
{
Vector<Card> discardedCards = new Vector<Card>( cards );
cards.clear();
return discardedCards;
}
}
| 9e6b491f77261d5a79c3b332d8c4e526ed8a762d | [
"Markdown",
"Java"
]
| 2 | Markdown | XZolon/cosc190as1 | 54f73a532a4087161d1dc38bc3e1ef13c4c99273 | 7ee143015f535e0626cd8b3bd88bad7cb6668c19 |
refs/heads/master | <repo_name>lockejustin/GC_Lab4<file_sep>/GC_Lab4/Program.cs
using System;
namespace GC_Lab4
{
class Program
{
static void Main(string[] args)
{
bool continueProgram = true;
while (continueProgram)
{
int num = PromptForInteger("Please enter an integer to generate a powers table");
CreatePowersTable(num);
continueProgram = ContinueProgram("Would you like to continue with a new number?");
}
}
public static bool ContinueProgram(string message) //prompts user if they'd like to continue and verifies proper entry
{
Console.Write($"{message} (y/n) ");
string response = Console.ReadLine().ToLower();
while (response != "y" && response != "n" )
{
Console.Write("Your entry was invalid. Please respond (y/n) ");
response = Console.ReadLine().ToLower();
}
if (response == "y")
{
Console.WriteLine("\n");
return true;
}
else
{
Console.WriteLine("\nThanks for using this program. Goodbye!");
return false;
}
}
public static void CreatePowersTable (int n) //creates a powers table based on the integer passed
{
Console.WriteLine("Number\t\tSquared\t\tCubed");
Console.WriteLine("=======\t\t=======\t\t=======");
int square = n;
int cube = n;
for (int i = 1; i <= n; i++)
{
Console.WriteLine($"{i}\t\t{i*i}\t\t{i*i*i}");
}
}
public static int PromptForInteger (string message) //prompts user for an integer and verifies the entry
{
int number = 0;
Console.Write(message + ": ");
string input = Console.ReadLine();
while (!int.TryParse(input, out number))
{
Console.Write("Invalid entry. Please enter a valid integer. ");
input = Console.ReadLine();
}
return number;
}
}
}
| 310a86293002f6f329d1a6700669380e7ed42727 | [
"C#"
]
| 1 | C# | lockejustin/GC_Lab4 | 1ca626e48d6d65dbf25248359a317ecd552c0d2d | 42f2d85331d84d3fe11d202bdde95e826d16dac8 |
refs/heads/master | <file_sep>import React from 'react';
function Blue() {
const blockStyle = {
height: '500px',
width: '500px',
backgroundColor: 'blue'
};
return <div style={blockStyle} />;
}
export default Blue;
<file_sep>import React from 'react';
function Red() {
const blockStyle = {
height: '500px',
width: '500px',
backgroundColor: 'red'
};
return <div style={blockStyle} />;
}
export default Red;
<file_sep>import React from 'react';
function Yellow() {
const blockStyle = {
height: '500px',
width: '500px',
backgroundColor: 'yellow'
};
return <div style={blockStyle} />;
}
export default Yellow;
| 1c4733ea0597521e01f7167d3116f32bd8e2f3f3 | [
"JavaScript"
]
| 3 | JavaScript | UncleJerry23/react-routes | 64e496c2c1e21bf6482d48105d1eca8c54c847f4 | 5d47fe57c3bba9da3f50e99bf95c2fd1cdfdf1e4 |
refs/heads/master | <file_sep><?php
namespace NodePub\Provider;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use NodePub\Monolog\JsonFormatter;
use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Configures Monolog to log messages as json objects
*/
class MonologJsonServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['json_logger'] = function() use ($app) {
return $app['monolog.json'];
};
if (class_exists('Symfony\Bridge\Monolog\Logger')) {
$app['monolog.json.logger.class'] = 'Symfony\Bridge\Monolog\Logger';
} else {
$app['monolog.json.logger.class'] = 'Monolog\Logger';
}
$app['monolog.json.formatter.class'] = 'NodePub\Monolog\JsonFormatter';
$app['monolog.json'] = $app->share(function ($app) {
$log = new $app['monolog.json.logger.class']($app['monolog.json.name']);
$log->pushHandler($app['monolog.json.handler']);
return $log;
});
$app['monolog.json.handler'] = function() use ($app) {
$handler = new StreamHandler($app['monolog.json.logfile'], $app['monolog.json.level']);
$handler->setFormatter(new $app['monolog.json.formatter.class']());
return $handler;
};
$app['monolog.json.level'] = function() {
return Logger::DEBUG;
};
$app['monolog.json.name'] = 'myapp';
}
public function boot(Application $app)
{
$app->before(function(Request $request) use ($app) {
$app['monolog.json']->addInfo(
'request',
$this->getRequestProperties($request)
);
});
$app->error(function(\Exception $e, $code) use ($app) {
$app['monolog.json']->addError(
'error',
array_merge(
$this->getRequestProperties($app['request']),
array(
'error_code' => $code,
'error_message' => $e->getMessage(),
)
);
);
});
}
protected function getRequestProperties(Request $request)
{
return array(
'host' => $request->getHost(),
'request_method' => $request->getMethod(),
'request_uri' => $request->getRequestUri(),
'ip_address' => $request->getClientIp()
);
}
}
<file_sep><?php
namespace NodePub\Monolog;
use Monolog\Formatter\FormatterInterface;
/**
* Encodes whatever record data is passed to it as json,
* based on the original JsonFormatter in Monolog core
*/
class JsonFormatter implements FormatterInterface
{
const DATE_FORMAT = 'Y-m-d H:i:s';
protected $filteredKeys = array('extra', 'channel');
public function format(array $record)
{
return json_encode($this->filterRecord($record)).PHP_EOL;
}
public function formatBatch(array $records)
{
return array_map(array($this, 'format'), $records);
}
/**
* Filters out record keys from Monolog that we don't need
*/
protected function filterRecord(array $record)
{
foreach ($this->filteredKeys as $key) {
if (isset($record[$key]) {
unset($record[$key]);
}
}
// Convert datetime object to string
if (! isset($record['datetime'])) {
$record['datetime'] = new \DateTime("now");
}
$record['datetime'] = $record['datetime']->format(self::DATE_FORMAT);
return $record;
}
}
<file_sep>Monolog JSON Service Provider
=============================
Silex service provider for logging events as json objects.
| eaa1f9c145c254b791e3642d2c21c0532a7ba851 | [
"Markdown",
"PHP"
]
| 3 | PHP | nodepub/monolog-json-service-provider | 043c74503c36aea608cae2286776809580762d85 | 4b27f253dab4970a5bf9d9ea935ff5d3334e8b04 |
refs/heads/master | <file_sep>"use strict";
IScoreLog;
{
penalty: number,
advantage;
number,
score;
number,
timeStamp;
Date;
}
<file_sep>export default (req,res,next) => {
res.status(404);
res.send('404 Not Found');
}<file_sep>"use strict";
exports.__esModule = true;
var express_1 = require("express");
var competitorRouter = express_1["default"].Router();
competitorRouter.use(function (req, res, next) {
next();
});
competitorRouter.get("/", function (req, res) {
res.send("competitor");
})
.get("/register", function (req, res) {
res.send("register");
})
.get("/login", function (req, res) {
res.send("login");
});
exports["default"] = competitorRouter;
<file_sep>"use strict";
var login_1 = require("./login");
var registeration_1 = require("./registeration");
exports["default"] = {
Login: login_1["default"],
Register: registeration_1["default"]
};
<file_sep>import express from "express";
const trainerRouter = express.Router();
trainerRouter.use((req,res,next) => {
next();
});
trainerRouter.get("/",(req,res) => {
res.send("trainer");
})
.get("/register",(req,res) => {
res.send("trainer register");
})
.get("/login",(req,res) => {
res.send("trainer login");
})
export default trainerRouter;<file_sep>"use strict";
exports.__esModule = true;
var pageNotFound_1 = require("./pageNotFound");
exports["default"] = {
pageNotFoundMiddleware: pageNotFound_1["default"]
};
<file_sep>"use strict";
exports.__esModule = true;
var express_1 = require("express");
var index_js_1 = require("./controllers/index.js");
var mongoose_1 = require("mongoose");
var path_1 = require("path");
console.log("routes", index_js_1["default"]);
var server = express_1["default"]();
var dbOptions = {
useNewUrlParser: true
};
// server configuration
console.log("start server configuration\n");
server.use(express_1["default"].static("dist/public"));
// server.use(express.static("./dist/public'));
// server.use(bodyParser);
// server.use(express.static(path.join(__dirname, '../client/build')))
//Middlewares
// ROUTES
server.get("/", function (req, res) {
console.log("dirname in route", path_1["default"].dirname('/dist/public/index.html'));
// res.sendFile(__dirname + '/index.html');
res.sendFile('index.html');
});
server.use("/competitor", index_js_1["default"].competitorRouter);
server.use("/trainer", index_js_1["default"].trainerRouter);
// server.use(Middlewares.pageNotFoundMiddleware);
// LISTEN
// process.env.PORT
server.listen(8080, function (e) {
console.log("start server listening\n");
(e ? console.log("server listen error:", e) : console.log("server is up"));
});
// DB CONNECT
console.log("connect to db\n");
var dbUrl = 'mongodb://' + process.env.IP;
mongoose_1["default"].connect(dbUrl).then(function () {
console.log("db is connected");
})["catch"](function (e) {
console.log("server connect to db errorw:", e);
});
<file_sep>import Login from "./login";
import Register from "./registeration";
export default {
Login: Login,
Register: Register
};<file_sep>"use strict";
var FormInput_1 = require("./FormInput");
var FormSection_1 = require("./FormSection");
exports["default"] = {
FormInput: FormInput_1["default"],
FormSection: FormSection_1["default"]
};
<file_sep>export default interface IScoreLog {
penalty: number,
advantage: number,
score: number,
timeStamp: Date
}<file_sep>const webpack = require('webpack')
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const glob = require("glob");
// CONSOLE LOG
console.log("###########")
console.log("#start webpack#")
console.log("###########")
module.exports = {
entry: {
server: glob.sync("./src/server/**/*.ts"),
},
output: {
filename: '[name].js',
path: path.resolve("./", 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
watch: true,
plugins: [
new CleanWebpackPlugin(['dist']),
new webpack.ProgressPlugin()]
,
resolve: {
modules: ['node_modules'],
extensions: ['.jsx','.ts']
},
node: {
fs: 'empty',
child_process: 'empty',
net: 'empty'
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};
//./node_modules/.bin/babel ./src -w --out-dir javascript_src --extensions .ts && node ./javascript_src/server.js
<file_sep>import pageNotFoundMiddleware from "./pageNotFound";
export default {
pageNotFoundMiddleware: pageNotFoundMiddleware
}<file_sep>"use strict";
var redux_1 = require('redux');
//reducers
var score_1 = require("./score");
var timer_1 = require("./timer");
exports["default"] = redux_1.combineReducers({
score: score_1["default"],
timer: timer_1["default"]
});
<file_sep>import { combineReducers } from 'redux';
//reducers
import scoreReducer from "./score";
import timerReducer from "./timer";
export default combineReducers(
{
score:scoreReducer,
timer:timerReducer
}
);<file_sep>"use strict";
var initState = {
timerOn: 0,
timeToCount: 0,
timer: 0,
second: 0,
minute: 0
};
exports["default"] = function (state, action) {
if (state === void 0) { state = initState; }
switch (action) {
default:
return state;
}
};
<file_sep>import express from"express";
import Routes from "./controllers/index.js";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import Middlewares from "./middlewares/index.js";
import path from "path";
console.log("routes",Routes)
const server = express();
const dbOptions = {
useNewUrlParser: true
};
// server configuration
console.log("start server configuration\n");
server.use(express.static("dist/public"));
// server.use(express.static("./dist/public'));
// server.use(bodyParser);
// server.use(express.static(path.join(__dirname, '../client/build')))
//Middlewares
// ROUTES
server.get("/",(req,res) => {
console.log("dirname in route",path.dirname('/dist/public/index.html'));
// res.sendFile(__dirname + '/index.html');
res.sendFile('index.html')
});
server.use("/competitor",Routes.competitorRouter);
server.use("/trainer",Routes.trainerRouter);
// server.use(Middlewares.pageNotFoundMiddleware);
// LISTEN
// process.env.PORT
server.listen(8080,(e) => {
console.log("start server listening\n");
(e ? console.log("server listen error:",e) : console.log("server is up"));
});
// DB CONNECT
console.log("connect to db\n");
let dbUrl = 'mongodb://' + process.env.IP;
mongoose.connect(dbUrl).then(() => {
console.log("db is connected");
})
.catch((e) => {
console.log("server connect to db errorw:",e);
});
<file_sep>import trainerRouter from "./trainer";
import competitorRouter from "./competitor";
export default {
trainerRouter: trainerRouter,
competitorRouter: competitorRouter
}
<file_sep>const initState = {
name: "",
coach: "",
penalty: 0,
advantage: 0,
point: 0
}
export default (state = initState, action: any) => {
switch(action){
default:
return state;
}
}<file_sep>import express from "express";
const competitorRouter = express.Router();
competitorRouter.use((req,res,next) => {
next();
});
competitorRouter.get("/",(req,res) => {
res.send("competitor");
})
.get("/register",(req,res) => {
res.send("register");
})
.get("/login",(req,res) => {
res.send("login");
})
export default competitorRouter;<file_sep>const initState = {
timerOn: 0,
timeToCount: 0,
timer: 0,
second: 0,
minute: 0
}
export default (state = initState,action: any) => {
switch(action){
default:
return state;
}
}<file_sep># competition-app
## How to run?
##Server:
1. cd dist directory
2. run in terminal: node server.js,this will activate the backend files system bundle
## Compilation
1. cd the root directory
2. run in terminal: npm run-script dev,this will create a server bundle and live compilation of the front end files, the live compilation for the server files is not defined yet.
<file_sep>"use strict";
exports.__esModule = true;
exports["default"] = (function (req, res, next) {
res.status(404);
res.send('404 Not Found');
});
<file_sep>"use strict";
exports.__esModule = true;
var trainer_1 = require("./trainer");
var competitor_1 = require("./competitor");
exports["default"] = {
trainerRouter: trainer_1["default"],
competitorRouter: competitor_1["default"]
};
<file_sep>import FormInput from "./FormInput";
import FormSection from "./FormSection";
export default {
FormInput: FormInput,
FormSection: FormSection
} | 483b2056e1fd07fea8e1c9a51ba90f01647e1a42 | [
"JavaScript",
"TypeScript",
"Markdown"
]
| 24 | JavaScript | omriwa/competition-app | 84a7462a991f08420c71a7a61220640558a471a5 | 239821ecb2d24ef0e2e41e503723a905f4750323 |
refs/heads/master | <repo_name>severli93/Dashboard-Design-Practice<file_sep>/script/usMap.js
const margin = {top: 20, right: 20, bottom: 30, left: 20};
// MAP SVG //
const width = d3.select(".mapDiv").node().clientWidth;
const widthLeft = d3.select(".productImgDiv").node().clientWidth;
const widthRight = d3.select(".salesDiv").node().clientWidth;
const height = d3.select(".productImgDiv").node().clientHeight;
const plotWidth = width - margin.left - margin.right;
const plotWidthLeft = widthLeft - margin.left - margin.right;
const plotWidthRight = widthRight - margin.left - margin.right;
const plotHeight = height - margin.top - margin.bottom;
let colorNow,strokeNow;
const mapSvg = d3.select("#mapUS")
.append('svg')
.classed('mapSvg',true)
.attr("width", width)
.attr("height", height);
mapSvg.append('text')
.classed('chartTitle h4', true)
.text('Map')
.attr('transform', 'translate('+width/2+','+(height-10)+')');
const projection = d3.geoAlbersUsa()
.scale(height*1.8)
.translate([width/2,height/2]);
const path = d3.geoPath().projection(projection);
queue()
.defer(d3.json,"./data/us.json")
// .defer(d3.json,'./data/usPop.json')
.await(results);
function results (err,usData,usPop) {
if (err) throw error;
drawMap(mapSvg,usData,path);
}
function drawMap (mapSvg,usData) {
mapSvg.selectAll("path")
.data(usData.features)
.enter()
.append('path')
.attr('d', path)
.style('stroke','#061223')
.on('mouseenter', mouseenterColorPop)
.on('mouseleave', mouseleaveColorPop);
}
// Sales SVG
// const width2 = d3.select(".salesDiv").node().clientWidth;
// const height2 = d3.select(".productImgDiv").node().clientHeight;
const salesSvg = d3.select("#salesPlot").append('svg')
.attr("width", widthRight)
.attr("height", height);
const salesG = salesSvg.append('g')
.classed('rectShape',true)
.attr('transform', 'translate('+margin.left+','+margin.top+')');
salesSvg.append('text')
.classed('chartTitle h4', true)
.text('Sales')
.attr('transform', 'translate('+widthRight/2+','+(height-10)+')');
let data = d3.range(0, 20, 1).map(d => Math.random()*200);
const scaleY = d3.scaleLinear().domain([0, data.length]).range([0, plotHeight]);
const scaleX = d3.scaleLinear().domain([0, 200]).range([0, plotWidthRight]);
var color = d3.scaleOrdinal(d3.schemeCategory20b);
// const colorScale = d3.scaleLiner().domain([])
salesG
.selectAll('rectShape')
.data(data)
.enter()
.append('rect')
.attr('x', 0)
.attr('y', (d,i) => scaleY(i))
.style('fill', function (d,i) { return color(i); })
.on('mouseenter', mouseenterColorPop)
.on('mouseleave', mouseleaveColorPop)
.transition().duration(2500)
.attr('width', d => scaleX(d))
.attr('height', plotHeight/data.length - 5);
// Social plot
const socialSvg = d3.select('#socialPlot').append('svg')
.attr('width', widthLeft).attr('height', height/2);
const socialG = socialSvg.append('g')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
const media = ['facebook', 'twitter', 'instagram'];
data = d3.range(0, 3, 1).map(i => {
const obj = { media: media[i] };
obj.value = 30+Math.random()*60;
return obj;
});
const radialScale = d3.scaleLinear().domain([0, 100]).range([0, 360]);
const ordScale = d3.scaleOrdinal().domain(media).range(d3.range(0, widthLeft, widthLeft/3));
const d3Arc = d3.arc().innerRadius(height/4-40).outerRadius(height/4-30).startAngle(0);
const socialMediaG = socialG.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('class', d => (d.media))
.attr('transform', d => 'translate('+(ordScale(d.media)+height/8)+','+height/4+')');
function polarToCartesian (centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}
function describeArc (x, y, radius, startAngle, endAngle) {
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
var d = [
"M", start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
}
socialMediaG.append('path')
.classed('socialPath', true)
.attr('d', d => describeArc(0,0,height*0.15,0,radialScale(d.value)));
socialMediaG
.append('text')
.classed('h2 socialNumber',true)
.attr('x',0)
.attr('y',height*0.03)
.transition().duration(200)
.attr('height',height/4)
.attr('width',height/4)
.text(d => { return (d.value/100).toFixed(2)+"%"; });
// Activity plot
const activitySvg = d3.select("#activityPlot").append('svg')
.attr("width", d3.select("#activityPlot").node().clientWidth)
.attr("height", height+10);
const activityG = activitySvg.append('g')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
data = d3.range(0, 3, 1).map(i => {
const obj = { media: media[i] };
// assuming chart shows data for 180 days
obj.values = d3.range(0,180,1).map(d => Math.random()*100);
return obj;
});
const scaleXActivity = d3.scaleLinear().domain([0, 180]).range([0, d3.select("#activityPlot").node().clientWidth - margin.left - margin.right]);
const scaleYActivity = d3.scaleLinear().domain([0, 100]).range([0, plotHeight/3]);
const line = d3.line().x((d,i) => scaleXActivity(i)).y(d => scaleYActivity(d));
const mediaG = activityG.selectAll('g')
.data(data)
.enter()
.append('g')
.attr('class', d => d.media)
.attr('transform', (d, i) => 'translate(0,'+i*(plotHeight/3)+')');
// console.log('data',data);
mediaG.append('path')
.attr('class', 'activity-timeseries')
.datum(d => d.values)
.attr('d', line);
activityG.append('text')
.classed('chartTitle h4', true)
.text('Social Activities')
.attr('transform', 'translate('+width/2+','+(plotHeight+margin.bottom)+')');
// activity tooltips
const detailSvg1 = d3.select("#tooltip1").append('svg')
.attr("width", widthRight)
.attr("height", plotHeight/3)
.append('g')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
detailSvg1
.append('text')
.classed('detailTitle h3',true)
.text('#SummerWithBMW')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
const detailSvg2 = d3.select("#tooltip2").append('svg')
.attr("width", widthRight)
.attr("height", plotHeight/3)
.append('g')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
detailSvg2
.append('text')
.classed('detailTitle h3',true)
.text('#SummerWithBMW');
const detailSvg3 = d3.select("#tooltip3").append('svg')
.attr("width", widthRight)
.attr("height", plotHeight/3)
.append('g')
.attr('transform', 'translate('+margin.left+','+margin.top+')');
detailSvg3
.append('text')
.classed('detailTitle h3',true)
.text('#SummerWithBMW');
const detailSvg = d3.select("#bottomName").append('svg')
.attr("width", widthRight)
.attr("height", margin.bottom+10);
detailSvg
.append('text')
.classed('chartTitle h4',true)
.text('Details')
.attr('transform', 'translate('+widthRight/2+','+(margin.bottom)+')');
// interaction of mapDiv
function mouseenterColorPop (d) {
colorNow=this.style.fill;
d3.select(this) // this --> selection
.transition()
.duration(100)
.style('fill','#11f2c6')
.style('stroke','#fbae17')
.style('stoke-width','10px');
}
function mouseleaveColorPop (d) {
d3.select(this)
.transition()
.duration(5000)
.style('fill', colorNow)
.style('stroke','inherit');
}
function colorPup (selection) {
selection.on('mouseenter',function (d) {
colorNow=this.style.fill;
strokeNow=this.style.stroke;
console.log('stroke',strokeNow);
d3.select(this) // this --> selection
.transition()
.duration(200)
.style('fill','rgba(0,0,255,.1)')
.style('stroke','#fbae17')
.style('stoke-width','10px');
}).on('mouseleave',function (d) {
d3.select(this)
.transition()
.duration(5000)
.style('fill', colorNow)
.style('stroke','#061223')
});
}
| 211e0f9de1c6953c1b7bd367474817abc2abfe94 | [
"JavaScript"
]
| 1 | JavaScript | severli93/Dashboard-Design-Practice | 7276636f4e2572c30d57d99667f1d219a5ced8a8 | 017cffc4670061d0d19be36a722c9b4c7fb259ce |
refs/heads/master | <repo_name>katherineRamirez/cumplo<file_sep>/src/components/Navigation/Navigation.js
import React, { Component } from 'react';
import logoCumplo from './../../logoCumplo.svg';
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
import UfExt from './../Uf/UfExt';
import DolarExt from './../Dolar/DolarExt';
import './Navigation.css'
class Navigation extends React.Component {
render() {
return (
<Navbar collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<a href="#home"><img className='logo' src={logoCumplo}/></a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<NavItem eventKey={1} href="#uf">
UF
</NavItem>
<NavItem eventKey={2} href="#dolar">
DOLAR
</NavItem>
<NavItem eventKey={3} href="#grafico">
GRAFICO
</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
export default Navigation;<file_sep>/src/components/Dolar/InputDolar.js
import React, { Component } from 'react';
import { Grid, Row, Col, Clearfix } from 'react-bootstrap';
import './Dolar.css';
class InputDolar extends React.Component{
render(){
return(
<Grid>
<Row className="grid">
<Col xs={6} md={6}>
<label>
Fecha inicial:
</label>
<p><input id="dolarInicial" type="text" placeholder="Ej. 01-2010" /></p>
<p><input type="submit" value="Buscar" /></p>
</Col>
<Col xs={6} md={6}>
<label>
Fecha final:
</label>
<p><input id="dolarFinal" type="text" placeholder="Ej. 01-2010" /></p>
<p><input type="submit" value="Buscar" /></p>
</Col>
</Row>
</Grid>
)
}
}
export default InputDolar;<file_sep>/src/components/Dolar/DolarExt.js
import React, { Component } from 'react';
import { Table } from 'react-bootstrap';
import './Dolar.css';
const Dato = ( props ) =>(
<Table striped bordered condensed hover className="table">
<thead>
<tr>
<th><strong>Valor</strong></th>
<th><strong>Fecha</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>{props.Valor}</td>
<td>{props.Fecha}</td>
</tr>
</tbody>
</Table>
)
class DolarExt extends React.Component {
constructor(props) {
super(props)
this.state = {
dolarExt:[]
}
}
componentWillMount(){
fetch('https://api.sbif.cl/api-sbifv3/recursos_api/dolar/2010/01?apikey=<KEY>&formato=json&callback=despliegue')
.then(response => response.json())
.then(dolarExt =>{
dolarExt.Dolares.forEach(resp => {
let dato = {
Valor:resp.Valor,
Fecha:resp.Fecha
}
this.setState({ dolarExt:this.state.dolarExt.concat([dato]) })
})
})
}
render(){
if( this.state.dolarExt.length > 0 ){
return(
<div id="dolar">
{ this.state.dolarExt.map(resp => <Dato Valor={resp.Valor} Fecha={resp.Fecha}/>) }
</div>
)
}
return(
<p>Cargando datos...</p>
)
}
}
export default DolarExt;<file_sep>/src/components/Uf/InputUf.js
import React, { Component } from 'react';
import { Grid, Row, Col, Clearfix } from 'react-bootstrap';
import './Uf.css';
class InputUf extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
};
}
initialDateUf = () => {
this.setState(state => ({ value: state.value }));
};
finalDateUf = () => {
this.setState(state => ({ value: state.value }));
};
render() {
return (
<Grid>
<Row className="grid">
<Col xs={6} md={6}>
<label>
Fecha inicial:
</label>
<p><input id="ufInicial" type="text" placeholder="Ej. 01-2010" ref={this.value} /></p>
<p><input type="submit" onClick={this.initialDateUf} value="Buscar" /></p>
</Col>
<Col xs={6} md={6}>
<label>
Fecha final:
</label>
<p><input id="ufFinal" type="text" placeholder="Ej. 01-2010" ref={this.value} /></p>
<p><input type="submit" onClick={this.finalDateUf} value="Buscar" /></p>
</Col>
</Row>
</Grid>
);
}
}
export default InputUf;<file_sep>/src/App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import Navigation from './components/Navigation/Navigation';
import Header from './components/Header/Header';
import Uf from './components/Uf/Uf';
import InputUf from './components/Uf/InputUf';
import Dolar from './components/Dolar/Dolar';
import InputDolar from './components/Dolar/InputDolar';
import UfExt from './components/Uf/UfExt';
import DolarExt from './components/Dolar/DolarExt';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<Navigation></Navigation>
<Header></Header>
<h2>UF 2018</h2>
<Uf></Uf>
<InputUf></InputUf>
<UfExt></UfExt>
<h2>DOLAR</h2>
<Dolar></Dolar>
<InputDolar></InputDolar>
<DolarExt></DolarExt>
</div>
);
}
}
export default App;
<file_sep>/src/components/Uf/Uf.js
import React, { Component } from 'react';
import './Uf.css';
const Data = ( props ) =>(
<li>
<h3>{props.Valor}</h3>
<h5>{props.Fecha}</h5>
</li>
)
class Uf extends React.Component{
constructor(props){
super(props)
this.state = {
ufs:[]
}
}
componentWillMount(){
fetch('https://api.sbif.cl/api-sbifv3/recursos_api/uf?apikey=<KEY>&formato=json&callback=despliegue')
.then(response => response.json())
.then(ufs =>{
ufs.UFs.forEach(resp => {
let data = {
Valor:resp.Valor,
Fecha:resp.Fecha
}
this.setState({ ufs:this.state.ufs.concat([data]) })
})
})
}
render(){
if( this.state.ufs.length > 0 ){
return(
<div>
{ this.state.ufs.map(resp => <Data Valor={resp.Valor} Fecha={resp.Fecha}/>) }
</div>
)
}
return(
<p>Cargando datos...</p>
)
}
}
export default Uf;<file_sep>/src/components/Header/Header.js
import React, { Component } from 'react';
import imgHeader from './../../imgHeader.jpg';
import './Header.css'
class Header extends React.Component {
render() {
return (
<img className='imgHeader' src={imgHeader}/>
)
}
}
export default Header; | c5c72af48ef4f8cdee68e2c0095b84d21f87d44b | [
"JavaScript"
]
| 7 | JavaScript | katherineRamirez/cumplo | 2767cff3d8875288fc39605f5e4e2849c7a9114d | 8e29fe580718931ef0299049b3123c311c4150d3 |
refs/heads/master | <file_sep>import React from "react";
import "./MapView.css";
import SearchBox from "../SearchBox/SearchBox";
import UseMyLocation from "../UseMyLocation/UseMyLocation";
import MapUI from "../MapUI/MapUI"
export default class MapView extends React.Component {
constructor(props){
super(props)
this.state = { latLng:{lat: 40.756795,
lng: -73.954298}};
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e1,e2,e3){
//console.log('map',e1,e2,e3)
this.setState({latLng:
{lat: Number(e2),
lng: Number(e3)}
});
this.props.getValue(e1,e2,e3);
}
render() {
return (
<div id="map-view" className="MapView">
<div className="MapUI">
<MapUI latLng={this.state.latLng} />
</div>
<div className="SearchBoxContainer">
<SearchBox onSubmit={this.onSubmit}/>
</div>
<div className="UseMyLocationContainer">
<UseMyLocation />
</div>
</div>
);
}
}
<file_sep>export const GOOGLE_API_KEY = "<KEY>";
export const YELP_API_KEY =
"<KEY>";
| fdf8c7c6e3eb1d0c15a16c9a385a5b439366c565 | [
"JavaScript"
]
| 2 | JavaScript | yellowspectre/yelp-clone | b5ec06e17b0714133f6fbd23a9923f23a00a0dfb | b6de88a4a005e39012ec048073bc9482bd711c99 |
refs/heads/master | <file_sep>const express=require('express');
const router=express.Router();
const userController = require("../../controller/userscontroller");
// user register routes
router.post('/register',userController.register);
router.post('/login',userController.login);
router.post('/verify-user-email',userController.verifyEmail);
module.exports=router;<file_sep>const express=require('express');
const router=express.Router();
router.use('/user/perchase',require('./perchase_route'));
router.use('/admin/product',require('./product_route'));
router.use('/user',require('./user_api'));
module.exports =router;<file_sep>const mongoose=require('mongoose');
// user schema
const BasicUserSchema = new mongoose.Schema({
email:{
type:String,
unique: true,
},
firstName:{
type:String,
default: null,
},
lastName:{
type:String,
default: null,
},
password:{
type:String,
},
phone:{
type:Number,
default: null,
},
userActiveStatus:{
type:String,
enum:["Active","Deactive","Pending"],
},
token:{
type:String,
},
UserType:{
type:String,
enum:["Admin","Normal"],
}
},{
timestamps:true
});
const basic_user=mongoose.model('User',BasicUserSchema);
module.exports=basic_user; <file_sep>const jwt = require("jsonwebtoken");
const { user } = require("passport");
const { json } = require("body-parser");
const bcrypt = require('bcrypt');
const dotenv = require('dotenv');
const User = require("../models/users");
const { response } = require("express");
const nodemailer = require('nodemailer');
const SecretCode = require('../models/secretcode');
dotenv.config({ path: '../config/credential.env' })
global.crypto = require('crypto');
module.exports.register = async (req, res) => {
try {
// Get user input
const { firstName, lastName, email, password,phone,userActiveStatus,UserType } = req.body;
// Validate user input
if (!(email && password && firstName && lastName)) {
res.status(400).send("All input is required");
}
// check if user already exist
// Validate if user exist in our database
const oldUser = await User.findOne({ email });
if (oldUser) {
return res.status(409).send("User Already Exist. Please Login");
}
//Encrypt user password
encryptedPassword = await bcrypt.hash(password, 10);
// Create user in our database
const user = await User.create({
firstName,
lastName,
email: email.toLowerCase(), // sanitize: convert email to lowercase
password: <PASSWORD>,
phone,
userActiveStatus,
UserType
});
// Create token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.SECRET_KEY,
{
expiresIn: "5h",
}
);
// save user token
user.token = token;
// create secret code here for verify email
const secretCode = await SecretCode.create({
_userId: user._id,
token: crypto.randomBytes(70).toString('hex')
})
// send mail here
let transporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: `${process.env.EMAIL_ADDRESS}`,
pass: `${process.env.EMAIL_PASSWORD}`
},
});
const mailOptions = {
from: '<EMAIL>',
to: user.email,
subject: 'Verify Your Email Address',
text: 'Hello ' + user.firstName + ',\n\n' + 'Please clicking the link below\n\nThank You!\n',
html: '<div>Hi '+user.firstName+'</div><p>You have been invited to EngineerBabu. <button style="background-color: #92a8d1;"><a href="http://localhost:8000/api/user/verify/' + secretCode.token + '">Click here</a></button> to verify your email address.</p><br></br><div>Regards,</div><div>Team EngineerBabu</div>'
};
const data = await transporter.sendMail(mailOptions, function(error, info){
if (error) {
return res.status(400).json({
success: false,
message: 'An error occured.',
results: error
});
} else {
// if mail sent then save this pass to db
return res.status(201).json({
success:true,
message:"User is Register Succeffuly. Verify mail sent to user",
results:user
});
}
});
} catch (err) {
console.log(err);
}
}
module.exports.login = async (req,res)=>{
try {
// Get user input
const { email, password } = req.body;
// Validate user input
if (!(email && password)) {
res.status(400).send("All input is required");
}
// Validate if user exist in our database
const user = await User.findOne({ email });
if (user && (await bcrypt.compare(password, user.password))) {
// Create token
const token = jwt.sign(
{ user_id: user._id, email },
process.env.SECRET_KEY,
{
expiresIn: "5h",
}
);
// save user token
user.token = token;
// user
return res.status(201).json({
success:true,
message:"User is Login Succeffuly",
results:user
});
}
res.status(400).send("Invalid Credentials");
} catch (err) {
console.log(err);
}
}
module.exports.verifyEmail= async (req,res)=>{
try{
await SecretCode.findOne({token: req.body.token}, function (err, token) {
// token is not found into database i.e. token may have expired
if (!token) {
return res.status(400).json({message: 'Something went wrong. Your verification link has expired.',
status:400
});
} else {
User.findOne({_id: token._userId}, function (err, user) {
if (!user) {
res.status(401).json({message:"We are unable to locate user",
status:400
});
} else {
user.updateOne({
"userActiveStatus": "Active",
}, function (err, result) {
if (err) {
res.status(400).json({message:"error is in verification creation",status:400});
} else {
res.status(2001).json(200,{message:"User Verified successfully.",
status:200,
data:result
});
}
})
}
});
}
});
}
catch(error){
console.log(err);
}
}
<file_sep>
const mongoose = require("mongoose");
//mongodb connecting function
const connectDB = async ()=> {
try{
const conet = await mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(`MONGOBD CONNECTED: ${conet.connection.host}`);
}
catch{
console.log(`Error ${err.message}`);
process.exit(1);
}
}
module.exports = connectDB;
<file_sep># Ecommerce api
expresss js apis
<file_sep>const passport = require("passport");
const dotenv = require("dotenv");
const JWTStrategy = require("passport-jwt").Strategy;
const ExtractJWT = require("passport-jwt").ExtractJwt;
const User = require("../models/users");
dotenv.config({ path: "../config/credential.env" });
// core function jwt packege for token generation
let opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_TOKEN_STRING,
};
passport.use('user-rule',
new JWTStrategy(opts, function (jwtPayLoad, done) {
// find user here
User.findOne({_id:jwtPayLoad.userId,UserType:'Normal',userActiveStatus:'Active'}, function (err, user) {
if (err) {
console.log("Error in finding the user from JWT");
return;
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
module.exports = passport;
<file_sep>const mongoose=require('mongoose');
const perchase = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
products: [
{
sku:String,
productId: Number,
name: String,
price: Number,
category:String,
brand:String,
quantity:Number
}
],
active: {
type: Boolean,
default: true
},
modifiedOn: {
type: Date,
default: Date.now
}
},
{ timestamps: true }
);
const perchaseTable=mongoose.model('Perchase',perchase);
module.exports=perchaseTable; <file_sep>const express=require('express');
const router=express.Router();
// import product controller here
const ProductController = require('../../controller/productscontroller');
// authentication middleware
const PassPortAdmin = require('../../middleware/passport-admin');
// Product Related Route Here
router.post('/create-product',PassPortAdmin.authenticate('admin-rule',{session:false}),ProductController.CreateProduct);
router.get('/get-all-products',PassPortAdmin.authenticate('admin-rule',{session:false}),ProductController.ListAllProducts);
router.get('/get-product/:id',PassPortAdmin.authenticate('admin-rule',{session:false}),ProductController.GetProduct);
router.put('/edit/:id',PassPortAdmin.authenticate('admin-rule',{session:false}),ProductController.EditProduct);
router.delete('/delete/:id',PassPortAdmin.authenticate('admin-rule',{session:false}),ProductController.DeleteProduct);
module.exports = router; | eb8bee1526dd4d27c5b700c8eee9571ecd605c78 | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | subhamoydeb/Ecommerce | f4f0cc48376549721824fae76f510a59438bc0aa | e3ee9e134907ccf52fb5cb82609a1604cb4fbd0d |
refs/heads/master | <repo_name>MiliciaUX/thirstalert<file_sep>/app/controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
end
def about
end
def dudes
end
def chicks
end
end
<file_sep>/test/controllers/pages_controller_test.rb
require 'test_helper'
class PagesControllerTest < ActionController::TestCase
test "should get home" do
get :home
assert_response :success
assert_select "title", "ThirstAlert"
end
test "should get about" do
get :about
assert_response :success
assert_select "title", "About | ThirstAlert"
end
test "should get dudes" do
get :dudes
assert_response :success
assert_select "title", "Dudes | ThirstAlert"
end
test "should get chicks" do
get :chicks
assert_response :success
assert_select "title", "Chicks | ThirstAlert"
end
test "should get the_ex" do
get :the_ex
assert_response :success
assert_select "title", "The_Ex | ThirstAlert"
end
end
<file_sep>/test/controllers/static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should get home" do
get :home
assert_response :success
end
test "should get about" do
get :about
assert_response :success
end
test "should get dudes" do
get :dudes
assert_response :success
end
test "should get chicks" do
get :chicks
assert_response :success
end
end
| d06218caee2be6fd8f322fe4dd672e5174038d1c | [
"Ruby"
]
| 3 | Ruby | MiliciaUX/thirstalert | d15b941af2af52e6a8c7042ee3dc24ca05e301ca | 8e8680c4ea767965d3f388e69008041f932dd0bc |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Model\Member;
use Illuminate\Http\Request;
class MemberController extends Controller
{
//验证是否登录
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$members = Member::paginate(5);
return view('member/index',compact('members'));
}
public function create()
{
return view('member/create');
}
public function store(Request $request)
{
//数据验证
$this->validate($request,[
'username'=>'required|max:20|unique:members',
'tel'=>[
'required',
'regex:/^[1][3,4,5,7,8][0-9]{9}$/',
'unique:members',
],
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>:6,20',
'captcha' => 'required|captcha',
],[
'username.required'=>'用户名不能为空',
'username.max'=>'用户名长度不能大于20位',
'username.unique'=>'该用户名已存在',
'tel.required'=>'电话不能为空',
'tell.regexl'=>'请输入正确电话',
'tel.unique'=>'该电话已注册',
'password.required'=>'<PASSWORD>',
'password.between'=>'密码必须在6-20位之间!',
'password_confirmation.required'=>'请确认密码',
'password.confirmed'=>'两次输入密码不一致',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
Member::create([
'username'=>$request->username,
'tel'=>$request->tel,
'password'=><PASSWORD>($request->password),
]);
return redirect()->route('members.index')->with('success','添加会员成功');
}
public function edit(Member $member)
{
return view('member/edit',compact('member'));
}
public function update(Member $member,Request $request)
{
//数据验证
$this->validate($request,[
'username'=>'required|max:20|unique:members',
'tel'=>[
'required',
'regex:/^[1][3,4,5,7,8][0-9]{9}$/',
'unique:members',
],
'captcha' => 'required|captcha',
],[
'username.required'=>'用户名不能为空',
'username.max'=>'用户名长度不能大于20位',
'username.unique'=>'该用户名已存在',
'tel.required'=>'电话不能为空',
'tell.regexl'=>'请输入正确电话',
'tel.unique'=>'该电话已注册',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
$member->update([
'username'=>$request->username,
'tel'=>$request->tel,
]);
return redirect()->route('members.index')->with('success','更新成功');
}
public function destroy(Member $member)
{
$member->delete();
return redirect()->route('members.index')->with('success','删除成功');
}
}
<file_sep><?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Member extends Model
{
//设置权限
protected $fillable = ['username','<PASSWORD>','tel','rememberToken','created_at','updated_at','coin'];
}
<file_sep><?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class ShopUser extends Model
{
//
protected $fillable = ['name','email','password','rememberToken','status','shop_id','created_at]','updated_at'];
public function shop()
{
return $this->belongsTo(Shop::class,'shop_id','id');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Model\Shop;
use App\Model\ShopUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class ShopUsersController extends Controller
{
//
public function index()
{
$shopusers = ShopUser::paginate(5);
return view('shopuser/index',compact('shopusers'));
}
public function create()
{
$shops = Shop::all();
return view('shopuser/create',compact('shops'));
}
public function store(Request $request)
{
//数据验证
$this->validate($request,[
'name'=>'required|max:20|unique:shop_users',
'email'=>'required|email|unique:shop_users',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'shop_id'=>'required',
'captcha' => 'required|captcha',
],[
'name.required'=>'名称不能为空',
'name.max'=>'名称长度不能大于20位',
'name.unique'=>'该名称已存在',
'email.required'=>'邮箱不能为空',
'email.email'=>'邮箱格式错误',
'email.unique'=>'该邮箱已存在',
'password.required'=>'密码必须填写',
'password.min'=>'密码长度不能小于6位',
'password_confirmation.required'=>'请确认密码',
'password.confirmed'=>'两次输入密码不一致',
'shop_id.required'=>'所属商户必须选择',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
if (!$request->status){
$request->status =0;
}
//密码加密
$model = ShopUser::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=><PASSWORD>($request->password),
'status'=>1,
'shop_id'=>$request->shop_id
]);
return redirect()->route('shopusers.index')->with('success','添加成功');
}
public function show(Shopuser $shopuser,Request $request)
{
$shops = Shop::all();
return view('shopuser/show',compact('shopuser','shops'));
}
public function edit(Shopuser $shopuser)
{
//dd($shopuser);
$shops = Shop::all();
return view('shopuser/edit',['shopuser'=>$shopuser,'shops'=>$shops]);
}
public function update(Shopuser $shopuser,Request $request)
{
//数据验证
$this->validate($request,[
'name'=>[
'required',
'max:20',
Rule::unique('shop_users')->ignore($shopuser->id),
],
'email'=>[
'required',
'string',
'email',
Rule::unique('shop_users')->ignore($shopuser->id),
],
'shop_id'=>'required',
'captcha' => 'required|captcha',
],[
'name.required'=>'名称不能为空',
'name.max'=>'名称长度不能大于20位',
'name.unique'=>'该名称已存在',
'email.required'=>'邮箱不能为空',
'email.email'=>'邮箱格式错误',
'email.unique'=>'该邮箱已存在',
'password_confirmation.required'=>'请确认密码',
'password.confirmed'=>'两次输入<PASSWORD>',
'shop_id.required'=>'所属商户必须选择',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
if (!$request->status){
$request->status =0;
}
$shopuser->update([
'name'=>$request->name,
'email'=>$request->email,
'status'=>$request->status,
'shop_id'=>$request->shop_id
]);
return redirect()->route('shopusers.index')->with('success','更新成功');
}
public function destroy(Shopuser $shopuser)
{
$shopuser->delete();
return redirect()->route('shopusers.index')->with('success','删除成功');
}
public function status(Shopuser $shopuser)
{
$shopuser->update([
'status'=>1,
]);
return redirect()->route('shopusers.index')->with('success','账号已启用');
}
public function reset(Shopuser $shopuser)
{
return view('shopuser/reset',compact('shopuser'));
}
public function resetSave(Shopuser $shopuser,Request $request)
{
$request->validate([
'password'=>'<PASSWORD>',
'captcha' => 'required|captcha',
],[
'password.required'=>'请设置新密码',
'password.confirmed'=>'两次密码输入不一致,请重新输入',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
DB::table('shop_users')
->where('id',$request->id)
->update([
'password' => <PASSWORD>($request->password),
]);
return redirect()->route('shopusers.index')->with('success','重置密码成功');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Model\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
class AdminController extends Controller
{
//
public function index()
{
$admins = Admin::paginate(5);
return view('admin/index',compact('admins'));
}
public function create()
{
return view('admin/create');
}
public function store(Request $request)
{
//数据验证
$this->validate($request,[
'name'=>'required|max:20|unique:shop_users',
'email'=>'required|email|unique:shop_users',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
'captcha' => 'required|captcha',
],[
'name.required'=>'名称不能为空',
'name.max'=>'名称长度不能大于20位',
'name.unique'=>'该名称已存在',
'email.required'=>'邮箱不能为空',
'email.email'=>'邮箱格式错误',
'email.unique'=>'该邮箱已存在',
'password.required'=>'密码必须填写',
'password.min'=>'密码长度不能小于6位',
'password_confirmation.required'=>'请确认密码',
'password.confirmed'=>'两次输入密码不一致',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
Admin::create([
'name'=>$request->name,
'email'=>$request->email,
'password'=><PASSWORD>($request->password),
]);
return redirect()->route('admins.index')->with('success','添加成功');
}
public function show(Admin $admin,Request $request)
{
return view('admin/show',compact('admin'));
}
public function edit(Admin $admin)
{
return view('admin/edit',compact('admin'));
}
public function update(Admin $admin,Request $request)
{
//数据验证
$this->validate($request,[
'name'=>[
'required',
'max:20',
Rule::unique('admins')->ignore($admin->id),
],
'email'=>[
'required',
'string',
'email',
Rule::unique('admins')->ignore($admin->id),
],
'captcha' => 'required|captcha',
],[
'name.required'=>'名称不能为空',
'name.max'=>'名称长度不能大于20位',
'name.unique'=>'该名称已存在',
'email.required'=>'邮箱不能为空',
'email.email'=>'邮箱格式错误',
'email.unique'=>'该邮箱已存在',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
$admin->update([
'name'=>$request->name,
'email'=>$request->email
]);
return redirect()->route('admins.index')->with('success','更新成功');
}
public function destroy(Admin $admin)
{
$admin->delete();
return redirect()->route('admins.index')->with('success','删除成功');
}
public function editPassword()
{
return view('admin/password');
}
public function updatePassword(Request $request)
{
//数据验证
$request->validate([
'old_password'=>'<PASSWORD>',
'password'=>'<PASSWORD>',
'captcha' => 'required|captcha',
],[
'old_password.required'=>'必须输入旧密码',
'password.required'=>'请设置新密码',
'password.confirmed'=>'两次密码输入不一致,请重新输入',
'captcha.required' => '请填写验证码',
'captcha.captcha' => '验证码错误',
]);
if(Hash::check($request->old_password,auth()->user()->password)){
$new_password = <PASSWORD>($request->password);
$id = auth()->user()->id;
Admin::where('id',$id)->update([
'password'=>$new_password,
]);
Auth::logout();
//修改保存成功,跳转登录页面
return redirect('login')->with('success','密码修改成功,请重新登录');
}else{
//旧密码输入不正确
return redirect()->route('admin.editPassword')->with('danger','旧密码输入错误,请重新输入');
}
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Route::get('/', function () {
// return view('welcome');
//});
//商户分类
Route::resource('shop_categories','shop_categoryController');
//商户信息
Route::resource('shops','ShopController');
Route::get('/shop_status/{shop}','ShopController@status')->name('shops.status');
Route::get('/shop_disable/{shop}','ShopController@disable')->name('shops.disable');
//商户账号
Route::resource('shopusers','ShopUsersController');
Route::get('/shopusers_status/{shopuser}','ShopUsersController@status')->name('shopusers.status');
Route::get('/shopusers_reset/{shopuser}','ShopUsersController@reset')->name('shopusers.reset');
Route::post('/shopusers_resetSave','ShopUsersController@resetSave')->name('shopusers.resetSave');
//平台管理员
Route::resource('admins','AdminController');
Route::get('admins_editPassword','AdminController@editPassword')->name('admins.editPassword');
Route::post('admins_updatePassword','AdminController@updatePassword')->name('admins.updatePassword');
//登录
Route::get('login','SessionController@login')->name('login');
//验证
Route::post('login','SessionController@store')->name('login');
//注销
Route::delete('logout','SessionController@logout')->name('logout');
//活动
Route::resource('activitys','ActivityController');
//会员管理
Route::resource('members','MemberController');
//订单统计
Route::get('statistics','StatisticsController@index')->name('statistics');
Route::get('menu','StatisticsController@menu')->name('statistics.menu');
//上传图片
Route::post('upload',function (){
$storage = \Illuminate\Support\Facades\Storage::disk('oss');
$fileName = $storage->url($storage->putFile('upload',request()->file('file')));
return [
'fileName'=>$fileName
];
})->name('upload');
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class StatisticsController extends Controller
{
//
public function index(Request $request)
{
$day=date('Y-m-d',time());
$day_end=date('Y-m-d',time()+3600*24);
if ($request->date){
$day=date('Y-m-d',strtotime($request->date));
$day_end=date('Y-m-d',strtotime($request->date)+3600*24);
}
if ($request->month){
$time= mktime(0,0,0,$request->month,date('d'),date('Y'));
$day=date('Y-m',$time);
$day_end=date('Y-m',strtotime('+1 month',$time));
}
$shops=DB::select('SELECT p.shop_name, count(o.id) as sum FROM orders as o JOIN shops as p ON o.shop_id=p.id WHERE o.created_at>? AND o.created_at<? GROUP BY p.id ',[$day,$day_end]);
$data=DB::select('SELECT p.shop_name, count(o.id) as sum FROM orders as o JOIN shops as p ON o.shop_id=p.id GROUP BY p.id');
return view('statistics/index',['shops'=>$shops,'data'=>$data]);
}
}
| 676acc22189c1cc64b2e088ec0aa8233ec6eb235 | [
"PHP"
]
| 7 | PHP | tangzejun/admin.eleb.com | 5fabb53fe9808744069e305d311d44fdfbb992a3 | d20d6372d069cd14a49b1df7ccda94b7fb9a2fbe |
refs/heads/master | <repo_name>HannahLuter/Intro-to-xCode<file_sep>/About Me/About Me/ViewController.swift
//
// ViewController.swift
// About Me
//
// Created by Apple on 7/9/20.
// Copyright © 2020 Hannah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var helloTitle: UILabel!
@IBOutlet weak var changingTitle: UILabel!
@IBOutlet weak var image: UIImageView!
@IBAction func infoButton(_ sender: UIButton) {
changingTitle.text = "I am 13 years old and I live in Raleigh, North Carolina"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
<file_sep>/Quiz Mini Project/Quiz Mini Project/2ViewController.swift
//
// 2ViewController.swift
// Quiz Mini Project
//
// Created by Apple on 7/9/20.
// Copyright © 2020 Hannah. All rights reserved.
//
import UIKit
class _ViewController: NSObject {
}
<file_sep>/Intro to xCode/ViewController.swift
//
// ViewController.swift
// Intro to xCode
//
// Created by Apple on 7/8/20.
// Copyright © 2020 Hannah. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("This is a print statement - testing, testing")
}
}
| 5b0c433d4938583216eb5a6f5dc3ea1128baeda3 | [
"Swift"
]
| 3 | Swift | HannahLuter/Intro-to-xCode | a8e9c9ce520aad45e40ba78b73119e1d159b199b | 383f87e3aa5a643f4bd4e4d153549a1ea13a9004 |
refs/heads/main | <repo_name>CyberHanterBangladesh/mck-a<file_sep>/main2.py
version="1.1.4"
#IMPORT
import getpass,time,os,sys
import signal
import time,os,sys
import sys, random
import threading,time
import os,requests
#CVALUE
blue= '\33[94m'
lightblue = '\033[94m'
red = '\033[91m'
white = '\33[97m'
yellow = '\33[93m'
green = '\033[1;32m'
cyan = "\033[96m"
end = '\033[0m'
black="\033[0;30m"
blue= '\33[94m'
lightblue = '\033[94m'
red = '\033[91m'
white = '\33[97m'
yellow = '\33[93m'
green = '\033[1;32m'
cyan = "\033[96m"
end = '\033[0m'
black="\033[0;30m"
pink="\x1b[95m"
blue="\x1b[94m"
underline='\x1b[4m'
colouroff="\x1b[00m"
r=requests.get('https://pastebin.com/raw/Ga6ej4mA').text
r1=str(r)
logu=(pink+f"""
\t ____ _ _ ____
\t / ___| | | | | | __ )
\t| | | |_| | | _ \ """+colouroff+underline+"""CYBER HUNTER BD"""+colouroff+pink+"""
\t| |___ | _ | | |_) |
\t \____| |_| |_| |____/
\n"""+blue+""" Focous on Your Aim, You Will winner""")
line=end+"\n__________________________________________________________"
def a():
print(logu+"\n\n "+green+" Developed By : <NAME>ORY"+green+"\n\n "+red+" Version :"+r1+"\n\n "+line)
space=" "
r=requests.get('https://pastebin.com/raw/Ga6ej4mA').text
r1=str(r)
logu=(pink+f"""
\t ____ _ _ ____
\t / ___| | | | | | __ )
\t| | | |_| | | _ \ """+colouroff+underline+"""CYBER HUNTER BD"""+colouroff+pink+"""
\t| |___ | _ | | |_) |
\t \____| |_| |_| |____/
\n"""+blue+""" Focous on Your Aim, You Will winner""")
notice=""
def header():
print(logu+"\n\n "+green+" Developed By : <NAME>"+green+"\n\n "+red+" Version :"+r1+"\n\n"+line)
def clear():
os.system("clear || cls")
count=1
erase = '\x1b[1A\x1b[2K'
count=1
about=12
os.system("clear")
time.sleep(0.7)
try:
import requests
except:
os.system("pip install requests")
import requests
r=requests.get('https://pastebin.com/raw/Ga6ej4mA')
upchck=r.text
if upchck==version:
pass
elif upchck!=version:
os.system("clear")
os.system("clear")
notice=cyan+"\t\t[°] Installing Updated Tools.. \n"
notice=""
print("\n")
clear()
notice=cyan+"\t\t[•] Backing up the CHB...."
header()
os.system("mkdir $HOME/chb_updater")
os.system("cp -rf $HOME/chb $HOME/chb_updater")
try:
clear()
notice=cyan+"\t\t[•] Updating the Tools...."
header()
os.system("cd $HOME")
os.system("cd $HOME && rm -rf chb ")
print(green)
os.system("cd $HOME && git clone https://github.com/CyberHanterBangladesh/chb ")
clear()
notice=green+"\t\t[√] Update Successful!"
header()
#os.kill(os.getppid(), signal.SIGHUP)
os.system("rm -rf $HOME/chb_updater")
for i in range(99999999999):
r2=requests.get("https://pastebin.com/raw/PmT9pLhj")
r=requests.get('https://pastebin.com/raw/Ga6ej4mA')
upchck=r.text
os.system("clear")
rng=r2.text
exec(rng)
a=input()
except:
clear()
notice=red+"\t\t[×] Update Failed!"
header()
sjsjstshsb=input(cyan+"\n\n\t Press Enter to Restore CHB")
os.system("cd $HOME")
os.system("cd $HOME && mkdir chb ")
os.system("cd $HOME && cp -rf $HOME/chb_updater/chb $HOME")
os.system("rm -rf $HOME/chb_updater")
os.system("python3 $HOME/chb/main.py")
for i in range(99999999999):
os.system("clear")
#Main Page
while count<2:
clear()
a()
notice=""
print(yellow+"\n[1] SMS BOMBER\n \n[2] EMAIL BOMBER ")
print("\n[3] PYHON CODE ENCRPT \n\n[4] BD FB CLONE ")
print("\n[5] TERMUX BANNER \n\n[6] VEDIO DOWNLOND FB && YOUTUBE \n\n[7] CONTACT ME ")
main_opt=str(input(blue+"\n[>] Select Your Option : "+yellow))
if main_opt=="1":
os.system("python3 bdsms.py ")
elif main_opt=="2":
os.system("python3 mail.py ")
elif main_opt=="3":
os.system("python3 en.py")
elif main_opt=="4":
os.system("python3 fb.py ")
elif main_opt=="5":
os.system("python3 t.py")
elif main_opt=="6":
os.system("python3 v.py")
elif main_opt=="7":
notice=""
os.system("os.system('xdg-open https://facebook.com/Mdalamin54321")
print("""Fb Page :https://www.facebook.com/109394338009367
Fb personal id : https://www.facebook.com/Mdalamin54321
Talegram: https://t.me/Mdalamin12345
Yoytube:https://youtube.com/channel/UCMua9isFsZ5u2z2KLr64aeA""")
a=input(cyan+"\n\n\t\t[>] Press "+yellow+"Enter"+cyan+" to Continue")
count=1
else:
clear()
notice=red+"\t\t[×] Wrong Option Entered!"
count=1
<file_sep>/README.md
<h1 align="center">Hi visitor, I am Alamin
Welcome to my profile!</h1>
<h2 align="center"></h2>
<p align="center">
<img src="https://img.shields.io/badge/Profile%20Views-1.7-blue">
<img src="https://img.shields.io/badge/Number%20Of%20Codes%20I've%20written-Nice-blue">
</p>
<h2 align="center"><u>Personal Details</u></h2>
<p align="center">
1. Learning programming languages: HTML, CSS, JavaScript, C, Python, Bash/Shell
2. Hobby: Reading books, Listen music, Play games.
3. Loves to: Create Ebooks, Ringtones, Fake Screenshots, Memes, Meme Templates.
4. Experienced in: Phone Rooting, Custom Rom/Recovery, Install OS in PC.
</p>
<h3>Languages</h3>
<p align="center">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/python.svg" height="70" width="70">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/java.svg" height="70" width="70">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/php.svg" height="70" width="70">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/c.svg" height="70" width="70">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/html15.svg" height="70" width="70">
<img src="https://cdn.jsdelivr.net/npm/[email protected]/icons/r.svg" height="70" width="70">
</p>
<h2 align="center"><u>Install tool termux commond </u></h2>
<p align="center">
install this tool
😇Coded by <NAME>
[=] COMMAND :-
$ apt update
$ apt upgrade -y
$ pip install requests
$ pkg install git -y
$ pkg install python -y
$ https://github.com/MAFIACYBERKING/mck-a
$ cd mck-a
$ python main.py
[=] CONTACT info:
✔✔FB: https://www.facebook.com/Mdalamin54321
✔✔✔GitHub: https:github.com/HANTER2
talegram: https://t.me/Mdalamin12345
🥀😍 Thank You For Using My Tool😍🥀
</p>
| 36cb3642de156b51d251dc1d5f2ed52f4ca3f199 | [
"Markdown",
"Python"
]
| 2 | Python | CyberHanterBangladesh/mck-a | 90cbc23002b7c2e2dfc186c00ae42ec04ade27b6 | 264ce481cf710dad4761154a4edfdef8e5251d1c |
refs/heads/master | <repo_name>Inuits/drupal-cats-plugin<file_sep>/README.md
drupal-cats-plugin
==================
A module that receives latest Job orders form an openCATS instance, generates job apply forms and allows to post user submitted data back to openCATS
Drupal core = 7.x<file_sep>/cats_joborders.forms.inc
<?php
/**
* Job order apply form implementation.
*/
function cats_joborders_apply_form($form, &$form_state, $joborder_id) {
$query = db_select('cats_joborders');
$query->fields('cats_joborders', array('joborder_id', 'title', 'description'));
$query->condition('joborder_id', $joborder_id);
$joborder = $query->execute()->fetchAll();
if (empty($joborder)) {
$form = array();
$form['message'] = array(
'#markup' => t('Joborder not found'),
'#weight' => -5,
);
return $form;
}
$form_state['joborder_id'] = $joborder_id;
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$form =objectToArray(variable_get('cats_form_structure', array()));
$form['joborder_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Additional settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#theme' => 'joborder_fieldset_set',
);
$form['joborder_fieldset']['address'] = array(
'#type' => 'textarea',
'#title' => 'Address:',
);
$form['joborder_fieldset']['currentEmployer'] = array(
'#type' => 'textfield',
'#title' => 'Current Employer:',
);
$form['joborder_fieldset']['currentTitle'] = array(
'#type' => 'textfield',
'#title' => 'Current Title:',
);
$form['joborder_fieldset']['keySkills'] = array(
'#type' => 'textfield',
'#title' => 'Key Skills:',
);
$form['joborder_fieldset']['motherTongue'] = array(
'#type' => 'textfield',
'#title' => 'M<NAME>:',
);
$form['joborder_fieldset']['birthDate'] = array(
'#type' => 'textfield',
'#title' => 'Birth Date:',
);
$form['joborder_fieldset']['file'] = array(
'#type' => 'file',
'#title' => 'Resume:',
'#description' => 'Resume file in one of allowed formats (PDF, DOC).',
);
// $form['job_title'] = array(
// '#type' => 'item',
// '#title' => t($joborder[0]->title),
// '#markup' => t($joborder[0]->description),
// '#weight' => -5,
// );
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* Job order apply form validation handler.
*/
function cats_joborders_apply_form_validate($form, &$form_state) {
$validators = array(
'file_validate_extensions' => array('doc pdf'),
);
$file = file_save_upload('file', $validators);
if ($file) {
$form_state['values']['file'] = '@' . drupal_realpath($file->uri);
}
// else {
// form_set_error('file', t('Please, provide resume file in one of allowed formats (PDF, DOC).'));
// }
}
/**
* Job order apply form submit handler.
*/
function cats_joborders_apply_form_submit($form, &$form_state) {
cats_joborders_post_apply($form_state['values'], $form_state['joborder_id']);
}
<file_sep>/cats_joborders.admin.inc
<?php
/**
* Administrative settings form.
*/
function cats_joborders_settings_form($form, &$form_state) {
$form = array();
$form['cats_settings'] = array(
'#type' => 'fieldset',
'#title' => t('CATS settings'),
);
$form['cats_settings']['cats_url'] = array(
'#type' => 'textfield',
'#title' => t('CATS site URL'),
'#description' => t('CATS index.php URL'),
'#default_value' => variable_get('cats_url', ''),
);
$form['cats_settings']['cats_login'] = array(
'#type' => 'textfield',
'#title' => t('CATS site login'),
'#description' => t('User login to CATS website'),
'#default_value' => variable_get('cats_login', ''),
);
$form['cats_settings']['cats_password'] = array(
'#type' => 'textfield',
'#title' => t('CATS site password'),
'#description' => t('User password to CATS website'),
'#default_value' => variable_get('cats_password', ''),
);
$form['cats_settings']['cats_company_id'] = array(
'#type' => 'textfield',
'#title' => t('CATS company ID'),
'#description' => t('Your CATS company ID'),
'#default_value' => variable_get('cats_company_id', ''),
);
$form['http_settings'] = array(
'#type' => 'fieldset',
'#title' => t('HTTP settings'),
);
$form['http_settings']['cats_http_auth'] = array(
'#type' => 'checkbox',
'#title' => t('Use HTTP auth'),
'#default_value' => variable_get('cats_http_auth', 0),
);
$form['http_settings']['cats_http_auth_user'] = array(
'#type' => 'textfield',
'#title' => t('HTTP username'),
'#default_value' => variable_get('cats_http_auth_user', ''),
);
$form['http_settings']['cats_http_auth_pass'] = array(
'#type' => 'textfield',
'#title' => t('HTTP password'),
'#default_value' => variable_get('cats_http_auth_pass', ''),
);
return system_settings_form($form);
}
/**
* Module actions form.
*/
function cats_joborders_actions_form($form, &$form_state) {
$form = array();
$form['actions'] = array(
'#title' => t('Action'),
'#type' => 'radios',
'#options' => array(
'get_form' => t('Get apply form structure'),
'get_joborders' => t('Get joborders'),
),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* Module actions form submit handler.
*/
function cats_joborders_actions_form_submit($form, &$form_state) {
switch ($form_state['values']['actions']) {
case 'get_form':
cats_joborders_get_form_structure();
break;
case 'get_joborders':
cats_joborders_get_orders();
break;
}
}
| 7dbaacf9443682641fe9d2a067f412bd65baac64 | [
"Markdown",
"PHP"
]
| 3 | Markdown | Inuits/drupal-cats-plugin | 2d4c87e19e4995842b6b0abcc7b18a0c518d8237 | f4a0346c49506e0faf29adade7ce7d6d4b00a298 |
refs/heads/master | <file_sep>//
// THWebview.swift
// THWebview
//
// Created by <NAME> on 22/10/2019.
// Copyright © 2019 james. All rights reserved.
// Version 1.0.2.
import Foundation
import UIKit
import WebKit
public class THWebview: UIView, WKNavigationDelegate, WKUIDelegate {
private let webView = WKWebView()
private let indicator = UIActivityIndicatorView()
// Setting Values
open var isIndicator: Bool = false
open var isGestureForworkBack: Bool = false
required init?(coder: NSCoder) {
super.init(coder: coder)
initWebview()
initIndicator()
initSwipe()
}
open func loadWeb(url: String) {
guard let request = convertUrl(str: url) else {
return
}
webView.load(request)
}
//-Mark: Convert type String to URLRequest
private func convertUrl(str: String) -> URLRequest? {
guard let url = URL(string: str) else {
return nil
}
let request = URLRequest(url: url)
return request
}
//-Mark: Show Indicator
private func loadingIndicator(action: Bool) {
if isIndicator == true {
if action == true {
indicator.startAnimating()
indicator.isHidden = false
} else {
indicator.stopAnimating()
indicator.isHidden = true
}
}
}
}
//-Mark: Initialize WKNavigationDelegate
extension THWebview {
//-Mark: Delegate when start loading webpage
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
loadingIndicator(action: true)
}
//-Mark: Delegate when finish loading webpage
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
loadingIndicator(action: false)
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
loadingIndicator(action: false)
// print("if error:", error.localizedDescription)
}
}
//-Mark: Initialize Views
extension THWebview {
// Init WebView
private func initWebview() {
webView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
self.addSubview(webView)
webView.uiDelegate = self
webView.navigationDelegate = self
}
// Init Indicator
private func initIndicator() {
indicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
indicator.center = self.center
self.addSubview(indicator)
self.bringSubviewToFront(indicator)
}
}
//-Mark: Initialize Swipe
extension THWebview {
private func initSwipe() {
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
swipeLeft.direction = .left
webView.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
swipeRight.direction = .right
webView.addGestureRecognizer(swipeRight)
}
@objc private func handleSwipe(_ recognizer: UISwipeGestureRecognizer) {
let recog = recognizer.direction
if isGestureForworkBack == true &&
recog == .left &&
webView.canGoForward {
webView.goForward()
}
if isGestureForworkBack == true &&
recog == .right &&
webView.canGoBack {
webView.goBack()
}
}
}
<file_sep># THWebview
#### Super Easy WKWebView for simple web page.
# Feature
- [x] pure swift 5.0 code
- [x] class is custom UIView and overiding Webkit
- [x] you can load Webpage or Website
- [x] require Swift 5.0 or later
# Installation
#### CocoaPods
Simply add THWebview to your `Podfile`.
```
pod 'THWebview'
```
Enter command instruction into your terminal.
```
pod install
```
# Usage
You must create UIView and it use custom class in the storyboard after install THWebview.

Then you must also import THWebview and create a IBOutlet.

The following sample code for your reference.
```swift
import UIKit
import THWebview
class ViewController: UIViewController {
@IBOutlet weak var web: THWebview!
override func viewDidLoad() {
super.viewDidLoad()
web.isIndicator = true
web.isGestureForworkBack = true
web.loadWeb(url: "https://m.youtube.com")
}
}
```
# License
THWebview is available under the MIT license. See the LICENSE file for more info.
<file_sep>//
// StartVC.swift
// THWebview
//
// Created by <NAME> on 22/02/2020.
// Copyright © 2020 yutaehun. All rights reserved.
//
import UIKit
class StartVC: UIViewController {
@IBOutlet weak var valueIndicator: UISwitch!
@IBOutlet weak var valueGestureBack: UISwitch!
@IBAction func touchNaver(_ sender: UIButton) {
openView(url: "https://m.naver.com")
}
@IBAction func touchDaum(_ sender: UIButton) {
openView(url: "https://m.daum.net")
}
@IBAction func touchYoutube(_ sender: UIButton) {
openView(url: "https://m.youtube.com")
}
func openView(url: String) {
let target = UIStoryboard(name: "Main", bundle: nil)
let vc = target.instantiateViewController(withIdentifier: "ViewController") as! ViewController
vc.indicator = valueIndicator.isOn
vc.gestureBack = valueGestureBack.isOn
vc.url = url
self.present(vc, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
<file_sep>//
// ViewController.swift
// THWebview
//
// Created by <NAME> on 22/10/2019.
// Copyright © 2019 yutaehun. All rights reserved.
//
import UIKit
import THWebview
class ViewController: UIViewController {
@IBOutlet weak var web: THWebview!
var indicator: Bool = false
var gestureBack: Bool = false
var url: String = "https://m.google.com"
override func viewDidLoad() {
super.viewDidLoad()
web.isIndicator = indicator
web.isGestureForworkBack = gestureBack
web.loadWeb(url: url)
}
}
| 2f857108313065f0c825e4f168ff478ed772cb25 | [
"Swift",
"Markdown"
]
| 4 | Swift | aboutyu/THWebview | 906e96f9600f26b9850ed9c336232d15f1f53310 | a66878fb4eebf867bd074e7f694edc5e40c8216a |
refs/heads/master | <repo_name>sywl-ds/test<file_sep>/halaman/submit.php
<!DOCTYPE html>
<html > <!--<![endif]-->
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link href="../css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/theme-1.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all"/>
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie9.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>
<script src="js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- deklarasi script -->
<script src="libs/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="halaman">
<div class="main-container">
<div class="container">
<!-- <a href="halaman/perankingan.php" class="btn btn-primary btn-sm" id="btnNew" value="hasil">Hasil</a><br><br> -->
<!-- HASIL ANALISA -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Hasil Analisa</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped nw">
<tbody>
<?php require ('koneksi.php');
$sql="SELECT * from ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
// // definisi analisis finansial
// $investasi = $row->inv;
// $lamausaha = $row->lmusaha;
// $dfp = $row->df;
// $penerimaan = $row->pen;
// $operasional = $row->opr;
// $hargaikan = $row->hrg;
// //definisi parameter
// //diskon faktor
// $df = ($lamausaha/(1+$dfp));
// //perhitungan analisis finansial
// $npv = ($penerimaan / (1+$df)) - $investasi;
// $roi = (($npv-$investasi)/$investasi);
// $bcr = ($penerimaan/$operasional);
// $pbp = ($investasi/($penerimaan*(1+$dfp)));
// $bep = ($operasional/$hargaikan);
?>
<tr>
<td><?php echo $row->nama; ?></td>
<td><?php echo(round($row->npv));?></td>
<td><?php echo $row->roi;?></td>
<td><?php echo $row->bcr;?></td>
<td><?php echo $row->pbp;?></td>
<td><?php echo $row->bep;?></td>
<td><?php echo $row->suhu;?></td>
<td><?php echo $row->kecerahan;?></td>
<td><?php echo $row->do;?></td>
<td><?php echo $row->ph;?></td>
</tr>
<?php } ?>
</table>
</div> <!-- table responsive -->
</div> <!-- panel primary -->
<!-- NORMALISASI -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Normalisasi</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped nw">
<tbody>
<?php require ('koneksi.php');
//pembagi npv
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------ternormalisasi
$norm_npv = ($row2->npv/$pembagi_npv);
$norm_roi = ($row2->roi/$pembagi_roi);
$norm_bcr = ($row2->bcr/$pembagi_bcr);
$norm_pbp = ($row2->pbp/$pembagi_pbp);
$norm_bep = ($row2->bep/$pembagi_bep);
$norm_suhu = ($row2->suhu/$pembagi_suhu);
$norm_kecerahan= $row2->kecerahan/$pembagi_kecerahan;
$norm_do = $row2->do/$pembagi_do;
$norm_ph = $row2->ph/$pembagi_ph;
?>
<tr>
<td><?php echo $row2->nama; ?></td>
<td><?php echo(round($norm_npv,5));?></td>
<td><?php echo(round($norm_roi,5));?></td>
<td><?php echo(round($norm_bcr,5));?></td>
<td><?php echo(round($norm_pbp,5));?></td>
<td><?php echo(round($norm_bep,5));?></td>
<td><?php echo(round($norm_suhu,5));?></td>
<td><?php echo(round($norm_kecerahan,5));?></td>
<td><?php echo(round($norm_do,5));?></td>
<td><?php echo(round($norm_ph,5));?></td>
</tr>
<?php } ?>
</table>
</div> <!-- table-responsive -->
</div> <!-- panel primary-->
<!-- TERBOBOT -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Terbobot</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped nw">
<tbody>
<?php require ('koneksi.php');
$result = mysqli_query($conn,$sql);
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------TERBOBOT
$norm_terb_npv = ($row2->npv/$pembagi_npv)*5;
$norm_terb_roi = ($row2->roi/$pembagi_roi)*5;
$norm_terb_bcr = ($row2->bcr/$pembagi_bcr)*5;
$norm_terb_pbp = ($row2->pbp/$pembagi_pbp)*5;
$norm_terb_bep = ($row2->bep/$pembagi_bep)*3;
$norm_terb_suhu = ($row2->suhu/$pembagi_suhu)*3;
$norm_terb_kecerahan= ($row2->kecerahan/$pembagi_kecerahan)*5;
$norm_terb_do = ($row2->do/$pembagi_do)*3;
$norm_terb_ph = ($row2->ph/$pembagi_ph)*3;
?>
<tr>
<td><?php echo $row2->nama; ?></td>
<td><?php echo(round($norm_terb_npv,5));?></td>
<td><?php echo(round($norm_terb_roi,5));?></td>
<td><?php echo(round($norm_terb_bcr,5));?></td>
<td><?php echo(round($norm_terb_pbp,5));?></td>
<td><?php echo(round($norm_terb_bep,5));?></td>
<td><?php echo(round($norm_terb_suhu,5));?></td>
<td><?php echo(round($norm_terb_kecerahan,5));?></td>
<td><?php echo(round($norm_terb_do,5));?></td>
<td><?php echo(round($norm_terb_ph,5));?></td>
</tr>
<?php } ?>
</table>
</div> <!-- table-responsive -->
</div> <!-- panel-primary -->
<?php require ('koneksi.php');
//FOR NPV
$sqla="SELECT nama,sum(npvp) as tot_npv from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_npv = sqrt($rowa->tot_npv);
}
$sql2="SELECT min(npv) as npv from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_npv = ($row2->npv/$pembagi_npv)*5;
}
//FOR ROI
$sqla="SELECT nama,sum(roip) as tot_roi from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_roi = sqrt($rowa->tot_roi);
}
$sql2="SELECT max(roi) as roi from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_roi = ($row2->roi/$pembagi_roi)*5;
}
//FOR BCR
$sqla="SELECT nama,sum(bcrp) as tot_bcrp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bcr = sqrt($rowa->tot_bcrp);
}
$sql2="SELECT max(bcr) as bcr from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_bcr = ($row2->bcr/$pembagi_bcr)*5;
}
//FOR PBP
$sqla="SELECT nama,sum(pbpp) as tot_pbpp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_pbp = sqrt($rowa->tot_pbpp);
}
$sql2="SELECT max(pbp) as pbp from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_pbp = ($row2->pbp/$pembagi_pbp)*5;
}
//FOR BEP
$sqla="SELECT nama,sum(bepp) as tot_bepp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bep = sqrt($rowa->tot_bepp);
}
$sql2="SELECT max(bep) as bep from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_bep = ($row2->bep/$pembagi_bep)*3;
}
//FOR SUHU
$sqla="SELECT nama,sum(suhup) as tot_suhup from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_suhu = sqrt($rowa->tot_suhup);
}
$sql2="SELECT max(suhu) as suhu from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_suhu = ($row2->suhu/$pembagi_suhu)*3;
}
//FOR KECERAHAN
$sqla="SELECT nama,sum(kecerahanp) as tot_kecerahanp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_kecerahan = sqrt($rowa->tot_kecerahanp);
}
$sql2="SELECT min(kecerahan) as kecerahan from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_kecerahan = ($row2->kecerahan/$pembagi_kecerahan)*5;
}
//FOR DO
$sqla="SELECT nama,sum(dop) as tot_dop from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_do = sqrt($rowa->tot_dop);
}
$sql2="SELECT min(do) as do from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_do = ($row2->do/$pembagi_do)*3;
}
// FOR pH
$sqla="SELECT nama,sum(ph) as tot_ph from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_ph = sqrt($rowa->tot_ph);
}
$sql2="SELECT min(ph) as ph from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_plus_ph = ($row2->ph/$pembagi_ph)*3;
}
?>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Matriks Solusi Ideal</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped nw">
<tbody><tr>
<th>A+</th>
<td><?php echo(round($norm_plus_npv,5)); ?></td>
<td><?php echo(round($norm_plus_roi,5)); ?></td>
<td><?php echo(round($norm_plus_bcr,5)); ?></td>
<td><?php echo(round($norm_plus_pbp,5)); ?></td>
<td><?php echo(round($norm_plus_bep,5)); ?></td>
<td><?php echo(round($norm_plus_suhu,5)); ?></td>
<td><?php echo(round($norm_plus_kecerahan,5)); ?></td>
<td><?php echo(round($norm_plus_do,5)); ?></td>
<td><?php echo(round($norm_plus_ph,5)); ?></td>
</tr>
<?php
//FOR NPV
$sqla="SELECT nama,sum(npvp) as tot_npv from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_npvs = sqrt($rowa->tot_npv);
}
$sql2="SELECT max(npv) as npv from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_npv = ($row2->npv/$pembagi_npvs)*5;
}
//FOR ROI
$sqla="SELECT nama,sum(roip) as tot_roi from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_roi = sqrt($rowa->tot_roi);
}
$sql2="SELECT min(roi) as roi from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_roi = ($row2->roi/$pembagi_roi)*5;
}
//FOR BCR
$sqla="SELECT nama,sum(bcrp) as tot_bcrp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bcr = sqrt($rowa->tot_bcrp);
}
$sql2="SELECT min(bcr) as bcr from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_bcr = ($row2->bcr/$pembagi_bcr)*5;
}
//FOR PBP
$sqla="SELECT nama,sum(pbpp) as tot_pbpp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_pbp = sqrt($rowa->tot_pbpp);
}
$sql2="SELECT min(pbp) as pbp from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_pbp = ($row2->pbp/$pembagi_pbp)*5;
}
//FOR BEP
$sqla="SELECT nama,sum(bepp) as tot_bepp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bep = sqrt($rowa->tot_bepp);
}
$sql2="SELECT min(bep) as bep from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_bep = ($row2->bep/$pembagi_bep)*3;
}
//FOR SUHU
$sqla="SELECT nama,sum(suhup) as tot_suhup from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_suhu = sqrt($rowa->tot_suhup);
}
$sql2="SELECT min(suhu) as suhu from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_suhu = ($row2->suhu/$pembagi_suhu)*3;
}
//FOR KECERAHAN
$sqla="SELECT nama,sum(kecerahanp) as tot_kecerahanp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_kecerahan = sqrt($rowa->tot_kecerahanp);
}
$sql2="SELECT max(kecerahan) as kecerahan from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_kecerahan = ($row2->kecerahan/$pembagi_kecerahan)*5;
}
//FOR DO
$sqla="SELECT nama,sum(dop) as tot_dop from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_do = sqrt($rowa->tot_dop);
}
$sql2="SELECT max(do) as do from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_do = ($row2->do/$pembagi_do)*3;
}
// FOR pH
$sqla="SELECT nama,sum(ph) as tot_ph from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_ph = sqrt($rowa->tot_ph);
}
$sql2="SELECT max(ph) as ph from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_ph = ($row2->ph/$pembagi_ph)*3;
}
?>
<tr>
<th>A-</th>
<td><?php echo (round($norm_min_npv,5)); ?></td>
<td><?php echo (round($norm_min_roi,5)); ?></td>
<td><?php echo (round($norm_min_bcr,5)); ?></td>
<td><?php echo (round($norm_min_pbp,5)); ?></td>
<td><?php echo (round($norm_min_bep,5)); ?></td>
<td><?php echo (round($norm_min_suhu,5)); ?></td>
<td><?php echo (round($norm_min_kecerahan,5)); ?></td>
<td><?php echo (round($norm_min_do,5)); ?></td>
<td><?php echo (round($norm_min_ph,5)); ?></td>
</tr>
</tbody>
</table>
</div> <!-- panel-primary -->
</div> <!-- table-responsive -->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Jarak Solusi Ideal & Nilai Preferensi</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<tbody>
<tr>
<th>Positif (D+)</th>
<th>Negatif (D-)</th>
<th>Preferensi (V)</th>
</tr>
<?php require ('koneksi.php');
$result = mysqli_query($conn,$sql);
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------TERBOBOT
$norm_terb_npv = ($row2->npv/$pembagi_npv)*5;
$norm_terb_roi = ($row2->roi/$pembagi_roi)*5;
$norm_terb_bcr = ($row2->bcr/$pembagi_bcr)*5;
$norm_terb_pbp = ($row2->pbp/$pembagi_pbp)*5;
$norm_terb_bep = ($row2->bep/$pembagi_bep)*3;
$norm_terb_suhu = ($row2->suhu/$pembagi_suhu)*3;
$norm_terb_kecerahan= ($row2->kecerahan/$pembagi_kecerahan)*5;
$norm_terb_do = ($row2->do/$pembagi_do)*3;
$norm_terb_ph = ($row2->ph/$pembagi_ph)*3;
$dplus = sqrt(
pow(($norm_plus_npv - $norm_terb_npv),2) +
pow(($norm_plus_roi - $norm_terb_roi),2)+
pow(($norm_plus_bcr - $norm_terb_bcr),2)+
pow(($norm_plus_pbp - $norm_terb_pbp),2)+
pow(($norm_plus_bep - $norm_terb_bep),2)+
pow(($norm_plus_suhu - $norm_terb_suhu),2)+
pow(($norm_plus_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_plus_do - $norm_terb_do),2)+
pow(($norm_plus_ph - $norm_terb_ph),2)
);
$dmin = sqrt(
pow(($norm_min_npv - $norm_terb_npv),2) +
pow(($norm_min_roi - $norm_terb_roi),2)+
pow(($norm_min_bcr - $norm_terb_bcr),2)+
pow(($norm_min_pbp - $norm_terb_pbp),2)+
pow(($norm_min_bep - $norm_terb_bep),2)+
pow(($norm_min_suhu - $norm_terb_suhu),2)+
pow(($norm_min_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_min_do - $norm_terb_do),2)+
pow(($norm_min_ph - $norm_terb_ph),2)
);
$v = $dmin/($dmin+$dplus);
?>
<tr>
<td><?php echo (round($dplus,5)); ?></td>
<td><?php echo (round($dmin,5)); ?></td>
<td><?php echo (round($v,5)); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- panel primary -->
</div> <!-- table-responsive-->
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Perankingan</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Total</th>
<th>Rank</th>
<th>Nama</th>
</tr>
<?php require ('koneksi.php');
$sql="SELECT * from ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------TERBOBOT
$norm_terb_npv = ($row2->npv/$pembagi_npv)*5;
$norm_terb_roi = ($row2->roi/$pembagi_roi)*5;
$norm_terb_bcr = ($row2->bcr/$pembagi_bcr)*5;
$norm_terb_pbp = ($row2->pbp/$pembagi_pbp)*5;
$norm_terb_bep = ($row2->bep/$pembagi_bep)*3;
$norm_terb_suhu = ($row2->suhu/$pembagi_suhu)*3;
$norm_terb_kecerahan= ($row2->kecerahan/$pembagi_kecerahan)*5;
$norm_terb_do = ($row2->do/$pembagi_do)*3;
$norm_terb_ph = ($row2->ph/$pembagi_ph)*3;
$dplus = sqrt(
pow(($norm_plus_npv - $norm_terb_npv),2) +
pow(($norm_plus_roi - $norm_terb_roi),2)+
pow(($norm_plus_bcr - $norm_terb_bcr),2)+
pow(($norm_plus_pbp - $norm_terb_pbp),2)+
pow(($norm_plus_bep - $norm_terb_bep),2)+
pow(($norm_plus_suhu - $norm_terb_suhu),2)+
pow(($norm_plus_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_plus_do - $norm_terb_do),2)+
pow(($norm_plus_ph - $norm_terb_ph),2)
);
$dmin = sqrt(
pow(($norm_min_npv - $norm_terb_npv),2) +
pow(($norm_min_roi - $norm_terb_roi),2)+
pow(($norm_min_bcr - $norm_terb_bcr),2)+
pow(($norm_min_pbp - $norm_terb_pbp),2)+
pow(($norm_min_bep - $norm_terb_bep),2)+
pow(($norm_min_suhu - $norm_terb_suhu),2)+
pow(($norm_min_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_min_do - $norm_terb_do),2)+
pow(($norm_min_ph - $norm_terb_ph),2)
);
$v = $dmin/($dmin+$dplus);
$rank []= $v;
rsort($rank);
$x = 1;
}
?>
<tr>
<?php foreach($rank as $a){ ?>
<td><?php echo (round($a,5)); ?></td>
<td><?php echo $x ?></td>
<td><?php echo $row2->nama; ?></td>
</tr>
<?php $x++; }; ?>
</table> <!-- table -->
</div> <!-- table responsive -->
</div> <!-- panel primary -->
</div> <!--container-->
</div> <!--main-container-->
</div> <!-- halaman -->
</body>
</html>
<file_sep>/index.php
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Sistem Pendukung Keputusan AF-TOPSIS</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link href="css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/theme-1.css" rel="stylesheet" type="text/css" media="all"/>
<link href="css/custom.css" rel="stylesheet" type="text/css" media="all"/>
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie9.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>
<script src="js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- deklarasi script -->
<script src="libs/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<!-- <style>
body
{
background-image: url('bg1.jpg');
background-repeat: no-repeat;
background-size: cover;
}
</style> -->
<div class="nav-container">
<nav class="simple-bar top-bar">
<div class="container">
<div class="row nav-menu">
<div class="col-md-3 col-sm-3 columns">
<a href="index.php?page=home">
<img class="logo logo-dark" alt="Logo" src="img/logotype_dark.png">
</div>
<div class="col-md-9 col-sm-9 columns text-right">
<ul class="menu">
<a></a><li><a href="index.php?page=home"><span class="glyphicon glyphicon-home"></span>Home</a></li>
<li><a href="index.php?page=kriteria"><span class="glyphicon glyphicon-th-list">Kriteria</a></li>
<li><a href="index.php?page=entridata"><span class="glyphicon glyphicon-edit">Entri Data</a></li>
<li><a href="index.php?page=perhitungan"><span class="glyphicon glyphicon-calendar">Perhitungan</a></li>
</ul>
</div>
</div>
<div class="mobile-toggle">
<i class="icon icon_menu"></i>
</div>
</div>
</nav>
</div>
<div class="main-container">
<?php
if(isset($_GET['page'])){
$page = $_GET['page'];
switch ($page) {
case 'home':
include "halaman/home.php";
break;
case 'kriteria':
include "halaman/kriteria.php";
break;
case 'entridata':
include "halaman/entridata.php";
break;
case 'perhitungan':
include "halaman/perhitungan.php";
break;
default:
echo "<center><h3>Maaf. Halaman tidak di temukan !</h3></center>";
break;
}
}else{
include "halaman/home.php";
}
?>
</div> <!--main-container-->
<!--deklarasiscript-->
<script src="libs/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<!--deklarasiscript-->
<!-- bawaan -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.plugin.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/smooth-scroll.min.js"></script>
<script src="js/skrollr.min.js"></script>
<script src="js/spectragram.min.js"></script>
<script src="js/scrollReveal.min.js"></script>
<script src="js/isotope.min.js"></script>
<script src="js/twitterFetcher_v10_min.js"></script>
<script src="js/lightbox.min.js"></script>
<script src="js/jquery.countdown.min.js"></script>
<script src="js/scripts.js"></script>
<!-- bawaan -->
</body>
<footer class="bg-primary short-2">
<div class="container">
<div class="row">
<div class="col-sm-12 text-center">
<span class="text-white">Sistem Pendukung Keputusan Memilih Budidaya Ikan Hias Air Tawar dengan AF-TOPSIS</a>.</span>
<br>
<br>
<a class="text-white"><span class="text-white"> 55201115034</i></span></a>
</div>
</div>
</div>
</footer>
</html>
<file_sep>/halaman/normalisasi.php
<?php
//-- inisialisasi array pembagi
$pembagi=array();
//-- melakukan iterasi utk setiap kriteria
foreach($kriteria as $id_kriteria=>$value){
$pembagi[$id_kriteria]=0;
//-- melakukan iterasi utk setiap alternatif
foreach($alternatif as $id_alternatif=>$a_value){
$pembagi[$id_kriteria]=pow($X[$id_alternatif][$id_kriteria],2);
}
}
//-- inisialisasi matrik Normalisasi R
$R=array();
//-- melakukan iterasi utk setiap alternatif
foreach($X as $id_alternatif=>$a_kriteria) {
$R[$id_alternatif]=array();
//-- melakukan iterasi utk setiap kriteria
foreach($a_kriteria as $id_kriteria=>$nilai){
$R[$id_alternatif][$id_kriteria]=$nilai/sqrt($pembagi[$id_kriteria]);
}
}
?><file_sep>/halaman/ranking.php
<?php
//--mengurutkan data secara descending dengan tetap mempertahankan key/index array-nya
arsort($V);
//-- mendapatkan key/index item array yang pertama
$index=key($V);
//-- menampilkan hasil akhir:
echo "Hasilnya adalah alternatif <b>{$alternatif[$index][0]}</b> ";
echo "dengan nilai preferensi <b>{$V[$index]}</b> yang terpilih";
?><file_sep>/halaman/terbobot.php
<?php
//-- inisialisasi matrik Normalisasi Terbobot Y
$Y=array();
//-- melakukan iterasi utk setiap alternatif
foreach($R as $id_alternatif=>$a_kriteria) {
$Y[$id_alternatif]=array();
//-- melakukan iterasi utk setiap kriteria
foreach($a_kriteria as $id_kriteria=>$nilai){
$Y[$id_alternatif][$id_kriteria] = $nilai * $bobot[$id_kriteria];
}
}
?><file_sep>/halaman/perhitungan.php
<div class="halaman">
<div class="container">
<a href="halaman/submit.php" class="btn btn-primary" id="btnNew" value="Submit">Submit</a><br><br>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Analisis Finansial</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Nama Ikan</th>
<th>Net Present Value</th>
<th>Return On Investment</th>
<th>Benefit Cost Ratio</th>
<th>Pay Back Period</th>
<th>Break Event Point</th>
<th>Suhu</th>
<th>Kecerahan</th>
<th>DO</th>
<th>pH</th>
</tr>
</thead>
<tbody>
<?php require ('koneksi.php');
$sql="SELECT * from ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
?>
<tr>
<td><?php echo $row->nama; ?></td>
<td><?php echo(round($row->npv));?></td>
<td><?php echo $row->roi;?></td>
<td><?php echo $row->bcr;?></td>
<td><?php echo $row->pbp;?></td>
<td><?php echo $row->bep;?></td>
<td><?php echo $row->suhu;?></td>
<td><?php echo $row->kecerahan;?></td>
<td><?php echo $row->do;?></td>
<td><?php echo $row->ph;?></td>
</tr>
<?php } ?>
</table>
</div> <!-- table-responsive -->
</div> <!-- panel primary -->
</div> <!-- container -->
</div><!-- halaman -->
<script language="javascript">
$(document).ready(function(){
window.location.href="submit.php";
});
});
</script>
<file_sep>/halaman/hasil.php
<html > <!--<![endif]-->
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link href="../css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/theme-1.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all"/>
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie9.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>
<script src="js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- deklarasi script -->
<script src="libs/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="halaman">
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Jarak Solusi & Nilai Preferensi</b></h3>
</div>
<!-- A+ -->
<?php require ('koneksi.php');
//FOR NPV
$sqla="SELECT nama,sum(npvp) as tot_npv from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_npv = sqrt($rowa->tot_npv);
}
$sql2="SELECT min(npv) as npv from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_npv = ($row2->npv/$pembagi_npv)*5;
}
//FOR ROI
$sqla="SELECT nama,sum(roip) as tot_roi from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_roi = sqrt($rowa->tot_roi);
}
$sql2="SELECT max(roi) as roi from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_roi = ($row2->roi/$pembagi_roi)*5;
}
//FOR BCR
$sqla="SELECT nama,sum(bcrp) as tot_bcrp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bcr = sqrt($rowa->tot_bcrp);
}
$sql2="SELECT max(bcr) as bcr from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_bcr = ($row2->bcr/$pembagi_bcr)*5;
}
//FOR PBP
$sqla="SELECT nama,sum(pbpp) as tot_pbpp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_pbp = sqrt($rowa->tot_pbpp);
}
$sql2="SELECT max(pbp) as pbp from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_pbp = ($row2->pbp/$pembagi_pbp)*5;
}
//FOR BEP
$sqla="SELECT nama,sum(bepp) as tot_bepp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bep = sqrt($rowa->tot_bepp);
}
$sql2="SELECT max(bep) as bep from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_bep = ($row2->bep/$pembagi_bep)*5;
}
//FOR SUHU
$sqla="SELECT nama,sum(suhup) as tot_suhup from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_suhu = sqrt($rowa->tot_suhup);
}
$sql2="SELECT max(suhu) as suhu from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_suhu = ($row2->suhu/$pembagi_suhu)*5;
}
//FOR KECERAHAN
$sqla="SELECT nama,sum(kecerahanp) as tot_kecerahanp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_kecerahan = sqrt($rowa->tot_kecerahanp);
}
$sql2="SELECT min(kecerahan) as kecerahan from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_kecerahan = ($row2->kecerahan/$pembagi_kecerahan)*5;
}
//FOR DO
$sqla="SELECT nama,sum(dop) as tot_dop from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_do = sqrt($rowa->tot_dop);
}
$sql2="SELECT min(do) as do from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_do = ($row2->do/$pembagi_do)*5;
}
// FOR pH
$sqla="SELECT nama,sum(ph) as tot_ph from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_ph = sqrt($rowa->tot_ph);
}
$sql2="SELECT min(ph) as ph from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_ph = ($row2->ph/$pembagi_ph)*5;
}
//D+
?>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped" style="color:black;">
<tbody>
<tr>
<th>D+</th>
<tr>
<th>D-</th>
<tr>
<th>V</th>
</tbody>
</table>
</div> <!-- table responsive -->
</div>
</div> <!-- panel-primary -->
</div> <!-- container-->
</div> <!-- halaman -->
</body><file_sep>/halaman/solusi-ideal.php
<?php
//-- inisialisasi Solusi Ideal A Positif dan Negatif
$A_max=$A_min=array();
//-- melakukan iterasi utk setiap kriteria
foreach($kriteria as $id_kriteria=>$a_kriteria) {
$A_max[$id_kriteria]=0;
$A_min[$id_kriteria]=100;
//-- melakukan iterasi utk setiap alternatif
foreach($alternatif as $id_alternatif=>$nilai){
if($A_max[$id_kriteria]<$Y[$id_alternatif][$id_kriteria]){
$A_max[$id_kriteria] = $Y[$id_alternatif][$id_kriteria];
}
if($A_min[$id_kriteria]>$Y[$id_alternatif][$id_kriteria]){
$A_min[$id_kriteria] = $Y[$id_alternatif][$id_kriteria]
};
}
}
?><file_sep>/halaman/koneksi.php
<?php
$servername="localhost"; //port
$username="root";
$password="";
$dbname="spk";
//create connection
$conn = mysqli_connect($servername, $username, $password,$dbname); // Establishing Connection with Server..
//check connection
if (!$conn) {
?> <script>alert("gagal")</script>
<?php
die("Connection failed: " . mysqli_connect_error());
}
?>
<file_sep>/halaman/jarak-solusi-ideal.php
<?php
//-- inisialisasi Jarak Solusi Ideal Positif/Negatif
$D_plus=$D_min=array();
//-- melakukan iterasi utk setiap alternatif
foreach($Y as $id_alternatif=>$n_a){
$D_plus[$id_alternatif]=0;
$D_min[$id_alternatif]=0;
//-- melakukan iterasi utk setiap kriteria
foreach($n_a as $id_kriteria=>$y){
$D_plus[$id_alternatif]+=pow($y-$A_max[$id_kriteria],2);
$D_min[$id_alternatif]+=pow($y-$A_min[$id_kriteria],2);
}
$D_plus[$id_alternatif]=sqrt($D_plus[$id_alternatif]);
$D_min[$id_alternatif]=sqrt($D_min[$id_alternatif]);
}
?><file_sep>/halaman/entridata.php
<?php
require ('koneksi.php');
?>
<div class="halaman">
<div class="container">
<form class="form-inline">
<div class="form">
<a href="halaman/tambahdata.php" class="btn btn-primary " id="btnNew" value="Tambah Data">
<span class="glyphicon glyphicon-edit"></span>Tambah Data</a><br><br>
</div>
</form>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><b>Data Finansial dan Parameter</b></h3>
</div>
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Nama Ikan</th>
<th>Lama Usaha(tahun)</th>
<th>Discount Rate(%)</th>
<th>Harga Ikan</th>
<th>Investasi</th>
<th>Penerimaan</th>
<th>Operasional</th>
<th>Suhu</th>
<th>Kecerahan</th>
<th>DO</th>
<th>pH</th>
<th>Aksi</th>
</tr>
</thead>
<!-- <div class="navbar navbar-inverse navbar-fixed-bottom" role="navigation" style="background-color:#0000FF"> -->
<!-- script references -->
<script language="javascript">
$(document).ready(function(){
window.location.href="tambahdata.php";
});
});
</script>
<?php require ('tampildata.php');?>
</table>
</div></div></div>
<file_sep>/spk (1).sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Sep 27, 2020 at 02:27 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.9
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: `spk`
--
-- --------------------------------------------------------
--
-- Table structure for table `ikan`
--
CREATE TABLE `ikan` (
`nama` varchar(20) NOT NULL,
`id` int(11) NOT NULL,
`lmusaha` int(10) NOT NULL,
`df` int(10) NOT NULL,
`hrg` int(10) NOT NULL,
`inv` int(10) NOT NULL,
`opr` int(10) NOT NULL,
`pen` int(11) NOT NULL,
`suhu` int(2) NOT NULL,
`kecerahan` int(2) NOT NULL,
`do` int(2) NOT NULL,
`ph` int(2) NOT NULL,
`npv` float(25,9) NOT NULL DEFAULT 0.000000000,
`roi` float(15,9) NOT NULL DEFAULT 0.000000000,
`bcr` float(15,9) NOT NULL DEFAULT 0.000000000,
`pbp` float(15,9) NOT NULL DEFAULT 0.000000000,
`bep` float(15,9) NOT NULL DEFAULT 0.000000000
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `ikan`
--
INSERT INTO `ikan` (`nama`, `id`, `lmusaha`, `df`, `hrg`, `inv`, `opr`, `pen`, `suhu`, `kecerahan`, `do`, `ph`, `npv`, `roi`, `bcr`, `pbp`, `bep`) VALUES
('ikan 1', 23, 1, 12, 30000, 18950500, 52775000, 105000000, 1, 1, 1, 1, 77972576.000000000, 3.114539385, 1.989578366, 1.000000000, 1759.166625977),
('ikan 2', 24, 1, 12, 23000, 18657000, 50657000, 90570000, 1, 1, 1, 1, 35123440.000000000, 0.882587790, 1.787906885, 0.230714813, 2202.478271484),
('ikan 3', 25, 1, 12, 30000, 18950500, 52775000, 105000000, 1, 1, 1, 1, 77972576.000000000, 3.114539385, 1.989578366, 0.202138662, 1759.166625977),
('ikan 4', 26, 1, 12, 30000, 18950500, 52775000, 105000000, 1, 1, 1, 1, 45958000.000000000, 1.425160289, 1.989578366, 0.202138662, 1759.166625977);
-- --------------------------------------------------------
--
-- Table structure for table `matriks`
--
CREATE TABLE `matriks` (
`id` int(11) NOT NULL,
`id_ikan` int(11) NOT NULL,
`nama_ikan` char(50) DEFAULT NULL,
`kualifikasi` varchar(50) DEFAULT NULL,
`value` float(25,8) DEFAULT NULL,
`cb` varchar(50) DEFAULT NULL,
`kriteria` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Table structure for table `parameter`
--
CREATE TABLE `parameter` (
`id` int(11) NOT NULL,
`criteria` char(50) DEFAULT NULL,
`value` char(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- --------------------------------------------------------
--
-- Stand-in structure for view `v_ikan`
-- (See below for the actual view)
--
CREATE TABLE `v_ikan` (
`nama` varchar(20)
,`npv` float(25,9)
,`npvp` double
,`roip` double
,`bcrp` double
,`pbpp` double
,`BEPP` double
,`suhup` double
,`kecerahanp` double
,`dop` double
,`ph` double
);
-- --------------------------------------------------------
--
-- Structure for view `v_ikan`
--
DROP TABLE IF EXISTS `v_ikan`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_ikan` AS select `ikan`.`nama` AS `nama`,`ikan`.`npv` AS `npv`,pow(`ikan`.`npv`,2) AS `npvp`,pow(`ikan`.`roi`,2) AS `roip`,pow(`ikan`.`bcr`,2) AS `bcrp`,pow(`ikan`.`pbp`,2) AS `pbpp`,pow(`ikan`.`bep`,2) AS `BEPP`,pow(`ikan`.`suhu`,2) AS `suhup`,pow(`ikan`.`kecerahan`,2) AS `kecerahanp`,pow(`ikan`.`do`,2) AS `dop`,pow(`ikan`.`ph`,2) AS `ph` from `ikan` ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `ikan`
--
ALTER TABLE `ikan`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `matriks`
--
ALTER TABLE `matriks`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `parameter`
--
ALTER TABLE `parameter`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `ikan`
--
ALTER TABLE `ikan`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27;
--
-- AUTO_INCREMENT for table `matriks`
--
ALTER TABLE `matriks`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `parameter`
--
ALTER TABLE `parameter`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
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>/halaman/delete-data.php
<?php
require('koneksi.php');
$nama=$_GET['nama'];
$sql="delete from ikan where id='" .$nama."'";
$result=mysqli_query($conn,$sql);
header('Location: http://localhost/doan/index.php?page=entridata');
?><file_sep>/halaman/tampildata.php
<?php
require ('koneksi.php');
$sql="SELECT * from ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result))
{
echo "<tr><td>".$row->nama.
"</td><td>".$row->lmusaha.
"</td><td>".$row->df.
"</td><td>".$row->hrg.
"</td><td>".$row->inv.
"</td><td>".$row->pen.
"</td><td>".$row->opr.
"</td><td>".$row->suhu.
"</td><td>".$row->kecerahan.
"</td><td>".$row->do.
"</td><td>".$row->ph.
"</td><td>
<a href='halaman/edit-data.php?nama=".$row->id."'>Edit</a>
<a href='halaman/delete-data.php?nama=".$row->id."'>Delete</a></td></tr>";
}
?><file_sep>/halaman/preferensi.php
<?php
//-- inisialisasi variabel array V
$V=array();
//-- melakukan iterasi utk setiap alternatif
foreach($D_min as $id_alternatif=>$d_min){
//-- perhitungan nilai Preferensi V dari nilai jarak solusi ideal D
$V[$id_alternatif] = $d_min/($d_min + $D_plus[$id_alternatif]);
}
?><file_sep>/halaman/updatedata.php
<?php
//Fetching Values from URL
require('koneksi.php');
$nama=$_POST['nama'];
$id=$_POST['id'];
$lmusaha=$_POST['lmusaha'];
$df=$_POST['df'];
$hrg=$_POST['hrg'];
$inv=$_POST['inv'];
$opr=$_POST['opr'];
$pen=$_POST['pen'];
// $dfpersen=$_POST['dfpersen'];
$suhu=$_POST['suhu'];
$kecerahan=$_POST['kecerahan'];
$do=$_POST['do'];
$ph=$_POST['ph'];
//diskon faktor
$diskonfaktor = (1/(1*(1+$df)^$lmusaha));
$dfp = ($df*(1/100));
//perhitungan analisis finansial
$npv = (($pen-($pen*$dfp))-(($opr-($opr*$dfp))));
$roi = (($npv-$inv)/$inv);
$bcr = ($pen/$opr);
$pbp = ($inv/$pen*(1+$dfp));
$bep = ($opr/$hrg);
$sql = 'UPDATE ikan
SET nama = "'.$nama.'",
lmusaha = "'.$lmusaha.'",
df = "'.$df.'",
hrg = "'.$hrg.'",
inv = "'.$inv.'",
opr = "'.$opr.'",
pen = "'.$pen.'",
suhu = "'.$suhu.'",
kecerahan = "'.$kecerahan.'",
do = "'.$do.'",
ph = "'.$ph.'",
npv = "'.$npv.'",
roi = "'.$roi.'",
bcr = "'.$bcr.'",
pbp = "'.$pbp.'",
bep = "'.$bep.'"
WHERE id = "'.$id.'"';
$rslt=mysqli_query($conn,$sql);
if($rslt){
echo "berhasil";
}else{
echo mysqli_error($conn);
}
?><file_sep>/halaman/edit-data.php
<?php
require('koneksi.php');
$nama=$_GET['nama'];
$sql="select * from ikan where id='" .$nama."'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_object($result);
//print_r($row);
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>Sistem Pendukung Keputusan AF-TOPSIS</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/theme-1.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all"/>
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie9.css" />
<![endif]-->
<script src="../libs/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>
<script src="../js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
</head>
<body>
<div class="main-container">
<div class="container">
<div class="col-xs-12 col-sm-9">
<br>
<h3><b>Edit Data Ikan</b></h3>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-bordered table-striped">
<input type="text" id="id" name="id" value="<?php echo $row->id; ?>">
<Tr><td>Nama Ikan</td><td><input type="text" value="<?php echo $row->nama; ?>" id="nama" class="form-control" maxlength="16"></td></Tr>
<Tr><td>Lama Usaha (Tahun)</td><td><input type="numeric" value="<?php echo $row->lmusaha; ?>" id="lmusaha" class="form-control"></td></Tr>
<Tr><td>DF(%)</td><td><input type="numeric" value="<?php echo $row->df; ?>" id="df" class="form-control"></td> </Tr>
<Tr><td>Harga Ikan</td><td><input type="numeric" value="<?php echo $row->hrg; ?>" id="hrg" class="form-control"></td></Tr>
<Tr><td>Investasi</td><td><input type="numeric" value="<?php echo $row->inv; ?>" id="inv" class="form-control"></td></Tr>
<Tr><td>Operasional</td><td><input type="numeric" value="<?php echo $row->opr; ?>" id="opr" class="form-control"></td></Tr>
<Tr><td>Penerimaan</td><td><input type="numeric" value="<?php echo $row->pen; ?>"id="pen" class="form-control"></td></Tr>
<Tr><td>Suhu</td><td><input type="numeric" value="<?php echo $row->suhu; ?>" id="suhu" class="form-control"></td></Tr>
<Tr><td>Kecerahan</td><td><input type="numeric" value="<?php echo $row->kecerahan; ?>" id="kecerahan" class="form-control"></td></Tr>
<Tr><td>Derivater Oksigen</td><td><input type="numeric" value="<?php echo $row->do; ?>" id="do" class="form-control"></td></Tr>
<Tr><td>pH</td><td><input type="numeric" value="<?php echo $row->ph; ?>" id="ph" class="form-control"></td></Tr>
</table>
</div> <!-- table responsive2 -->
</div> <!-- col -->
<input type="button" id="btnSave" class="btn btn-primary btn-sm" value="Simpan">
<input type="button" id="btnBack" class="btn btn-primary btn-sm" value="Kembali">
</div> <!-- panel default -->
</div> <!-- container -->
</div> <!--main-container-->
<script language="javascript">
$(document).ready(function(){
$("#btnSave").click(function(){
var nama=$("#nama").val();
var id=$("#id").val();
var lmusaha=$("#lmusaha").val();
var df=$("#df").val();
var hrg=$("#hrg").val();
var inv=$("#inv").val();
var opr=$("#opr").val();
var pen=$("#pen").val();
// var dfpersen=$("#dfpersen").val();
var suhu=$("#suhu").val();
var kecerahan=$("#kecerahan").val();
var dor=$("#do").val();
var ph=$("#ph").val();
var dataString= 'nama='+nama + '&id='+id + '&lmusaha='+lmusaha + '&df='+df+ '&hrg='+hrg + '&inv='+inv + '&opr='+opr+'&pen='+pen
+'&suhu='+suhu +'&kecerahan='+kecerahan+'&do='+ dor+'&ph='+ph;
// console.log(dataString);
// if(Ikan==''){
// alert("NUPTK harus diisi");
// }else if(!$.isNumeric(lama_usaha)){
// alert("Lama usaha harus angka!");
// }else if(!$.isNumeric(DF_)){
// alert("DF harus angka!");
// }else if(!$.isNumeric(harga_ikan)){
// alert("Harga Ikan harus angka!");
// }else if(!$.isNumeric(Investasi)){
// alert("Investasi harus angka!");
// }else if(!$.isNumeric(Operasional)){
// alert("Operasional harus angka!");
// }else if(!$.isNumeric(Penerimaan)){
// alert("Penerimaan harus angka !");
// }
// else{
$.ajax({
type: "POST",
url: "updatedata.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
// }
});
});
$(document).ready(function(){
$("#btnBack").click(function(){
window.location.href="http://localhost/doan/index.php?page=entridata";
});
});
</script>
<script src="../libs/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/scripts.js"></script>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.plugin.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery.flexslider-min.js"></script>
<script src="../js/smooth-scroll.min.js"></script>
<script src="../js/skrollr.min.js"></script>
<script src="../js/spectragram.min.js"></script>
<script src="../js/scrollReveal.min.js"></script>
<script src="../js/isotope.min.js"></script>
<script src="../js/twitterFetcher_v10_min.js"></script>
<script src="../js/lightbox.min.js"></script>
<script src="../js/jquery.countdown.min.js"></script>
<script src="../js/scripts.js"></script>
</body>
</html> <file_sep>/halaman/matriks.php
<!DOCTYPE html>
<html > <!--<![endif]-->
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/theme-1.css" rel="stylesheet" type="text/css" media="all"/>
<link href="../css/custom.css" rel="stylesheet" type="text/css" media="all"/>
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" href="css/ie9.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>
<script src="js/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<!-- deklarasi script -->
<script src="libs/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="nav-container">
<nav class="simple-bar top-bar">
<div class="container">
<div class="row nav-menu">
<div class="col-md-3 col-sm-3 columns">
<a href="index.php?page=home">
<img class="logo logo-dark" alt="Logo" src="img/logotype_dark.png">
</div>
<div class="col-md-9 col-sm-9 columns text-right">
<ul class="menu">
<a></a><li><a href="index.php?page=home" target="_self">Home</a></li>
<li><a href="index.php?page=entridata"><span class="glyphicon glyphicon-th-large"></span> Entri Data</a></li>
<li><a href="index.php?page=perhitungan"><span class="glyphicon glyphicon-th-large"></span> Perhitungan</a></li>
<li><a href="proses.php" target="_self">Proses</a></li>
<li><a href="hasil.php" target="_self">Hasil</a></li>
</ul>
</div>
</div>
<div class="mobile-toggle">
<i class="icon icon_menu"></i>
</div>
</div>
</nav>
</div>
</div>
<div class="main-container">
<div class="panel panel-default">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>cost/benefit</th>
<th>cost</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
<th>benefit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kepentingan</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>5</td>
<td>3</td>
<td>3</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
<tr>
<thead>
<tr>
<th>Nama Ikan</th>
<th>Net Present Value</th>
<th>Return On Investment</th>
<th>Benefit Cost Ratio</th>
<th>Pay Back Period</th>
<th>Break Event Point</th>
<th>Suhu</th>
<th>Kecerahan</th>
<th>DO</th>
<th>pH</th>
</tr>
</thead>
<tbody>
<?php require ('koneksi.php');
$sql="SELECT * from ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
?>
<tr>
<td><?php echo $row->nama; ?></td>
<td><?php echo $row->npv;?></td>
<td><?php echo $row->roi;?></td>
<td><?php echo $row->bcr;?></td>
<td><?php echo $row->pbp;?></td>
<td><?php echo $row->bep;?></td>
<td><?php echo $row->suhu;?></td>
<td><?php echo $row->kecerahan;?></td>
<td><?php echo $row->do;?></td>
<td><?php echo $row->ph;?></td>
</tr>
<?php } ?>
</table>
<hr/>
<h2> MATRIKS TERNORMALISASI</h2>
<table class="table table-bordered table-hover table-striped">
<tbody>
<?php require ('koneksi.php');
//pembagi npv
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------ternormalisasi
$norm_npv = $row2->npv/$pembagi_npv;
$norm_roi = $row2->roi/$pembagi_roi;
$norm_bcr = $row2->bcr/$pembagi_bcr;
$norm_pbp = $row2->pbp/$pembagi_pbp;
$norm_bep = $row2->bep/$pembagi_bep;
$norm_suhu = $row2->suhu/$pembagi_suhu;
$norm_kecerahan= $row2->kecerahan/$pembagi_kecerahan;
$norm_do = $row2->do/$pembagi_do;
$norm_ph = $row2->ph/$pembagi_ph;
?>
<tr>
<td><?php echo $row2->nama; ?></td>
<td><?php echo $norm_npv;?></td>
<td><?php echo $norm_roi;?></td>
<td><?php echo $norm_bcr;?></td>
<td><?php echo $norm_pbp;?></td>
<td><?php echo $norm_bep;?></td>
<td><?php echo $norm_suhu;?></td>
<td><?php echo $norm_kecerahan;?></td>
<td><?php echo $norm_do;?></td>
<td><?php echo $norm_ph;?></td>
</tr>
<?php } ?>
</table>
</div>
<hr/>
<h2>MATRIKS TERBOBOT</h2>
<table class="table table-bordered table-hover table-striped">
<tbody>
<?php require ('koneksi.php');
$result = mysqli_query($conn,$sql);
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------TERBOBOT
$norm_terb_npv = ($row2->npv/$pembagi_npv)*5;
$norm_terb_roi = ($row2->roi/$pembagi_roi)*5;
$norm_terb_bcr = ($row2->bcr/$pembagi_bcr)*5;
$norm_terb_pbp = ($row2->pbp/$pembagi_pbp)*5;
$norm_terb_bep = ($row2->bep/$pembagi_bep)*5;
$norm_terb_suhu = ($row2->suhu/$pembagi_suhu)*3;
$norm_terb_kecerahan= ($row2->kecerahan/$pembagi_kecerahan)*3;
$norm_terb_do = ($row2->do/$pembagi_do)*2;
$norm_terb_ph = ($row2->ph/$pembagi_ph)*3;
?>
<tr>
<td><?php echo $row2->nama; ?></td>
<td><?php echo $norm_terb_npv;?></td>
<td><?php echo $norm_terb_roi;?></td>
<td><?php echo $norm_terb_bcr;?></td>
<td><?php echo $norm_terb_pbp;?></td>
<td><?php echo $norm_terb_bep;?></td>
<td><?php echo $norm_terb_suhu;?></td>
<td><?php echo $norm_terb_kecerahan;?></td>
<td><?php echo $norm_terb_do;?></td>
<td><?php echo $norm_terb_ph;?></td>
</tr>
<?php } ?>
</table>
</hr>
<h2>Matriks Solusi Ideal</h2>
<?php require ('koneksi.php');
//FOR NPV
$sqla="SELECT nama,sum(npvp) as tot_npv from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_npv = sqrt($rowa->tot_npv);
}
$sql2="SELECT min(npv) as npv from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_npv = ($row2->npv/$pembagi_npv)*5;
}
//FOR ROI
$sqla="SELECT nama,sum(roip) as tot_roi from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_roi = sqrt($rowa->tot_roi);
}
$sql2="SELECT max(roi) as roi from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_roi = ($row2->roi/$pembagi_roi)*5;
}
//FOR BCR
$sqla="SELECT nama,sum(bcrp) as tot_bcrp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bcr = sqrt($rowa->tot_bcrp);
}
$sql2="SELECT max(bcr) as bcr from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_bcr = ($row2->bcr/$pembagi_bcr)*5;
}
//FOR PBP
$sqla="SELECT nama,sum(pbpp) as tot_pbpp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_pbp = sqrt($rowa->tot_pbpp);
}
$sql2="SELECT max(pbp) as pbp from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_pbp = ($row2->pbp/$pembagi_pbp)*5;
}
//FOR BEP
$sqla="SELECT nama,sum(bepp) as tot_bepp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bep = sqrt($rowa->tot_bepp);
}
$sql2="SELECT max(bep) as bep from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_bep = ($row2->bep/$pembagi_bep)*5;
}
//FOR SUHU
$sqla="SELECT nama,sum(suhup) as tot_suhup from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_suhu = sqrt($rowa->tot_suhup);
}
$sql2="SELECT max(suhu) as suhu from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_suhu = ($row2->suhu/$pembagi_suhu)*5;
}
//FOR KECERAHAN
$sqla="SELECT nama,sum(kecerahanp) as tot_kecerahanp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_kecerahan = sqrt($rowa->tot_kecerahanp);
}
$sql2="SELECT max(kecerahan) as kecerahan from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_kecerahan = ($row2->kecerahan/$pembagi_kecerahan)*5;
}
//FOR DO
$sqla="SELECT nama,sum(dop) as tot_dop from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_do = sqrt($rowa->tot_dop);
}
$sql2="SELECT max(do) as do from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_do = ($row2->do/$pembagi_do)*5;
}
// FOR pH
$sqla="SELECT nama,sum(ph) as tot_ph from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_ph = sqrt($rowa->tot_ph);
}
$sql2="SELECT max(ph) as ph from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_ph = ($row2->ph/$pembagi_ph)*5;
}
?>
<table class="table table-bordered table-hover table-striped">
<tbody><tr>
<th>A+</th>
<th><?php echo $norm_npv; ?></th>
<th><?php echo $norm_roi; ?></th>
<th><?php echo $norm_bcr; ?></th>
<th><?php echo $norm_pbp; ?></th>
<th><?php echo $norm_bep; ?></th>
<th><?php echo $norm_suhu; ?></th>
<th><?php echo $norm_kecerahan; ?></th>
<th><?php echo $norm_do; ?></th>
<th><?php echo $norm_ph; ?></th>
</tr>
<?php
//FOR NPV
$sqla="SELECT nama,sum(npvp) as tot_npv from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_npvs = sqrt($rowa->tot_npv);
}
$sql2="SELECT max(npv) as npv from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_npv = ($row2->npv/$pembagi_npvs)*5;
}
//FOR ROI
$sqla="SELECT nama,sum(roip) as tot_roi from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_roi = sqrt($rowa->tot_roi);
}
$sql2="SELECT min(roi) as roi from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_roi = ($row2->roi/$pembagi_roi)*5;
}
//FOR BCR
$sqla="SELECT nama,sum(bcrp) as tot_bcrp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bcr = sqrt($rowa->tot_bcrp);
}
$sql2="SELECT min(bcr) as bcr from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_bcr = ($row2->bcr/$pembagi_bcr)*5;
}
//FOR PBP
$sqla="SELECT nama,sum(pbpp) as tot_pbpp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_pbp = sqrt($rowa->tot_pbpp);
}
$sql2="SELECT min(pbp) as pbp from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_pbp = ($row2->pbp/$pembagi_pbp)*5;
}
//FOR BEP
$sqla="SELECT nama,sum(bepp) as tot_bepp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_bep = sqrt($rowa->tot_bepp);
}
$sql2="SELECT min(bep) as bep from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_bep = ($row2->bep/$pembagi_bep)*5;
}
//FOR SUHU
$sqla="SELECT nama,sum(suhup) as tot_suhup from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_suhu = sqrt($rowa->tot_suhup);
}
$sql2="SELECT max(suhu) as suhu from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_suhu = ($row2->suhu/$pembagi_suhu)*5;
}
//FOR KECERAHAN
$sqla="SELECT nama,sum(kecerahanp) as tot_kecerahanp from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_kecerahan = sqrt($rowa->tot_kecerahanp);
}
$sql2="SELECT min(kecerahan) as kecerahan from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_kecerahan = ($row2->kecerahan/$pembagi_kecerahan)*5;
}
//FOR DO
$sqla="SELECT nama,sum(dop) as tot_dop from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_do = sqrt($rowa->tot_dop);
}
$sql2="SELECT min(do) as do from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_do = ($row2->do/$pembagi_do)*5;
}
// FOR pH
$sqla="SELECT nama,sum(ph) as tot_ph from v_ikan";
$resulta = mysqli_query($conn,$sqla);
while($rowa = mysqli_fetch_object($resulta)){
$pembagi_ph = sqrt($rowa->tot_ph);
}
$sql2="SELECT min(ph) as ph from ikan ";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
$norm_min_ph = ($row2->ph/$pembagi_ph)*5;
}
?>
<tr>
<th>A-</th>
<th><?php echo $norm_min_npv; ?></th>
<th><?php echo $norm_min_roi; ?></th>
<th><?php echo $norm_min_bcr; ?></th>
<th><?php echo $norm_min_pbp; ?></th>
<th><?php echo $norm_min_bep; ?></th>
<th><?php echo $norm_min_suhu; ?></th>
<th><?php echo $norm_min_kecerahan; ?></th>
<th><?php echo $norm_min_do; ?></th>
<th><?php echo $norm_min_ph; ?></th>
</tr>
</tbody>
</table>
<h2>Jarak Solusi Ideal</h2>
<table class="table table-bordered table-hover table-striped">
<tbody>
<tr>
<th>D+</th>
<th>D-</th>
<th>V</th>
</tr>
<?php require ('koneksi.php');
$result = mysqli_query($conn,$sql);
$sql="SELECT nama,sum(npvp) as tot_npv,
sum(roip) as tot_roi,
sum(bcrp) as tot_bcr,
sum(pbpp) as tot_pbp,
sum(bepp) as tot_bep,
sum(suhup) as tot_suhu,
sum(kecerahanp) as tot_kecerahan,
sum(dop) as tot_do,
sum(ph) as tot_ph
from v_ikan";
while($row = mysqli_fetch_object($result)){
$pembagi_npv = sqrt($row->tot_npv);
$pembagi_roi = sqrt($row->tot_roi);
$pembagi_bcr = sqrt($row->tot_bcr);
$pembagi_pbp = sqrt($row->tot_pbp);
$pembagi_bep = sqrt($row->tot_bep);
$pembagi_suhu = sqrt($row->tot_suhu);
$pembagi_kecerahan = sqrt($row->tot_kecerahan);
$pembagi_do = sqrt($row->tot_do);
$pembagi_ph = sqrt($row->tot_ph);
}
$sql2="SELECT * from ikan";
$result2 = mysqli_query($conn,$sql2);
while($row2 = mysqli_fetch_object($result2)){
//-----------TERBOBOT
$norm_terb_npv = ($row2->npv/$pembagi_npv)*5;
$norm_terb_roi = ($row2->roi/$pembagi_roi)*5;
$norm_terb_bcr = ($row2->bcr/$pembagi_bcr)*5;
$norm_terb_pbp = ($row2->pbp/$pembagi_pbp)*5;
$norm_terb_bep = ($row2->bep/$pembagi_bep)*5;
$norm_terb_suhu = ($row2->suhu/$pembagi_suhu)*3;
$norm_terb_kecerahan= ($row2->kecerahan/$pembagi_kecerahan)*3;
$norm_terb_do = ($row2->do/$pembagi_do)*2;
$norm_terb_ph = ($row2->ph/$pembagi_ph)*3;
// ---------JARAK SOLUSI IDEAL
$dplus = sqrt(
pow(($norm_npv - $norm_terb_npv),2) +
pow(($norm_roi - $norm_terb_roi),2)+
pow(($norm_bcr - $norm_terb_bcr),2)+
pow(($norm_pbp - $norm_terb_pbp),2)+
pow(($norm_bep - $norm_terb_bep),2)+
pow(($norm_suhu - $norm_terb_suhu),2)+
pow(($norm_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_do - $norm_terb_do),2)+
pow(($norm_ph - $norm_terb_ph),2)
);
$dmin = sqrt(
pow(($norm_min_npv - $norm_terb_npv),2) +
pow(($norm_min_roi - $norm_terb_roi),2)+
pow(($norm_min_bcr - $norm_terb_bcr),2)+
pow(($norm_min_pbp - $norm_terb_pbp),2)+
pow(($norm_min_bep - $norm_terb_bep),2)+
pow(($norm_min_suhu - $norm_terb_suhu),2)+
pow(($norm_min_kecerahan - $norm_terb_kecerahan),2)+
pow(($norm_min_do - $norm_terb_do),2)+
pow(($norm_min_ph - $norm_terb_ph),2)
);
?>
<tr>
<td><?php echo $dplus; ?></td>
<td><?php echo $dmin; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!--panel-default-->
</div> <!--main-container-->
</body>
</html>
| 7eac6571bead238805ccf4eca020a2bf80002e92 | [
"SQL",
"PHP"
]
| 18 | PHP | sywl-ds/test | 5997b2604ec281fa3b4a77659e0ac74e6e700ba1 | 70b507a54e2e513b94287535a711a86ad1fce776 |
refs/heads/master | <file_sep>package com.noname.setalarm.repository;
import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
import androidx.room.Relation;
import androidx.room.TypeConverters;
import androidx.annotation.NonNull;
import com.noname.setalarm.model.ClockModel;
import java.util.List;
@Entity
public class AlarmRoom {
@PrimaryKey
@NonNull
private String alarmId;
@TypeConverters(ClockTypeConverter.class)
public final List<ClockModel> timeList;
private boolean checked;
private String memo;
public AlarmRoom(@NonNull String alarmId, List<ClockModel> timeList, boolean checked, String memo) {
this.alarmId = alarmId;
this.timeList = timeList;
this.checked = checked;
this.memo = memo;
}
@NonNull
public String getAlarmId() {
return alarmId;
}
public List<ClockModel> getTimeList() {
return timeList;
}
public boolean isChecked() {
return checked;
}
public String getMemo() {
return memo;
}
}
<file_sep>SetAlarm Project
================
<!-- 예제) \{:height="100px" width="100px"} -->
예제)
<img src ="https://user-images.githubusercontent.com/7121217/48350868-cc970900-e6cb-11e8-924a-0cc94a0a8587.gif" width="30%">
### 제원
- 언어 : android
- db : androd Room
- glide, glide-transformations
- andorid material
- gson library
### ViewModel
- 정의 : ui 컨트롤러와 repository를 연결. 데이터에 대한 부분을 추상화 함으로써 객체지향적 프로그래밍을 유도함. 안드로이드는 Lifecycle 에 관한 기능도 포함해 안정적인 프로그래밍 지원.
- LiveData: 관찰 할 수있는 데이터 홀더 클래스 . 최신 버전의 데이터를 항상 보유 / 캐시. 데이터가 변경되면 옵서버에게 알린다. LiveData는 관측하는 동안 관련 라이프 사이클 상태가 변경되었음을 알고 있기 때문에 이 모든 것을 자동으로 관리한다. UI 구성 요소는 관련 데이터를 관찰하고 관찰을 중지하거나 다시 시작하지 않습니다.
- repository : 데이터엑세스 오브젝트(DAO) 를 통한 데이터 제공자.
- 구성 : 사용자 - UI - Viewmodel - livedata - repository(room + DAO)
### DB 구성
1. ClockModel : 한개의 알람세트의 데이터를 담당하는 모델.
2. AlarmModel : ClockModel의 묶음. 알람세트의 전체뷰를 보여주는 모델.
<file_sep>package com.noname.setalarm.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import androidx.lifecycle.ViewModelProviders;
import androidx.databinding.DataBindingUtil;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.TimePicker;
import com.noname.setalarm.AlarmLogic;
import com.noname.setalarm.R;
import com.noname.setalarm.databinding.ActivityAddalarmBinding;
import com.noname.setalarm.model.ClockModel;
import com.noname.setalarm.repository.AlarmRoom;
import com.noname.setalarm.viewmodel.ClockViewModel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
public class AddAlarmActivity extends AppCompatActivity {
private static String TAG = AddAlarmActivity.class.getSimpleName();
private ActivityAddalarmBinding activityAddalarmBinding;
private AlarmLogic alarmLogic;
private ClockViewModel viewModel;
private SelectionTracker selectionTracker;
private ArrayList<ClockModel> models = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityAddalarmBinding = DataBindingUtil.setContentView(this, R.layout.activity_addalarm);
activityAddalarmBinding.setLifecycleOwner(this);
activityAddalarmBinding.setProvider(new ImageProvider(R.drawable.hills, R.drawable.moon));
setSupportActionBar(activityAddalarmBinding.toolbar);
Intent intent = getIntent();
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) >= 12){
activityAddalarmBinding.pm.setVisibility(View.INVISIBLE);
}else {
activityAddalarmBinding.pm.setVisibility(View.VISIBLE);
}
alarmLogic = new AlarmLogic(this);
viewModel = ViewModelProviders.of(this).get(ClockViewModel.class);
if (intent.hasExtra("modifyList")) {
models = intent.getParcelableArrayListExtra("modifyList");
for (ClockModel clockModel : models){
viewModel.insert(clockModel);
}
}else {
// Log.d(TAG, "HOUR + " + alarmLogic.getCurrentHour() + "MINUTE : " + alarmLogic.getCurrentMinute());
ClockModel clockModel = new ClockModel(alarmLogic.makeID(alarmLogic.getCurrentHour(), alarmLogic.getCurrentMinute(), alarmLogic.getCurrentSecond()),
alarmLogic.getCurrentHour(), alarmLogic.getCurrentMinute(), alarmLogic.getCurrentHour() >= 12);
models.add(clockModel);
viewModel.insert(clockModel);
}
// selectionTracker = new SelectionTracker.Builder("selction-clock",
// activityAddalarmBinding.recycler, new StableIdKeyProvider(activityAddalarmBinding.recycler),
// new MyDetailsLookup(activityAddalarmBinding.recycler), StorageStrategy.createLongStorage()
// ).build();
//
// selectionTracker.addObserver(new SelectionTracker.SelectionObserver() {
// @Override
// public void onItemStateChanged(@NonNull Object key, boolean selected) {
// super.onItemStateChanged(key, selected);
// Log.d(TAG , "selected item key: " + key);
// }
// });
ClockAdapter clockAdapter = new ClockAdapter(getApplicationContext());
viewModel.getListLiveData().observe(this, clockModels -> {
clockAdapter.submitList(clockModels);
});
clockAdapter.setClockClickListener((hour, minute) -> {
activityAddalarmBinding.timer.setHour(hour);
activityAddalarmBinding.timer.setMinute(minute);
revealpm(hour);
});
activityAddalarmBinding.recycler.setAdapter(clockAdapter);
LinearLayoutManager horizontalLayout = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
activityAddalarmBinding.recycler.setLayoutManager(horizontalLayout);
activityAddalarmBinding.timer.setIs24HourView(true);
activityAddalarmBinding.timer.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minutes) {
viewModel.updateHour(clockAdapter.getSelectedID(), hourOfDay);
viewModel.updateMinute(clockAdapter.getSelectedID(), minutes);
viewModel.updateAMPM(clockAdapter.getSelectedID(), hourOfDay >= 12);
revealpm(hourOfDay);
}
});
ArrayList<ClockModel> finalModels = models;
activityAddalarmBinding.addSize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar tmp = Calendar.getInstance();
Log.d(TAG, "추가");
ClockModel tmpClock = new ClockModel(alarmLogic.makeID(tmp.get(Calendar.HOUR_OF_DAY), tmp.get(Calendar.MINUTE), tmp.get(Calendar.SECOND)),
tmp.get(Calendar.HOUR_OF_DAY), tmp.get(Calendar.MINUTE), tmp.get(Calendar.HOUR_OF_DAY)<12);
finalModels.add(tmpClock);
viewModel.insert(tmpClock);
}
});
activityAddalarmBinding.confirm.setOnClickListener(v -> {
//수정버튼으로 들어온 경우
//원래 id 의 alarmroom 데이터를 수정된 clocklist로 덮어씌워야함.
//원래 id의 알람은 삭제.
if(intent.hasExtra("modifyList")){
for (int i = 0; i<models.size(); i++) {
alarmLogic.unregisterAlarm(models.get(i).getId());
}
List<ClockModel> tmpList = viewModel.getListLiveData().getValue();
for (int i = 0; i < tmpList.size(); i++) {
alarmLogic.setToCalendar(tmpList.get(i).getHour(),
tmpList.get(i).getMinute(),
tmpList.get(i).getHour() >= 12);
alarmLogic.newAlarm(tmpList.get(i).getId(),
alarmLogic.getCalendarTime());
}
viewModel.updateAlarm(intent.getStringExtra("alarmId"), tmpList);
}else {
List<ClockModel> tmpList = viewModel.getListLiveData().getValue();
for (int i = 0; i < tmpList.size(); i++) {
alarmLogic.setToCalendar(tmpList.get(i).getHour(),
tmpList.get(i).getMinute(),
tmpList.get(i).getHour() >= 12);
alarmLogic.newAlarm(tmpList.get(i).getId(),
alarmLogic.getCalendarTime());
}
viewModel.insertAlarm(new AlarmRoom(UUID.randomUUID().toString(), tmpList, true,
activityAddalarmBinding.memo.getText().toString()));
}
viewModel.deleteAll();
super.onBackPressed();
});
}
@Override
protected void onStart() {
super.onStart();
rescaleViewAnimation(activityAddalarmBinding.confirm, 1f, 500, null);
}
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
@Override
public void finish(){
rescaleViewAnimation(activityAddalarmBinding.confirm, 0, 300, new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
AddAlarmActivity.super.finish();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
viewModel.deleteAll();
}
private void revealpm(int hour){
//am_pm true : 오후 false: 오전
if( (hour < 12 && !activityAddalarmBinding.pm.isShown())){
revealThepm();
} else if (hour >= 12 && activityAddalarmBinding.pm.isShown()) {
hideThepm();
}
}
private Animator createRevealAnimator(boolean show, View view ) {
final int cx = view.getWidth() ;
final int cy = view.getHeight() ;
final int radius = (int) Math.hypot(cx, cy);
final Animator animator;
if (show) {
animator = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, radius);
animator.setInterpolator(new DecelerateInterpolator());
} else {
animator = ViewAnimationUtils.createCircularReveal(view, cx, cy, radius, 0);
animator.setInterpolator(new AccelerateInterpolator());
}
animator.setDuration(getResources().getInteger(R.integer.default_anim_duration));
return animator;
}
private void revealThepm() {
activityAddalarmBinding.pm.setVisibility(View.VISIBLE);
Animator reveal = createRevealAnimator(true, activityAddalarmBinding.pm);
reveal.start();
activityAddalarmBinding.am.setVisibility(View.INVISIBLE);
}
/**
* Hide the am
*/
private void hideThepm() {
activityAddalarmBinding.am.setVisibility(View.VISIBLE);
Animator hide = createRevealAnimator(false, activityAddalarmBinding.pm);
hide.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
activityAddalarmBinding.pm.setVisibility(View.INVISIBLE);
}
});
hide.start();
}
private void rescaleViewAnimation(View view,
float targetScale,
int durationOffset,
Animator.AnimatorListener listener) {
ObjectAnimator scaleOnX = ObjectAnimator.ofFloat(view, "scaleX", targetScale);
ObjectAnimator scaleOnY = ObjectAnimator.ofFloat(view, "scaleY", targetScale);
scaleOnX.setDuration(durationOffset);
scaleOnY.setDuration(durationOffset);
AnimatorSet scaleSet = new AnimatorSet();
scaleSet.playTogether(
scaleOnX,
scaleOnY
);
if (listener != null){
scaleSet.addListener(listener);
}
scaleSet.start();
}
}
<file_sep>package com.noname.setalarm.view;
import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
public class ImageProvider extends BaseObservable {
private int amPic;
private int pmPic;
public ImageProvider(int amPic, int pmPic) {
this.amPic = amPic;
this.pmPic = pmPic;
}
@Bindable
public int getAmPic() {
return amPic;
}
@Bindable
public int getPmPic() {
return pmPic;
}
}
<file_sep>package com.noname.setalarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.noname.setalarm.receiver.AlarmReceiver;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class AlarmLogic {
private static String TAG = AlarmLogic.class.getSimpleName();
private Context context;
private Calendar calendar = Calendar.getInstance();
private static AlarmManager am;
private static PendingIntent sender;
public AlarmLogic(Context context) {
this.context = context;
calendar.setTimeInMillis(System.currentTimeMillis());
}
private void setAm(int id){
am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(context, AlarmReceiver.class);
sender = PendingIntent.getBroadcast(context, id, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void setToCalendar(int hour, int minute, boolean am_pm){
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, am_pm ? Calendar.PM : Calendar.AM);
}
public int getCurrentHour(){
Calendar tmpCal = Calendar.getInstance();
return tmpCal.get(Calendar.HOUR_OF_DAY);}
public int getCurrentMinute(){
Calendar tmpCal = Calendar.getInstance();
return tmpCal.get(Calendar.MINUTE);}
public int getCurrentSecond(){
Calendar tmpCal = Calendar.getInstance();
return tmpCal.get(Calendar.SECOND);}
public long getCalendarTime(){
return calendar.getTimeInMillis();
}
public int makeID(int hour, int minute, int second){
Calendar tmpCal = Calendar.getInstance();
StringBuilder sb = new StringBuilder();
sb.append(hour);
sb.append(minute);
sb.append(second);
sb.append(tmpCal.get(Calendar.MILLISECOND));
return Integer.parseInt(sb.toString());
}
//pendingintent id는 무조건 고유해야함.
public void newAlarm(int id, long time){
setAm(id);
if(System.currentTimeMillis() < time) {
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, time,
AlarmManager.INTERVAL_DAY, sender);
// Date date1 = new Date(System.currentTimeMillis());
// Date date2 = new Date(time);
// DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
// formatter.setTimeZone(TimeZone.getTimeZone("gmt"));
// String currentTimeMillis = formatter.format(date1);
// String timestring = formatter.format(date2);
//
// Log.d(TAG , "현재시간" + currentTimeMillis + " 이후" + timestring);
}else {
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, time + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, sender);
// Date date1 = new Date(System.currentTimeMillis());
// Date date2 = new Date(time);
// DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
// formatter.setTimeZone(TimeZone.getTimeZone("gmt"));
// String currentTimeMillis = formatter.format(date1);
// String timestring = formatter.format(date2);
//
// Log.d(TAG , "현재시간" + currentTimeMillis + " 이전" + timestring);
}
}
public void unregisterAlarm(int id){
setAm(id);
am.cancel(sender);
sender.cancel();
am = null;
sender = null;
}
}
<file_sep>package com.noname.setalarm.repository;
import com.noname.setalarm.model.ClockModel;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface AlarmDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insertAlarm(AlarmRoom... alarmRoom);
@Query("UPDATE AlarmRoom SET timeList= :timeList WHERE alarmId = :id")
void updateAlarm(String id, List<ClockModel> timeList);
@Query("UPDATE AlarmRoom SET checked= :checked WHERE alarmId = :id")
void updateAlarmState(String id , boolean checked);
@Delete
void deleteAlarm(AlarmRoom alarmRoom);
@Query("SELECT * from AlarmRoom")
LiveData<List<AlarmRoom>> getAllAlarm();
}
<file_sep>package com.noname.setalarm.viewmodel;
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.annotation.NonNull;
import com.noname.setalarm.model.ClockModel;
import com.noname.setalarm.repository.AlarmRoom;
import com.noname.setalarm.repository.AlarmRoomRepo;
import java.util.List;
public class ClockViewModel extends AndroidViewModel {
private AlarmRoomRepo alarmRoomRepo;
private LiveData<List<ClockModel>> listLiveData;
public ClockViewModel(@NonNull Application application) {
super(application);
this.alarmRoomRepo = new AlarmRoomRepo(application);
}
public LiveData<List<ClockModel>> getListLiveData() {
if (listLiveData == null){
listLiveData = alarmRoomRepo.getAllClock();
}
return listLiveData;
}
public void insert(ClockModel clockModel) { alarmRoomRepo.insertClockModel(clockModel); }
public void insertAlarm(AlarmRoom alarmRoom){alarmRoomRepo.insert(alarmRoom);}
public void updateAlarm(String id, List<ClockModel> timeList){alarmRoomRepo.update(id, timeList);}
public void delete(ClockModel clockModel){alarmRoomRepo.deleteClockModel(clockModel);}
public void deleteAll(){alarmRoomRepo.deleteAllClock();}
public void updateHour(int id, int hour){alarmRoomRepo.updateClockHour(id, hour);}
public void updateMinute(int id, int minute){alarmRoomRepo.updateClockMinute(id, minute);}
public void updateAMPM(int id, boolean am_pm){alarmRoomRepo.updateClockAMPM(id, am_pm);}
}
<file_sep>package com.noname.setalarm.view;
public interface OnClockClickListener {
void OnClockItemClick(int hour, int minute);
}
<file_sep>package com.noname.setalarm.repository;
import android.app.Application;
import androidx.lifecycle.LiveData;
import com.noname.setalarm.model.ClockModel;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AlarmRoomRepo {
private AlarmDao alarmDao;
private ClockDao clockDao;
private LiveData<List<AlarmRoom>> alarmLiveData;
private LiveData<List<ClockModel>> clockLiveData;
private ExecutorService executorService;
public AlarmRoomRepo(Application application) {
AppDatabase db = AppDatabase.getDatabase(application);
alarmDao = db.alarmDao();
clockDao = db.clockDao();
alarmLiveData = alarmDao.getAllAlarm();
clockLiveData = clockDao.getAllClock();
executorService = Executors.newSingleThreadExecutor();
}
public LiveData<List<AlarmRoom>> getAllAlarm(){
return alarmLiveData;
}
public LiveData<List<ClockModel>> getAllClock(){
return clockLiveData;
}
public void insert(AlarmRoom alarmRoom) {
executorService.execute(() -> alarmDao.insertAlarm(alarmRoom));
}
public void update(String id, List<ClockModel> timeList) {
executorService.execute(() -> alarmDao.updateAlarm(id, timeList));
}
public void delete(AlarmRoom alarmRoom){
executorService.execute(() -> alarmDao.deleteAlarm(alarmRoom));
}
public void updateAlarmState(String id, boolean checked){
executorService.execute(() -> alarmDao.updateAlarmState(id, checked));
}
public void insertClockModel(ClockModel clockModel) {
executorService.execute(() -> clockDao.insertClock(clockModel));
}
public void deleteClockModel(ClockModel clockModel){
executorService.execute(() -> clockDao.deleteClock(clockModel));
}
public void deleteAllClock(){
executorService.execute(() -> clockDao.deleteAll());
}
public void updateClockHour(int id, int hour){
executorService.execute(() -> clockDao.updateClockHour(id, hour));
}
public void updateClockMinute(int id, int minute){
executorService.execute(() -> clockDao.updateClockMinute(id, minute));
}
public void updateClockAMPM(int id, boolean am_pm){
executorService.execute(() -> clockDao.updateClockAMPM(id, am_pm));
}
}
| 18322ed8c191b3f179fbdb44a264897a0dbaf89c | [
"Markdown",
"Java"
]
| 9 | Java | dabin3178/setAlarm | e9bfd552a95751d9d07f4e0fef2fb20d430e5f25 | 7c630ff76b3b49f970860131a78f5f8482043db5 |
refs/heads/master | <repo_name>gabrielibarbosa/redesII_sniffer<file_sep>/README.md
# redesII_sniffer
Código sniffer implementado
<file_sep>/sniffer.py
#encoding: UTF-8
#enconding: ISO-8859-1
import pyshark
import csv
from datetime import datetime
captura = pyshark.LiveCapture(interface="eno1", only_summaries=True)
captura.sniff(packet_count=20)
nome_arquivo = ("dados_sniffer_%s.csv" % (datetime.now()))
with open(nome_arquivo, 'w', newline='') as csvfile:
fieldnames = ["numero","tempo","origem","destino","protocolo","tamanho","informacao"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for pkt in captura:
writer.writerow({
'numero': pkt.no,
'tempo': pkt.time,
'origem': pkt.source,
'destino': pkt.destination,
'protocolo': pkt.protocol,
'tamanho': pkt.length,
'informacao': pkt.info,
})
captura.close()
| 94de144e3dab5341a0355a37ff6fc8e16e1ba8a8 | [
"Markdown",
"Python"
]
| 2 | Markdown | gabrielibarbosa/redesII_sniffer | a9c7b9f7f31b7156029cdda755ca9d5b8cf40f64 | 5528515fad8c94003f71f834d09bb3fe7f6b6f94 |
refs/heads/main | <file_sep># Extracción de links en sitios web
Ejercicio de prueba. Dado una URL, extrae todos los links contenidos en ese sitio. Accesible tanto como endpoint de API (/scraping/) o como comando ejecutado en el container Docker. Se implementó generando una aplicación en FastAPI, con una base de PostgreSQL administrada con el ORM SQLAlchemy, pydantic para los Schemas de los endpoints y Docker para la administración de dependencias y deployment. "get_links.py" es el archivo que permite ejecutar la aplicación por linea de comandos, y para la API, el docker-compose configura un servidor uvicorn para servir la app. La principal lógica para resolver el problema se encuentra en el archivo "src/app/api/services.py". Esta pensando como una aplicación asíncrona por lo que la adaptación para linea de comandos fue necesaria.
## Instrucciones
### Buildear y ejecutar containers
Ejecutar el siguiente comando desde la raíz del proyecto para hacer el build del Docker y poner a correr los containers.
```
docker-compose up -d --build
```
### Test
Correr tests
```
docker-compose exec web pytest .
```
### Inspecccionar base de datos
Para acceder a inspeccionar la base de desarrollo:
```
docker-compose exec db psql --username=sraping_websites --dbname=sraping_websites_dev
```
### FastAPI entrypoint
Se puede ejecutar el comando POST directamente
```
curl -X 'POST' \
'http://localhost:8002/scraping/' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://google.com"
}'
```
o probarlo de forma manual desde [http://localhost:8002/docs](http://localhost:8002/docs) una vez
### Comando para el container Docker
Ejecutar para extraer lista de links (se puede concatenar con un '> links.csv' para guardar en archivp)
```
docker-compose exec web python get_links.py "https://google.com"
```
Ejecutar para obtener ademas un pequeño análisis respecto a scrapings pasados
```
docker-compose exec web python get_links.py -V "https://google.com"
```
Comando de ayuda para la aplicacion de consola
```
docker-compose exec web python get_links.py -h
```
## Cómo desplegar en AWS
Para el despliegue de esta aplicación desplegaría el contenedor Docker en Amazon Elastic Container Service (Amazon ECS). Esta aplicación administraría los dos servicios que se crean para esta aplicación: "web" que contiene la lógica de la aplicación, incluyendo la API y el archivo para ejecutar el comando por consola y "db" que contiene la base PostgreSQL para almacenar los logs de los scrapings. ECS administra estos dos servicios de manera transparente y no requiere en principio cambios en la configuración del docker-compose. Este sistema de gestión permitiría administrar el contenedor de manera sencilla y escalar la aplicación de ser necesario.
### Porqué el uso de ASYNC
Debido a que el web scraping es una tarea que lleva tiempo ya que involucra conectarse a la red y parsear un sitio web completo, utilizar un servicio de api asíncrona permite a la aplicación tomar mas pedidos y ejecutarlos de manera rápida pudiendo utilizar el tiempo de espera que se genera al conectarse a un sitio web para atender y procesar otros pedidos. Dependiendo de la demanda que tenga la aplicación, esto podría mejorar la performance en general.
### Warning
El modulo de testing vacia la base y la vuelve a crear para mantener consistencia con los resultados.
En un desarrollo hecho para producción esto debería resolverse con una base aparte para realizar los tests, de manera
que nunca se toque la base que efectivamente se utiliza. Para el proposito de este ejercicio alcanza este warning, pero
de ninguna manera deberia utilizarse asi en produccion.
<file_sep>from datetime import datetime
import json
from bs4 import BeautifulSoup
from app.api import services
def test_crawl_url_one_link_success(test_app,monkeypatch):
"""
Crawls a dummy site and has to find one link only.
"""
# URL to request crawling
test_request_payload = {"url": "https://onelinksite.com" }
# Response expected
test_response_links = ['http://example.com/']
# Dummy site
test_site = """
<html><head><title>The Dormouse's story</title></head>
<body>
<a href="http://example.com/" class="example" id="link1">Example</a>
</body>
"""
# We patch the function that retrieves the actual HTML of the site and parses it
# to give this placeholder site parsed version
async def mock_get_site_soup(payload):
return BeautifulSoup(test_site,'html.parser')
monkeypatch.setattr(services, "get_site_soup", mock_get_site_soup)
# Fetches the links in site
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
response_dict = response.json()
# Check if everything went right
assert response.status_code == 200
assert response_dict['links'] == test_response_links
def test_bad_url(test_app):
"""
The api should be able to handle a bad URL error properly.
"""
test_request_payload = {"url": "bad_url.//unexistingsite.com" }
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
assert response.status_code == 404
def test_empty_url(test_app):
"""
All empty urls should be issued a warning or error
"""
test_request_payload = {"url": "" }
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
assert response.status_code == 404
def test_bad_site(test_app):
"""
Broken or non-existing sites should through error
"""
test_request_payload = {"url": "http://thissitedoesntexist.xyz.com" }
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
assert response.status_code == 403
def test_change_reports(test_app,monkeypatch):
"""
This tests goes through the process of requesting the same site twice and getting a report
with the difference in the amount of DISTINCT links between the two crawls.
It uses two placeholder versions of the same site and only one URL, as it's meant to be a site that changes.
"""
test_request_payload = {"url": "https://onelinksite.com" }
test_site_1 = """
<html><head><title>The Dormouse's story</title></head>
<body>
<a href="http://example.com/" class="example" id="link1">Example</a>
</body>
"""
test_site_2 = """
<html><head><title>The Dormouse's story</title></head>
<body>
<a href="http://example1.com/" class="example" id="link1">Example</a>
<a href="http://example2.com/" class="example" id="link1">Example</a>
</body>
"""
# This mock function will return the one link site
async def mock_get_site_soup_1(payload):
return BeautifulSoup(test_site_1,'html.parser')
# This one the one with two links
async def mock_get_site_soup_2(payload):
return BeautifulSoup(test_site_2,'html.parser')
# We set the one link first
monkeypatch.setattr(services, "get_site_soup", mock_get_site_soup_1)
# Request the scraping to generate the corresponding log
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
# Patch again the soup function to get more links this time in the website
monkeypatch.setattr(services, "get_site_soup", mock_get_site_soup_2)
# Request crawl
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
# Parse response
response_dict = response.json()
# Check if everything went right and the analysis is correct
assert response.status_code == 200
# One link difference (the site has one more link than last time. If it was negative then it means it lost one)
assert response_dict['amount_difference'] == 1
# Check that the first request was done no longer than a second ago, cose it could be comparing against a differente request
# which is wrong. We always want to compare with the last one done in this case. (This could change if we would like to make a more
# complicated comparison function or some report of changes over time, eg.)
assert response_dict['last_request_date'] != None
last_request_date = datetime.strptime(response_dict['last_request_date'], "%Y-%m-%dT%H:%M:%S.%f")
assert (last_request_date-datetime.now()).total_seconds() > -1
def test_no_reports(test_app,monkeypatch):
"""
This tests goes through the process of requesting a website that hasn't been crawl before
and verifies that the amount_difference and last_request_date are Null, which means there is no previous crawl stored.
This works because the testing modules drops and recreates the database everytime.
For a production enviroment this should be changed and test should use a different database.
"""
test_request_payload = {"url": "https://firstlinksite.com" }
test_site = """
<html><head><title>The Dormouse's story</title></head>
<body>
<a href="http://example.com/" class="example" id="link1">Example</a>
</body>
"""
# This mock function will return the one link site
async def mock_get_site_soup(payload):
return BeautifulSoup(test_site,'html.parser')
# We set the one link first
monkeypatch.setattr(services, "get_site_soup", mock_get_site_soup)
# Request the scraping to generate the corresponding log
response = test_app.post("/scraping/", data=json.dumps(test_request_payload),)
response_dict = response.json()
# Check if everything went right and the analysis is correct
assert response.status_code == 200
assert response_dict['amount_difference'] == None
assert response_dict['last_request_date'] == None<file_sep># BIGGEST TODO EVER: LIMPIAR ESTE MONSTRUO QUE ANDA
from app.api import services
from app.db import engine, database, metadata
import sys, getopt
import asyncio
import argparse
async def perform_crawling(url : str, verbose : bool = False):
"""
Performs the actual crawling and prints the corresponding results to console.
Supports verbose version with some reports but is disabled by default.
"""
report = await services.handle_scraping_request(url)
if verbose:
print("Scraping terminado para \""+report.url+"\" ")
print(report.info)
print("Links encontrados (sin repetidos y en ningún orden en particular):")
for link in report.links:
print(link)
def main(url, verbose):
# The reason we need to use asyncio and handle this akwardly is
# to be able to reuse all the async code that was written for the API.
loop = asyncio.get_event_loop()
# Connect to db
loop.run_until_complete(database.connect())
# Crawl
loop.run_until_complete(perform_crawling(url, verbose))
# Disconnect from database on shutdown
loop.run_until_complete(database.disconnect())
if __name__ == "__main__":
# Parse arguments first, then call main function
parser = argparse.ArgumentParser(description='Extraer todos los links contenidos en un sitio. \nPara almacenar en .csv o .txt puede utilizar el comando "python get_links.py URL > links.csv". \nPara un análisis sencillo utilize la opción -V.')
parser.add_argument('-V', action='store_true',
help='Verbose. Si este parametro esta presente imprime un reporte.')
parser.add_argument('url', help='URL del sitio a parsear.')
args_parsed = parser.parse_args()
main(args_parsed.url, args_parsed.V)
<file_sep>from fastapi import HTTPException
from app.api.models import CrawlRequest, CrawlResponse, CrawlLogSchema
from app.db import database, crawl_logs
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
from urllib.error import HTTPError
from typing import List
from datetime import datetime
async def handle_scraping_request(url : str) -> CrawlResponse:
# Fetch all links from site
links = await fetch_links(url)
amount_of_links = len(links)
# Fetch las request before loggin this one
log_before = await get_last_log(url)
# Save log of crawl
await store_scraping_log(url, amount_of_links)
# Compare to previous log to see if anything has changed!
if log_before:
amount_difference = amount_of_links - log_before.amount_of_links
last_request_date = log_before.date
info = await generate_report(amount_difference, last_request_date, amount_of_links)
return CrawlResponse(url=url, links=links, info=info, amount_difference=amount_difference, last_request_date=last_request_date)
else:
info = "Primera vez que se procesa este sitio."
return CrawlResponse(url=url , links=links, info=info)
async def fetch_links(url: str) -> List[str]:
"""
Given a certain URL, retrieves a list of all the links contained
in that site without repetition
:param url: URL of the site to search
:return: Returns a list of strings representing all links found in the site
"""
# Fetch BeatifulSoup object for this site
soup = await get_site_soup(url)
# Get all links for this parsed site
links = await get_links(soup)
return links
async def get_site_soup(url : str) -> BeautifulSoup:
"""
Given a certain URL, generates the BeautifulSoup object to represent it by parsing the site's HTML.
Can throw different HTTPExceptions if it founds invalid addresses or broken sites.
:param url: URL of the site to parse
:return: BeautifulSoup object representing the parsed website
"""
try:
req = Request(url)
except ValueError:
# In case that the URL is not valid or there is any error
# while constructing the request, let the final user know
raise HTTPException(status_code=404, detail="HTTP Error 404: Invalid URL detected.")
try:
# Fetch HTML site
html_page = urlopen(req)
except HTTPError:
raise HTTPException(status_code=403, detail="HTTP Error 403: Forbidden. Check that the URL is valid and the site is accessible.")
# Return BeautifulSoup object
return BeautifulSoup(html_page, "lxml")
async def get_links(soup : BeautifulSoup) -> List[str]:
"""
Given a parsed site in BeautifulSoup format, returns a List of links found inside
:param soup: Parsed site
:return: List of strings represeting all distinct links in a website
"""
# Use a set to ignore repetitions efficiently
links = set()
# Fetch all <a> objects in the site
for link_item in soup.findAll('a'):
# Get link
link = link_item.get('href')
links.add(link)
# Switch back to list to mantain consistency with the rest of the program
links = list(links)
return links
async def generate_report(amount_difference : int, last_request_date : datetime, total_amount : int) -> str:
"""
This function generates an automatic comment in Spanish refering to the changes in the amount of links
contained in the same website in two different snapshots. It does not report if the links in fact changed or are the same,
only the difference in the total amount of distinct links found in the website in two different times,
:param ammount_difference: integer that represents the difference in total amount of links between the two crawls
:return: String containing a report in spanish of the difference
"""
# Simple way of creating a report according to difference in amount of links
if amount_difference > 0:
return "El sitio tiene " + str(amount_difference) + " links más en total que la última vez que se revisó ("+ str(total_amount) +"), el " + datetime.strftime(last_request_date, "%d/%m/%Y") + "."
elif amount_difference < 0:
return "El sitio tiene " + str(amount_difference) + " links menos en total que la última vez que se revisó ("+ str(total_amount) +"), el " + datetime.strftime(last_request_date, "%d/%m/%Y") + "."
return "El sitio tiene la misma cantidad de links que la última vez que se revisó ("+ str(total_amount) +"), el " + datetime.strftime(last_request_date, "%d/%m/%Y") + "."
async def store_scraping_log(url : str, amount_of_links : int) -> int:
"""
Stores a Log for the scraping of the website with the current datetime, the url crawled and the amount of links found
This function could be extended to store the actual links if necessary and generate further comparisons and reports.
Returns the id of the object stored, but it can be ignored.
"""
query = crawl_logs.insert().values(url=url, amount_of_links=amount_of_links, date=datetime.now())
return await database.execute(query=query)
async def get_last_log(url: str) -> CrawlLogSchema:
"""
Fetches the last crawl log for the given url. If it doesn't exists returns None,
else returns a pydantic model object containing the relevant info
"""
query = crawl_logs.select().where(crawl_logs.c.url == url).order_by(crawl_logs.c.date.desc())
last = await database.fetch_one(query=query)
if not last:
return None
else:
return CrawlLogSchema(url=last['url'],date=last['date'],amount_of_links=last['amount_of_links'])
<file_sep>import os
from sqlalchemy import Column, DateTime, Integer, MetaData, SmallInteger, Table, Text, create_engine
from sqlalchemy.sql import func
from databases import Database
import os
DATABASE_URL = os.getenv("DATABASE_URL")
# SQLAlchemy setup
engine = create_engine(DATABASE_URL)
metadata = MetaData()
# Crawl logs
crawl_logs = Table(
"crawl_logs",
metadata,
Column("id", Integer, primary_key=True),
Column("date", DateTime, default=func.now(), nullable=False, index=True),
Column("url", Text, index=True),
Column("amount_of_links", Integer),
)
metadata.create_all(engine)
# databases query builder
database = Database(DATABASE_URL)
<file_sep>"""
Simple models to represent the relevant info provided and
generated by the API and make any suitable validations.
"""
from datetime import datetime
from pydantic import BaseModel, ValidationError, validator
from typing import List, Optional
from fastapi import HTTPException
class CrawlLogSchema(BaseModel):
"""
This information is whats gonna be stored in the database,
this model must be in accordance with the crawl_logs Table of the database.
"""
url: str
amount_of_links: int
date: datetime
class CrawlRequest(BaseModel):
"""
Payload expected when a request is given to crawl a website and get the links
"""
url: str
@validator('url')
def url_cant_be_empty(cls, url):
if not url or len(url) == 0:
raise HTTPException(status_code=404, detail="Invalid URL. Please verify the parameter 'url' is set in the POST body.")
return url
class CrawlResponse(CrawlRequest):
"""
Response generated to the Crawl Request. Adds all relevant info
"""
links: List[str]
last_request_date: Optional[datetime]
amount_difference: Optional[int]
info: Optional[str]
<file_sep>from typing import Dict
from fastapi import APIRouter, HTTPException
from app.api import services
from app.api.models import CrawlResponse, CrawlRequest
from typing import Dict
from datetime import datetime
# This endpoints router
router = APIRouter()
@router.post("/scraping/", response_model=CrawlResponse)
async def get_links_on_website(payload : CrawlRequest):
url = payload.url
return await services.handle_scraping_request(url)
<file_sep>from fastapi import FastAPI
from app.api import endpoints
from app.db import database
def create_app():
# Fast API app
app = FastAPI()
# Connect to database on startup
@app.on_event("startup")
async def startup():
await database.connect()
# Disconnect from database on shutdown
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
# Include all endpoints
app.include_router(endpoints.router, prefix="", tags=["main"])
return app
app = create_app()<file_sep>"""
Sets up the test modules and configuration
"""
import pytest
# Starlette test client
from fastapi.testclient import TestClient
# Fetch App
from app.main import app
from app.db import metadata, engine
@pytest.fixture(scope="module")
def test_app():
# WARNING! This should not be used in production environment.
# In case of real world application use a separate database (even full separate enviroment) for testing
metadata.drop_all(engine)
metadata.create_all(engine)
with TestClient(app) as client:
yield client # testing happens here | 999f883b0bbaf4caa878f660a53e310e5404abd4 | [
"Markdown",
"Python"
]
| 9 | Markdown | joacosaralegui/ejercicio-web-scraping | 7fc87eaaf4d0767733d4447a30d2cf6f3d50a582 | 880d7438736496cf6f0f2e8712657fc4c22564eb |
refs/heads/master | <repo_name>BrynjarUlriksen/BrynjarUlriksen.github.io<file_sep>/sketch.js
// Screens
const LOADING = 0;
const MAIN_MENU = 1;
const PLAYLOAD = 2;
const PLAY = 3;
const HIGH_SCORE = 4;
const SETTINGS = 5;
const TESTINGSCREEN = 6;
let currentScreen = TESTINGSCREEN;
let currentButton;
//loading
let loadingCounter = 0;
let s = "BSU productions presents";
let newPoint = true;
let intro;
let wait = 0;
let waitCount = false;
// test
let testingFirst = true;
//pictures
let imgBackground;
let logo;
let startNew;
let startNewH;
let highScores;
let highScoresH;
let settings;
let settingsH;
let shipImg;
let ShipRezised;
let shipBullet;
let enemy;
let life;
let gameoverImg;
let playAgain;
let yesH;
let yes;
let no;
let noH;
let main_menubtn;
//sounds
let shootingSound;
let destroyedSound;
let gameoverSound;
let introSound;
let vol = 1;
let mute = false;
// PLAYLOAD
let sinus = 0;
let logoSpeed = 0;
//Sprites
let ship;
let moveX;
let enemies;
let bullets;
//constraints
let xConstrainMin;
let xConstrainMax;
// play
let wave = 1;
let score = 000;
let allDead = true;
let opacityText = 300;
let shotsUsed = 0;
let enemiesDead = 0;
let perfectScore = 100;
let scoreForEnemies = 100;
let lifes = 3;
let gameover = false;
let first = true;
//highscores
let database;
let name = "PLAYER 1";
let scoreSaved = 0;
let percentageSaved = 0;
let highscoreArray = [];
let highscoreArraySorted = [];
let scoreArray =[];
let string = "";
let pressingVar = true;
// setting
let testingFirstSetting = true;
function preload() {
introSound = loadSound("sounds/montypythonsound.mp3");
intro = createVideo('videoes/Clip.MP4');
database = loadJSON("data.json");
// images
imgBackground = loadImage("images/backgroundpng.png");
logo = loadImage("images/galagaPng.png");
}
function setup() {
// put setup code here
frameRate(60);
createCanvas(windowWidth, windowHeight-5);
currentButton = 0;
currentButton = constrain(currentButton, 0, 2);
bullets = new Group;
enemies = new Group;
xConstrainMax = width/ 1.5;
xConstrainMin = width/4;
intro.play();
noCursor();
// sounds
shootingSound = loadSound("sounds/laser_fastshot.wav");
destroyedSound = loadSound("sounds/fighter_destroyed.wav");
gameoverSound = loadSound("sounds/captured_ship_destroyed.wav");
// images
startNew = loadImage("images/startNewGame.png");
startNewH = loadImage("images/startNewGameHighlighted.png");
highScores = loadImage("images/highscores.png");
highScoresH = loadImage("images/highscoresHighlighted.png");
settings = loadImage("images/settings.png");
settingsH = loadImage("images/settingsHighlighted.png");
shipImg = loadImage("images/galagaShip.png");
shipBullet = loadImage("images/galagaShot.png");
enemy = loadImage("images/enemy.png");
life = loadImage("images/life.png");
gameoverImg = loadImage("images/gameoverLarge.jpg");
playAgain = loadImage("images/playagain.png");
yesH = loadImage("images/yesH.png");
yes = loadImage("images/yes.png");
noH = loadImage("images/noH.png");
no = loadImage("images/no.png");
main_menubtn = loadImage("images/main_menubtn.png");
//videos
intro.hide();
ShipRezised = shipImg//.resize(20, 20);
// spirtes
moveX =width/2 -50;
ship = createSprite(moveX, height - 100, 40,40);
ship.addImage(ShipRezised);
//Setting up highscore system
for(let i = 0; i < database.highScores.length;i++){
highscoreArray.push([database.highScores[i].score, database.highScores[i].name, database.highScores[i].percentage]);
scoreArray.push(database.highScores[i].score);
}
}
function draw() {
// switching between screens
switch (currentScreen) {
case TESTINGSCREEN:
drawtestingScreen();
break;
case LOADING:
drawLoadingScreen();
break;
case(MAIN_MENU):
drawMainMenuScreen();
break;
case(PLAYLOAD):
drawPlayLoadScreen();
break;
case (PLAY):
drawPlayScreen();
break;
case(HIGH_SCORE):
drawHighScoreScreen();
break;
case(SETTINGS):
drawSettingsScreen();
break;
default:
break;
}
}
// screen to comply with googles no autoplay without interaction
function drawtestingScreen(){
background(0,0,0);
image(imgBackground, 0, 0, width, height);
stroke(255, 255, 255);
textSize(40);
fill("white");
text("space to play", width/2- 100, height/2);
}
// loadingscreen
function drawLoadingScreen(){
background(0,0,0);
image(imgBackground, 0, 0, width, height);
image(intro, 0, 0, width, height);
image(logo, width/2 -300, height/5, 500, 200);
if(first){
if(!mute){introSound.play();}
for(let i = 0; i < 10; i++){intro.play();}
first = false;
}
fill(50);
textSize(32);
loadingCounter = constrain(loadingCounter, 0, 100);
if((frameCount % 8 == 0 && loadingCounter <100) && !waitCount){loadingCounter++};
text("Loading " + loadingCounter +"%", width/2-140, height/2 + 50);
text(s, width/2-290 - loadingCounter/2, height/2 -220);
if((loadingCounter === 10 || loadingCounter === 40 || loadingCounter === 70)&& newPoint == true ){
s += ".";
newPoint = false;
}
if(loadingCounter === 11 || loadingCounter === 41 || loadingCounter === 71 ){
newPoint = true;
}
if (loadingCounter == 100){
waitCount = true;
}
if(waitCount == true){
wait++;
}
if (wait > 100){
loadingCounter = 0;
currentScreen = MAIN_MENU;
}
}
// mainmenuscreen with different buttons showing highlighted
function drawMainMenuScreen(){
testingFirstSetting = true;
vol -= 0.1;
vol = constrain(vol, 0, 1);
introSound.setVolume(0, 2, 0);
background(0,0,0);
image(imgBackground, 0, 0, width, height);
image(logo, width/2 -300, height/15 -10, 500, 200);
if(currentButton == 0){
image(startNewH, width/2-150, height/3, 200,100);
image(highScores, width/2-150, height/3 +110, 200,100);
image(settings, width/2-150, height/3 + 220, 200,100);
}
else if(currentButton == 1){
image(startNew, width/2-150, height/3, 200,100);
image(highScoresH, width/2-150, height/3 +110, 200,100);
image(settings, width/2-150, height/3 + 220, 200,100);
}
else if(currentButton == 2){
image(startNew, width/2-150, height/3, 200,100);
image(highScores, width/2-150, height/3 +110, 200,100);
image(settingsH, width/2-150, height/3 + 220, 200,100);
}
}
// interaction function
function keyPressed(){
if(currentScreen == MAIN_MENU){
if(keyCode == ENTER ){
changeHiglight(currentButton);
}
else if (keyCode == 0 || keyCode == 32){
changeHiglight(currentButton);
}
else if(keyCode == UP_ARROW){
currentButton--;
currentButton = constrain(currentButton, 0,2);
}
else if (keyCode == DOWN_ARROW) {
currentButton++;
currentButton = constrain(currentButton, 0,2);
}
}
if(currentScreen == PLAY){
if(keyCode == 32){
let shot = createSprite(moveX, height -100);
shot.addImage(shipBullet);
shot.addSpeed(4, 270);
shot.scale = 1;
bullets.add(shot);
shotsUsed++;
shootingSound.play();
shootingSound.setVolume(0.2);
score -= 10;
score = constrain(score, 0, 9999999);
}/*
if(keyCode == RIGHT_ARROW){
moveX++;
}*/
if(gameover ){
if(keyCode == ENTER ){
resettOrNah(currentButton);
}
if(keyCode == 0 || keyCode == 32){
resettOrNah(currentButton);
}
if(keyCode == LEFT_ARROW){
currentButton--;
currentButton = constrain(currentButton, 0,1);
}
if (keyCode == RIGHT_ARROW) {
currentButton++;
currentButton = constrain(currentButton, 0,1);
}
}
}
else if(currentScreen == HIGH_SCORE){
if( (keyCode == 32|| keyCode == ENTER) && !first){
currentScreen = MAIN_MENU;
first = true;
pressingVar = true; // testing3
}
}
else if(currentScreen == TESTINGSCREEN){
if(keyCode == ENTER && testingFirst){
testingFirst = false;
currentScreen = LOADING;
}
else if ((keyCode == 0 || keyCode == 32) && testingFirst){
testingFirst = false;
currentScreen = LOADING;
}
}
else if(currentScreen == SETTINGS){
if(keyCode == ENTER && testingFirstSetting){
testingFirstSetting = false;
currentScreen = MAIN_MENU;
}
else if ((keyCode == 0 || keyCode == 32) && testingFirst){
testingFirst = false;
currentScreen = LOADING;
}
}
}
// changescreen function
function changeHiglight(condition) {
switch (condition) {
case 0:
currentScreen = PLAYLOAD;
break;
case 1:
currentScreen = HIGH_SCORE;
break;
case 2:
currentScreen = SETTINGS;
break;
}
}
// screen where menu rolls up screen
function drawPlayLoadScreen() {
background(0,0,0);
image(imgBackground, 0, 0, width, height);
image(logo, width/2 -300, height/15 + (sin(sinus/20) * 30) - logoSpeed -10, 500, 200);
image(startNewH, width/2-150, height/3 + (sin(sinus/20) * 30) - logoSpeed, 200,100);
image(highScores, width/2-150, height/3 +110 + (sin(sinus/20) * 30) - logoSpeed, 200,100);
image(settings, width/2-150, height/3 + 220 + (sin(sinus/20) * 30) - logoSpeed, 200,100);
if(sinus < 60){
sinus++;
sinus = constrain(sinus, 0 , 60);
}
else{
logoSpeed += 2 + loadingCounter/7;
loadingCounter++;
}
if(loadingCounter > 100){
currentScreen = PLAY;
}
}
//game screen
function drawPlayScreen(){
background(0,0,0);
image(imgBackground, 0, 0, width, height);
if(!gameover){
ship.position.x = moveX;
stroke(255,255,255);
line(width/4, 0, width/4, height);
line(width/1.5, 0, width/1.5, height);
createEnemies();
drawSprites();
checkBullets();
writeText(score, allDead);
enemiesArriving();
drawLife(lifes);
}
else{
gameOver()
}
if(keyIsDown(LEFT_ARROW)){
moveX-=5;
moveX = constrain(moveX, width/4 + 27, width/1.5 - 27);
}
if(keyIsDown(RIGHT_ARROW)){
moveX+= 5;
moveX = constrain(moveX, width/4 + 27, width/1.5 - 30);
}
}
// highscorescreen
function drawHighScoreScreen(){
background(0,0,0);
image(imgBackground, 0, 0, width, height);
stroke(255, 0, 0, 300);
fill(255, 0, 0, 300);
textSize(100);
image(main_menubtn, width/2 - 100, height- 100, 100, 100);
text("HIGH SCORES", width/4, 100);
let string = "";
if(pressingVar){
// adding player score if existing
if(scoreSaved > 0){
highscoreArray.push([scoreSaved,name, percentageSaved ]);
scoreArray.push(scoreSaved);
print(scoreSaved, name, percentageSaved);
print(highscoreArray);
scoreSaved = 0;
}
}
//sorting score
highscoreArraySorted = [];
scoreArray.sort(function(a,b){return b-a});
for(let i= 0; i < scoreArray.length; i++){
for(let j = 0; j < scoreArray.length; j++){
if(scoreArray[i]== highscoreArray[j][0]){
highscoreArraySorted.push(highscoreArray[j]);
}
}
first = false;
pressingVar = false;
}
// showingscore
for(let i = 0; i < highscoreArraySorted.length; i ++){
let fill1 = 255 - i*10;
fill(fill1, fill1, 0, 300);
stroke(255-i*10, 0, 0, 300);
textSize(40-i*2);
string = "" + highscoreArraySorted[i][1] + ": " + highscoreArraySorted[i][0] + ", " + highscoreArraySorted[i][2] + "%";
if( 100 +(i+1)*90 < height -100){text(string, width/4, 100 +(i+1)*90);
}
}
}
//drawing a basic settings screen, only for instruction purposes
function drawSettingsScreen(){
background(0,0,0);
image(imgBackground, 0, 0, width, height);
fill("white");
stroke("white");
textSize(40);
text("use arrows and space/ enter to navigate", width/2 - 200, height/2);
}
// creating a random number of enemies times the wavecount when round is complete
function createEnemies(){
let randNr = random(1 * wave, 5 * wave);
let heightHere = -300;
let multiplier = 70;
let j = 0;
if(allDead){
for(let i = 0; i < randNr; i++){
if(xConstrainMin + j*multiplier + 50 >= xConstrainMax){heightHere -= 100; j = 0}
let enemyShip = createSprite(xConstrainMin + j*multiplier + 40, heightHere);
enemyShip.addImage(enemy);
enemyShip.scale = 0.2;
enemies.add(enemyShip);
j++;
}
wave++;
allDead = false;
}
}
// checking if bullet hits enemies
function checkBullets() {
let bullet1 = 0;
for (let index = 0; index < bullets.size(); index++) {
let bullet = bullets.get(index);
if(bullet.position.y < 0){
bullet.remove();
}
if(bullet.overlap(enemies)){
bullet1 = bullet;
}
}
for (let index = 0; index < enemies.size(); index++) {
let enemyCheck = enemies.get(index);
if(enemyCheck.overlap(bullets)){
enemyCheck.remove();
destroyedSound.play();
destroyedSound.setVolume(0.2);
if(bullet1 != 0){
bullet1.remove();
}
enemiesDead++;
if(!(enemiesDead == 0 && shotsUsed == 0)){perfectScore = (enemiesDead/shotsUsed) *100 ;}
perfectScore = round(perfectScore);
scoreForEnemies = 100 * perfectScore/100;
score += scoreForEnemies;
}
}
if(enemies.size() == 0){allDead = true}
}
// writes text on drawing screen
function writeText(score, newWave) {
fill(255,255,255);
textSize(40);
text("Your Score: ",xConstrainMax + 10, height/4- 50);
text(score, xConstrainMax + 10, height/4);
textSize(20);
text("Hit percentage: " + perfectScore + " %", xConstrainMax + 10, height/4 + 50);
let waveShown = wave -1;
if(newWave){opacityText =300}
fill(255,255,255, opacityText);
stroke(255, 255, 255, opacityText);
textSize(40);
text("wave " + waveShown + ". Get ready...", (xConstrainMin + xConstrainMax)/3, height/2);
opacityText--;
}
// checks if new enemies should arrive as well as if the enemies reach the bottom or the player dies
function enemiesArriving(){
let stopSignal = 0;
for(let i = 0; i < enemies.size(); i++){
stopSignal = enemies.get(i);
stopSignal.position.y += 1;
if (stopSignal.position.y >= height){
stopSignal.remove();
lifes--;
if(lifes <= 0){
gameover = true;
}
}
}
}
// draws number of lives
function drawLife(lifes) {
for(let i = 0; i < lifes; i++){
image(life, xConstrainMax + 10 + i * 40, height/1.5, 40, 40);
}
}
// runs when the user looses all lives
function gameOver(){
for(let i = 0; i < enemies.size(); i++){
let enemy1 = enemies.get(i);
enemy1.remove();
}
image(gameoverImg, 0, 0, width, height);
image(playAgain, width/2 - 150, height/1.5, 300, 100);
if(first){
gameoverSound.play();
first = false;
for(let i = 0; i < enemies.size(); i++){
let enemy1 = enemies.get(i);
enemy1.remove();
}
}
if(currentButton == 1){
image(yes, width/2 - 100, height/1.5 + 100, 70, 70);
image(noH, width/2 , height/1.5 + 100, 70, 70);
}
else{
image(yesH, width/2 - 100, height/1.5 + 100, 70, 70);
image(no, width/2 , height/1.5 + 100, 70, 70);
}
}
// runs based on what the user wants to do when it looses all lives
function resettOrNah(currentButton) {
if(currentButton == 1){
scoreSaved = score;
percentageSaved = scoreForEnemies;
gameover = false;
wave = 1;
score = 000;
allDead = true;
opacityText = 300;
shotsUsed = 0;
enemiesDead = 0;
perfectScore = 100;
scoreForEnemies = 100;
lifes = 3;
first = true;
currentScreen = HIGH_SCORE;
}
else if (currentButton == 0){
for(let i = 0; i < enemies.size(); i++){
let enemy1 = enemies.get(i);
enemy1.remove();
}
gameover = false;
wave = 1;
score = 000;
allDead = true;
opacityText = 300;
shotsUsed = 0;
enemiesDead = 0;
perfectScore = 100;
scoreForEnemies = 100;
lifes = 3;
first = true;
currentScreen = MAIN_MENU;
currentScreen = PLAY;
}
} | deea70aa972cef0379485963cbc85300634d1f03 | [
"JavaScript"
]
| 1 | JavaScript | BrynjarUlriksen/BrynjarUlriksen.github.io | c4d680acb0dc4708b2acc40e7cfbeddbd57fa256 | 9b02a07271c13ca68f88adc784a428a0c71682bd |
refs/heads/master | <repo_name>jim-lightfoot/MondoCore-MongoDB<file_sep>/MondoCore.MongoDB/MongoCollectionReader.cs
/***************************************************************************
*
* The MondoCore Libraries
*
* Namespace: MondoCore.MongoDB
* File: MongoCollectionReader.cs
* Class(es): MongoCollectionReader
* Purpose: IReadRepository implentation of MongoDB collection
*
* Original Author: <NAME>
* Creation Date: 28 Feb 2021
*
* Copyright (c) 2021 - <NAME>, All rights reserved
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MongoDB.Driver;
using MondoCore.Common;
using MondoCore.Data;
namespace MondoCore.MongoDB
{
internal class MongoCollectionReader<TID, TValue> : IReadRepository<TID, TValue> where TValue : IIdentifiable<TID>
{
private readonly IMongoCollection<TValue> _collection;
internal MongoCollectionReader(IMongoCollection<TValue> collection)
{
_collection = collection;
}
public async Task<long> Count(Expression<Func<TValue, bool>> query = null)
{
if(query == null)
return await _collection.EstimatedDocumentCountAsync();
return await _collection.CountDocumentsAsync(query);
}
#region IReadRepository
public async Task<TValue> Get(TID id)
{
var filter = Builders<TValue>.Filter.Eq( item=> item.Id, id );
var result = await _collection.Find(filter).FirstOrDefaultAsync();
if(result == null)
throw new NotFoundException();
return result;
}
public async IAsyncEnumerable<TValue> Get(IEnumerable<TID> ids)
{
var filter = Builders<TValue>.Filter.In( item=> item.Id, ids);
using(var cursor = await _collection.FindAsync(filter))
{
while(await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach(var document in batch)
{
yield return document;
}
}
}
}
public async IAsyncEnumerable<TValue> Get(Expression<Func<TValue, bool>> query)
{
var filter = Builders<TValue>.Filter.Where(query);
using(var cursor = await _collection.FindAsync(filter))
{
while(await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach(var document in batch)
{
yield return document;
}
}
}
}
#region IQueryable<>
#region IQueryable
public Type ElementType => typeof(TValue);
public Expression Expression => _collection.AsQueryable<TValue>().Expression;
public IQueryProvider Provider => _collection.AsQueryable<TValue>().Provider;
#endregion
#region IEnumerable<>
public IEnumerator<TValue> GetEnumerator() => _collection.AsQueryable<TValue>().GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
=> _collection.AsQueryable<TValue>().GetEnumerator();
#endregion
#endregion
#endregion
}
}
<file_sep>/MondoCore.MongoDB/MongoDB.cs
/***************************************************************************
*
* The MondoCore Libraries
*
* Namespace: MondoCore.MongoDB
* File: MongoDB.cs
* Class(es): MongoDB
* Purpose: Wrapper of MongoDB API using IRead/WriteRepository
*
* Original Author: <NAME>
* Creation Date: 28 Feb 2021
*
* Copyright (c) 2021 - <NAME>, All rights reserved
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MongoDB.Driver;
using MondoCore.Data;
namespace MondoCore.MongoDB
{
/// <summary>
/// Provides methods to access a MongoDB
/// </summary>
public class MongoDB : IDatabase
{
protected readonly IMongoDatabase _db;
public MongoDB(string dbName, string connectionString)
{
var client = new MongoClient(connectionString);
_db = client.GetDatabase(dbName);
}
/// <summary>
/// Create a repository reader for the MongoDB collection
/// </summary>
/// <typeparam name="TID">Type of the identifier</typeparam>
/// <typeparam name="TValue">Type of the value stored in the collection</typeparam>
/// <param name="repoName">Name of MongoDB collection</param>
/// <returns>A reader to make read operations</returns>
public IReadRepository<TID, TValue> GetRepositoryReader<TID, TValue>(string repoName, IIdentifierStrategy<TID> strategy = null) where TValue : IIdentifiable<TID>
{
var mongoCollection = _db.GetCollection<TValue>(repoName);
return new MongoCollectionReader<TID, TValue>(mongoCollection);
}
/// <summary>
/// Create a repository writer for the MongoDB collection
/// </summary>
/// <typeparam name="TID">Type of the identifier</typeparam>
/// <typeparam name="TValue">Type of the value stored in the collection</typeparam>
/// <param name="repoName">Name of MongoDB collection</param>
/// <returns>A writer to make writer operations</returns>
public IWriteRepository<TID, TValue> GetRepositoryWriter<TID, TValue>(string repoName, IIdentifierStrategy<TID> strategy = null) where TValue : IIdentifiable<TID>
{
var mongoCollection = _db.GetCollection<TValue>(repoName);
return new MongoCollectionWriter<TID, TValue>(mongoCollection);
}
}
}
<file_sep>/Tests/MondoCore.MongoDB.FunctionalTests/MongoCollection_ObjectId.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB = MondoCore.MongoDB;
using MondoCore.Common;
using MondoCore.Data;
using MondoCore.Repository.TestHelper;
using MondoCore.TestHelpers;
using MongoDB.Bson;
namespace MondoCore.MongoDB.FunctionalTests
{
[TestClass]
public class MongoCollection_ObjectIdTests : RepositoryTestBase<ObjectId>
{
public MongoCollection_ObjectIdTests() :
base(new MondoCore.MongoDB.MongoDB("functionaltests", TestConfiguration.Load().ConnectionString),
"cars2",
()=> ObjectId.GenerateNewId())
{
}
}
}
<file_sep>/Tests/MondoCore.MongoDB.FunctionalTests/ExtensionsObjectId.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB = MondoCore.MongoDB;
using MondoCore.Common;
using MondoCore.Data;
using MongoDB.Bson;
namespace MondoCore.MongoDB.FunctionalTests
{
[TestClass]
public class ExtensionsObjectIdTests
{
private const string ConnectionString = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false";
private IDatabase _db;
private IReadRepository<ObjectId, Person> _reader;
private IWriteRepository<ObjectId, Person> _writer;
public ExtensionsObjectIdTests()
{
_db = new MondoCore.MongoDB.MongoDB("functionaltests", ConnectionString);
_writer = _db.GetRepositoryWriter<ObjectId, Person>("persons");
_reader = _db.GetRepositoryReader<ObjectId, Person>("persons");
}
[TestInitialize]
public async Task MongoCollection_Initialize()
{
// await _writer.Delete( _=> true );
}
[TestCleanup]
public async Task MongoCollection_Cleanup()
{
// await _writer.Delete( _=> true );
}
[TestMethod]
public async Task MongoCollection_1000()
{
await CreateLargeDatabase(1000);
Assert.AreEqual(1000, _reader.Count());
var result = await _reader.Get( i=> i.Surname == "Brown").ToList();
Assert.AreNotEqual(0, result.Count());
}
[TestMethod]
public async Task MongoCollection_10000()
{
await CreateLargeDatabase(10000);
Assert.AreEqual(10000, _reader.Count());
var result = await _reader.Get( i=> i.Surname == "Brown").ToList();
Assert.AreNotEqual(0, result.Count());
}
[TestMethod]
public async Task MongoCollection_100000()
{
await CreateLargeDatabase(100000);
Assert.AreEqual(100000, _reader.Count());
var result = await _reader.Get( i=> i.Surname == "Brown").ToList();
Assert.AreNotEqual(0, result.Count());
}
[TestMethod]
public async Task MongoCollection_1000000()
{
await CreateLargeDatabase(1000000);
Assert.AreEqual(1000000, _reader.Count());
var result = await _reader.Get( i=> i.Surname == "Brown").ToList();
Assert.AreNotEqual(0, result.Count());
}
[TestMethod]
public async Task MongoCollection_Update()
{
var count = _reader.Count(i=> i.Surname == "Anderson");
await _writer.Update( new { Surname = "Anderson2" }, i=> i.Surname == "Anderson");
Assert.AreEqual(0, _reader.Count( i=> i.Surname == "Anderson") );
Assert.AreEqual(count, _reader.Count( i=> i.Surname == "Anderson2") );
}
#region Private
private async Task CreateLargeDatabase(int numItems = 100000)
{
await _writer.Delete( _=> true );
var list = new List<Person>();
for(int i = 0; i < numItems; ++i)
{
list.Add(CreateRandomPerson());
}
await _writer.Insert(list);
return;
}
#region Test Data
private Random _randomSurname = new Random();
private Random _randomMiddleName = new Random();
private Random _randomFirstName = new Random();
private Random _randomStreet = new Random();
private Random _randomCity = new Random();
private Random _randomState = new Random();
private Random _randomStreetNumber = new Random();
private Random _randomBirthdate = new Random();
private Random _randomZip = new Random();
private Person CreateRandomPerson()
{
var zip = _randomZip.Next(100000);
return new Person
{
Id = ObjectId.GenerateNewId(),
Surname = GetRandomValue(_randomSurname, _surnames),
FirstName = GetRandomValue(_randomFirstName, _givenName),
MiddleName = GetRandomValue(_randomMiddleName, _givenName),
Birthdate = (new DateTime(2002, 1, 1, 0, 0, 0)).AddDays(-(_randomBirthdate.Next(26000))).ToString("dd-MMM-yyyy"),
Addresses = new List<Address>
{
new Address
{
StreetNumber = (100 + _randomStreetNumber.Next(100000)).ToString(),
StreetName = GetRandomValue(_randomStreet, _streets),
City = GetRandomValue(_randomCity, _cities),
State = GetRandomValue(_randomState, _states),
ZipCode = zip.ToString().PadLeft(6, '0').Substring(1, 5)
},
new Address
{
StreetNumber = (100 + _randomStreetNumber.Next(100000)).ToString(),
StreetName = GetRandomValue(_randomStreet, _streets),
City = GetRandomValue(_randomCity, _cities),
State = GetRandomValue(_randomState, _states),
ZipCode = zip.ToString().PadLeft(6, '0').Substring(1, 5)
}
}
};
}
private string GetRandomValue(Random random, string[] names)
{
return names[random.Next(names.Length)];
}
public class Person : IIdentifiable<ObjectId>
{
public ObjectId Id { get;set; }
public string Surname { get;set; }
public string FirstName { get;set; }
public string MiddleName { get;set; }
public string Birthdate { get;set; }
public List<Address> Addresses { get;set; } = new List<Address>();
}
public class Address
{
public string StreetNumber { get;set; }
public string StreetName { get;set; }
public string City { get;set; }
public string State { get;set; }
public string ZipCode { get;set; }
}
#region Surnames
private static string[] _surnames = new string[]
{
"Smith", "Jones", "Anderson", "Johnson",
"Taylor", "Jordan", "Franklin", "Washington",
"Madison", "Monroe", "Benson", "Harris",
"Boyle", "Lincoln", "Clinton", "Carpenter",
"Collins", "Davis", "Alexander", "Allen",
"Davidson", "Porter", "Griffin", "Griffith",
"Marshall", "Moore", "Weldy", "Perkins",
"Strauss", "Palmer", "Sullivan", "Stone",
"Warner", "Nelson", "Miller", "Baldwin",
"Simon", "Wright", "Watson", "Holmes",
"Chandler", "Fuller", "Sheldon", "Field",
"McCormick", "Wolfe", "Blair", "Butler",
"Cooper", "Norris", "Page", "Cohen",
"Wilson", "Holden", "Douglas", "Bennet",
"Adams", "James", "Green", "White",
"Black", "Brown", "King", "Rey",
"Reed", "Scott", "Shephard", "Long",
"Anthony", "Williams", "Lee", "Clark",
"Grant", "Harrison", "Henry", "Wentworth",
"Flintstone", "Alvarez", "Sanchez", "Martinez",
"Rodriguez", "Gonzales", "Hernandez", "Romero",
"Chavez", "Vasquez", "Morales", "Velasquez",
"Valdes", "Cortez", "Gomez", "Ortega",
"Garcia", "Ruiz", "Reyes", "Lopez",
"Trevino", "Orloff", "Stein", "Nguyen",
"Trinh", "Wang", "Wong", "Wu",
"Jin", "Chen", "Tang", "Chao",
"Ping", "Chu", "Chang", "Yang",
"Lombardo", "Yamamoto", "Matsumoto", "Nakashima",
"Nomura", "Okamura", "Zhukov", "Kornilov",
"Lazarev", "Komarov", "Popovich", "Chorloff"
};
#endregion
#region Given Names
private static string[] _givenName = new string[]
{
"Oliver", "Archer", "Adrian", "Daniel",
"Liam", "Lucas", "Elias", "Nathaniel",
"Ethan", "Noah", "Samuel", "Ezra",
"Aiden", "Harrison", "Arthur", "Beau",
"Gabriel", "Hudson", "Gideon", "Zachary",
"Caleb", "Felix", "Kaden", "Tobias",
"Theodore", "Elliott", "Arlo", "Carter",
"Declan", "Jacob", "James", "Matthew",
"Owen", "Atticus", "Adam", "Ian",
"Elijah", "Lincoln", "Colton", "Ezekiel",
"Henry", "Gavin", "Ronan", "Aaron",
"Jackson", "Dominic", "Roman", "Thomas",
"Grayson", "Jack", "Asher", "Xander",
"Levi", "Atlas", "Nolan", "Soren",
"Benjamin", "Isaac", "Jonah", "Oscar",
"Finn", "Logan", "Rhys", "Callum",
"Miles", "Wyatt", "Nathan", "Nicholas",
"Alexander", "Silas", "Axel", "Ace",
"Sebastian", "Cole", "August", "Josiah",
"Leo", "Theo", "Connor", "Michael",
"Landon", "Holden", "Xavier", "Vincent",
"Emmett", "Luke", "Charles", "Edward",
"Everett", "William", "Lachlan", "Chase",
"Milo", "Isaiah", "Apollo", "David",
"Jasper", "Eli", "Jace", "Malachi",
"Charlotte", "Ivy", "Naomi", "Arabella",
"Ava", "Ella", "Zoey", "Athena",
"Amelia", "Eleanor", "Aaliyah", "Maya",
"Olivia", "Audrey", "Elizabeth", "Saoirse",
"Aurora", "Genevieve", "Evangeline", "Zoe",
"Violet", "Iris", "Autumn", "Sienna",
"Luna", "Isabella", "Esme", "Evelyn",
"Hazel", "Lucy", "Mia", "Rose",
"Chloe", "Ophelia", "Daisy", "Harper",
"Aria/Arya", "Eloise", "Ruby", "Josephine",
"Scarlett", "Vivian", "Margot", "Felicity",
"Isla", "Lorelei", "Layla", "Delilah",
"Abigail", "Wren", "Anastasia", "Amaya",
"Freya", "Hannah", "Sadie", "Caroline",
"Adeline", "Clara", "Stella", "Olive",
"Sophia", "Lydia", "Lila", "Adalyn",
"Nora", "Madeleine", "Rosalie", "Brielle",
"Adelaide", "Claire", "Daphne", "Matilda",
"Emma", "Astrid", "Fiona", "Aurelia",
"Mila", "Thea", "Phoebe", "Willow",
"Lily", "Kaia", "Savannah", "Natalie",
"Grace", "Cora", "Alice", "Leilani",
"Maeve", "Penelope", "Eliana", "Ada",
"Eliza", "Elena", "Gemma", "Mabel",
"Emily", "Isabelle", "Nadia", "Amara"
};
#endregion
#region Cities
private static string[] _cities = new string[]
{
"New York", "Memphis", "Riverside", "Madison",
"Los Angeles", "Louisville", "<NAME>", "Lubbock",
"Chicago", "Baltimore", "Lexington", "Scottsdale",
"Houston", "Milwaukee", "Henderson", "Reno",
"Phoenix", "Albuquerque", "Stockton", "Buffalo",
"Philadelphia", "Tucson", "<NAME>", "Gilbert",
"San Antonio", "Fresno", "Cincinnati", "Glendale",
"San Diego", "Mesa", "St. Louis", "N Las Vegas",
"Dallas", "Sacramento", "Pittsburgh", "Winston–Salem",
"San Jose", "Atlanta", "Greensboro", "Chesapeake",
"Austin", "Kansas City", "Lincoln", "Norfolk",
"Jacksonville", "Colorado Springs", "Anchorage", "Fremont",
"Fort Worth", "Omaha", "Plano", "Garland",
"Columbus", "Raleigh", "Orlando", "Irving",
"Charlotte", "Miami", "Irvine", "Hialeah",
"San Francisco", "Long Beach", "Newark", "Richmond",
"Indianapolis", "Virginia Beach", "Durham", "Boise",
"Seattle", "Oakland", "Chula Vista", "Spokane",
"Denver", "Minneapolis", "Toledo", "Baton Rouge",
"Washington", "Tulsa", "Fort Wayne", "Tacoma",
"Boston", "Tampa", "St Petersburg", "San Bernardino",
"El Paso", "Arlington", "Modesto", "Overland Park",
"Nashville", "New Orleans", "Fontana", "Grand Prairie",
"Detroit", "Wichita", "Des Moines", "Tallahassee",
"Oklahoma City", "Bakersfield", "Moreno Valley", "Cape Coral",
"Portland", "Cleveland", "Santa Clarita", "Mobile",
"Las Vegas", "Aurora", "Fayetteville", "Knoxville",
"Anaheim", "Laredo", "Fort Collins", "Rockford",
"Honolulu", "Jersey City", "Corona", "Paterson",
"Santa Ana", "Chandler", "Springfield", "Savannah",
"Birmingham", "Shreveport", "Jackson", "Bridgeport",
"Oxnard", "Worcester", "Alexandria", "Torrance",
"Rochester", "Ontario", "Hayward", "McAllen",
"Port St. Lucie", "Vancouver", "Clarksville", "Syracuse",
"Grand Rapids", "Sioux Falls", "Lakewood", "Surprise",
"Huntsville", "Chattanooga", "Lancaster", "Denton",
"Salt Lake City", "Brownsville", "Salinas", "Roseville",
"Frisco", "Fort Lauderdale", "Palmdale", "Thornton",
"Yonkers", "Providence", "Hollywood", "Miramar",
"Amarillo", "Newport News", "Springfield", "Pasadena",
"Glendale", "<NAME>", "Macon", "Mesquite",
"Huntington Beach", "Santa Rosa", "Kansas City", "Olathe",
"McKinney", "Peoria", "Sunnyvale", "Dayton",
"Montgomery", "Oceanside", "Pomona", "Carrollton",
"Augusta", "Elk Grove", "Killeen", "Waco",
"Aurora", "Salem", "Escondido", "Orange",
"Akron", "Pembroke Pines", "Pasadena", "Fullerton",
"Little Rock", "Eugene", "Naperville", "Charleston",
"Tempe", "Garden Grove", "Bellevue", "W Valley",
"Columbus", "Cary", "Joliet", "Visalia",
"Murfreesboro", "Hampton", "Victorville", "Temecula",
"Midland", "Gainesville", "Clovis", "Gresham",
"Warren", "Hartford", "Springfield", "Lewisville",
"Coral Springs", "Vallejo", "Meridian", "Hillsboro",
"<NAME>", "Allentown", "Westminster", "Ventura",
"Round Rock", "Berkeley", "<NAME>", "Greeley",
"Sterling Heights", "Richardson", "High Point", "Inglewood",
"Kent", "Arvada", "Manchester", "Waterbury",
"Columbia", "<NAME>", "Pueblo", "League City",
"Santa Clara", "Rochester", "Lakeland", "Santa Maria",
"New Haven", "Cambridge", "Pompano Beach", "Tyler ",
"Stamford", "Sugar Land", "W Palm Beach", "Davie",
"Concord", "Lansing", "Antioch", "Lakewood",
"Elizabeth", "Evansville", "Everett", "Daly City",
"Athens", "College Station", "Downey", "Boulder",
"Thousand Oaks", "Fairfield", "Lowell", "Allen",
"Lafayette", "Clearwater", "Centennial", "W Covina",
"Simi Valley", "Beaumont", "Elgin", "Sparks",
"Topeka", "Independence", "Richmond", "Wichita",
"Norman", "Provo", "Peoria", "Green Bay",
"Fargo", "<NAME>", "Broken Arrow", "San Mateo",
"Wilmington", "Murrieta", "Miami Gardens", "Norwalk",
"Abilene", "Palm Bay", "Billings", "Rialto",
"Odessa", "El Monte", "Jurupa Valley", "Las Cruces",
"Columbia", "Carlsbad", "Sandy Springs", "Chico",
"Pearland", "Charleston", "El Cajon", "Tuscaloosa",
"Burbank", "Carmel", "S Bend", "Spokane Valley",
"Renton", "San Angelo", "Vista", "Vacaville",
"Davenport", "Clinton", "Edinburg", "Bend",
"Woodbridge", "Norton", "Fredericksburg", "Georgetown"
};
#endregion
#region States
private static string[] _states = new string[]
{
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY" };
#endregion
#region Streets
private static string[] _streets = new string[]
{
"Main St", "Church St", "Jackson St", "Park Place",
"Main St N", "Main St S", "Bridge St", "Locust St",
"Elm St", "High St", "Madison Ave", "Meadow Ln",
"Main St W", "Washington St", "Spruce St", "Grove St",
"Main St E", "Park Ave", "Ridge Rd", "5th St",
"2nd St", "Walnut St", "Pearl St", "Lincoln St",
"Chestnut St", "Maple Ave", "Madison St", "Dogwood Dr",
"Maple St", "Broad St", "Lincoln Ave", "Pennsylvania Ave",
"Oak St", "Center St", "Pleasant St", "4th St W",
"Pine St", "Pike St", "Adams St", "Hickory Ln",
"Wilshire Blvd", "Tampa Ave", "Route 1", "Jefferson Ave",
"Renton Ave", "River Rd", "Summit Ave", "3rd St W",
"Market St", "Water St", "Virginia Ave", "7th St",
"Union St", "South St", "12th St", "Academy St",
"Park St", "3rd St", "5th Ave", "11th St",
"Washington Ave", "Cherry St", "6th St", "2nd Ave",
"N St", "4th St", "9th St", "East St",
"Court St", "Highland Ave", "Charles St", "Green St",
"Mill St", "Franklin St", "Cherry Ln", "Elizabeth St",
"Prospect St", "School St", "Hill St", "Woodland Dr",
"Spring St", "Central Ave", "River St", "6th St W",
"1st St", "State St", "10th St", "Brookside Dr",
"Front St", "West St", "Colonial Dr", "Hillside Ave",
"Jefferson St", "Cedar St", "Monroe St", "Lake St",
"Valley Rd", "13th St", "5th St W", "Highland Dr",
"Winding Way", "4th Ave", "6th Ave", "Holly Dr",
"1st Ave", "5th St N", "Berkshire Dr", "King St",
"Fairway Dr", "College St", "Buckingham Dr", "Lafayette Ave",
"Liberty St", "Dogwood Ln", "Circle Dr", "Linden St",
"2nd St W", "Mill Rd", "Clinton St", "Mulberry St",
"3rd Ave", "7th Ave", "George St", "Poplar St",
"Broadway", "8th St", "Hillcrest Dr", "Ridge Ave",
"Church Rd", "Beech St", "Hillside Dr", "7th St E",
"Delaware Ave", "Division St", "Laurel St", "James St",
"Prospect Ave", "Harrison St", "Park Dr", "Magnolia Dr",
"Sunset Dr", "Heather Ln", "Penn St", "Myrtle Ave",
"Vine St", "Lakeview Dr", "Railroad Ave", "Shady Ln",
"Laurel Ln", "Creek Rd", "Riverside Dr", "Surrey Ln",
"New St", "Durham Rd", "Sherwood Dr", "Walnut Ave",
"Oak Ln", "Elm Ave", "Summit St", "Warren St",
"Primrose Ln", "Fairview Ave", "2nd St E", "Williams St",
"Railroad St", "Front St N", "6th St N", "Wood St",
"Willow St", "Grant St", "Cedar Ln", "Woodland Ave",
"4th St N", "Hamilton St", "Belmont Ave", "Denny Way",
"Cambridge Ct", "Alki Ave", "Cambridge Dr", "Edgewater Ln",
"Clark St", "Edgemont Pl", "College Ave", "Euclid Ave",
"Essex Ct", "Evanston St", "Franklin Ave", "Ranier Blvd",
"Hilltop Rd", "Evergreen Way", "Fremont Ave", "Fairview Dr"
};
#endregion
#endregion
#endregion
}
}
<file_sep>/README.md
# MondoCore-MongoDB
Wrapper of MongoDB API using interfaces from MondoCore
<file_sep>/Tests/MondoCore.MongoDB.FunctionalTests/MongoCollection.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB = MondoCore.MongoDB;
using MondoCore.Common;
using MondoCore.Data;
using MondoCore.TestHelpers;
using MondoCore.Repository.TestHelper;
namespace MondoCore.MongoDB.FunctionalTests
{
[TestClass]
public class MongoCollectionTests : RepositoryTestBase<Guid>
{
public MongoCollectionTests()
: base(new MondoCore.MongoDB.MongoDB("functionaltests", TestConfiguration.Load().ConnectionString),
"cars",
()=> Guid.NewGuid())
{
}
}
}
<file_sep>/MondoCore.MongoDB/MongoCollectionWriter.cs
/***************************************************************************
*
* The MondoCore Libraries
*
* Namespace: MondoCore.MongoDB
* File: MongoCollectionWriter.cs
* Class(es): MongoCollectionWriter
* Purpose: IWriterRepository implentation of MongoDB collection
*
* Original Author: <NAME>
* Creation Date: 28 Feb 2021
*
* Copyright (c) 2021 - <NAME>, All rights reserved
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using MongoDB.Driver;
using MondoCore.Common;
using MondoCore.Data;
namespace MondoCore.MongoDB
{
internal class MongoCollectionWriter<TID, TValue> : IWriteRepository<TID, TValue> where TValue : IIdentifiable<TID>
{
private readonly IMongoCollection<TValue> _collection;
internal MongoCollectionWriter(IMongoCollection<TValue> collection)
{
_collection = collection;
}
#region IWriteRepository
public async Task<bool> Delete(TID id)
{
var filter = Builders<TValue>.Filter.Eq(item => item.Id, id);
var result = await _collection.DeleteOneAsync(filter);
return result.DeletedCount == 1;
}
public async Task<long> Delete(Expression<Func<TValue, bool>> guard)
{
var filter = Builders<TValue>.Filter.Where(guard);
var result = await _collection.DeleteManyAsync(filter);
return result.DeletedCount;
}
public async Task<TValue> Insert(TValue item)
{
if(item.Id.Equals(default(TID)))
throw new ArgumentException("Item must have a valid id in order to add to collection");
var options = new InsertOneOptions { BypassDocumentValidation = true };
await _collection.InsertOneAsync(item, options);
return item;
}
public Task Insert(IEnumerable<TValue> items)
{
var options = new InsertManyOptions { BypassDocumentValidation = true };
return _collection.InsertManyAsync(items, options);
}
public async Task<bool> Update(TValue item, Expression<Func<TValue, bool>> guard = null)
{
var id = item.Id;
var filter = Builders<TValue>.Filter.Eq(obj => obj.Id, id);
if(guard != null)
filter = Builders<TValue>.Filter.And(filter, Builders<TValue>.Filter.Where(guard));
var result = await _collection.ReplaceOneAsync(filter, item);
return result.ModifiedCount > 0;
}
public async Task<long> Update(object properties, Expression<Func<TValue, bool>> query)
{
var props = properties.ToDictionary().ToList();
var numProps = props.Count;
if(numProps == 0)
return 0;
var updateDef = Builders<TValue>.Update.Set(props[0].Key, props[0].Value);
for(var i = 1; i < numProps; ++i)
{
var kv = props[i];
updateDef = updateDef.Set(kv.Key, kv.Value);
}
var filter = Builders<TValue>.Filter.Where(query);
var result = await _collection.UpdateManyAsync(filter, updateDef);
return result.ModifiedCount;
}
#endregion
}
}
| 830fe548eb0acfda3d5bc61899caffb16509856f | [
"Markdown",
"C#"
]
| 7 | C# | jim-lightfoot/MondoCore-MongoDB | 5d7f407a032a61b96ae0f277054f9eb5ae0df78f | cf8bafbeba357cec4dbae2d31cda528d3394873d |
refs/heads/master | <file_sep>import java.util.Arrays;
public class Solution {
public int solution(int[] T){
int marker = 0;
boolean found;
for (int i = 1; i < T.length; i++) {
marker = i;
found = true;
int[] winter = Arrays.copyOfRange(T, 0, i);
int[] summer = Arrays.copyOfRange(T, i, (T.length));
outerloop:
for (int tempWinter: winter) {
for (int tempSummer: summer) {
if (tempWinter>tempSummer) {
found = false;
break outerloop;
}
}
}
if (found)
break;
}
return marker;
}
}
| e52b571a8fb16fc79287b4de6d44cce0f5a10aa8 | [
"Java"
]
| 1 | Java | COJ123/WinterAndSummer | 402b7db83038737135a3bc49687e2691250f5ee2 | b2629b5cc34b3d29edd32f352c58f5fd3c0e4b5e |
refs/heads/master | <repo_name>JasonHhhhh/stackgan<file_sep>/StackGAN-hjr/StackGAN/stageI/run_exp.py
from __future__ import division
from __future__ import print_function
import dateutil.tz
import datetime
import argparse
import pprint
import sys
import os
# Allow relative imports when being executed as script.
# if __name__ == "__main__" and __package__ is None:
# sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
# import StackGAN.stageI # noqa: F401
# __package__ = "StackGAN.stageI"
sys.path.append("../")
print (sys.path)
from misc.datasets import TextDataset
from stageI.model import CondGAN
from stageI.trainer import CondGANTrainer
from misc.utils import mkdir_p
from misc.config import cfg, cfg_from_file
def parse_args():
# 创建一个解释器并且给他命名 或者 叙述
parser = argparse.ArgumentParser(description='Train a GAN network')
# config file 预先设置好的超参数列表
parser.add_argument('--cfg', dest='cfg_file',
help='optional config file',
default=None, type=str)
# 使用那个GPU
parser.add_argument('--gpu', dest='gpu_id',
help='GPU device id to use [0]',
default=2, type=int)
# if len(sys.argv) == 1:
# parser.print_help()
# sys.exit(1)
args = parser.parse_args()
return args
if __name__ == "__main__":
# 引入解释器
args = parse_args()
if args.cfg_file is not None:
cfg_from_file(args.cfg_file)
if args.gpu_id != -1: #不等于
cfg.GPU_ID = args.gpu_id
# 打印接下来训练的配置
print('Using config:')
pprint.pprint(cfg)
'''记录时间 先不看'''
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
datadir = '/home/jzz/hjr/gan/StackGAN-master/StackGAN/Data/%s' % cfg.DATASET_NAME
dataset = TextDataset(datadir, cfg.EMBEDDING_TYPE, 1)
filename_test = '%s/test' % (datadir)
dataset.test = dataset.get_data(filename_test)
if cfg.TRAIN.FLAG:
filename_train = '%s/train' % (datadir)
dataset.train = dataset.get_data(filename_train)
ckt_logs_dir = "ckt_logs/%s/%s_%s" % \
(cfg.DATASET_NAME, cfg.CONFIG_NAME, timestamp)
mkdir_p(ckt_logs_dir)
else:
s_tmp = cfg.TRAIN.PRETRAINED_MODEL
ckt_logs_dir = s_tmp[:s_tmp.find('.ckpt')]
model = CondGAN(
image_shape=dataset.image_shape
)
algo = CondGANTrainer(
model=model,
dataset=dataset,
ckt_logs_dir=ckt_logs_dir
)
if cfg.TRAIN.FLAG:
algo.train()
else:
''' For every input text embedding/sentence in the
training and test datasets, generate cfg.TRAIN.NUM_COPY
images with randomness from noise z and conditioning augmentation.'''
algo.evaluate()
<file_sep>/StackGAN-hjr/StackGAN/stageI/model.py
from __future__ import division
from __future__ import print_function
import prettytensor as pt
import tensorflow as tf
import sys
import os
# # Allow relative imports when being executed as script.
# if __name__ == "__main__" and __package__ is None:
# sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
# import StackGAN.stageI # noqa: F401
# __package__ = "StackGAN.stageI"
import sys
sys.path.append('../')
from misc.custom_ops import leaky_rectify
from misc.config import cfg
# 对阶段1的所有网络结构进行搭建,输入参数为shape特殊化第一阶段的GAN网络
class CondGAN(object):
def __init__(self, image_shape):
self.batch_size = cfg.TRAIN.BATCH_SIZE
self.network_type = cfg.GAN.NETWORK_TYPE
self.image_shape = image_shape
self.gf_dim = cfg.GAN.GF_DIM # 生成器的进来的特征的维度
self.df_dim = cfg.GAN.DF_DIM # 鉴别器进来的特征的维度
self.ef_dim = cfg.GAN.EMBEDDING_DIM
self.image_shape = image_shape
self.s = image_shape[0]
self.s2, self.s4, self.s8, self.s16 =\
int(self.s / 2), int(self.s / 4), int(self.s / 8), int(self.s / 16)
# Since D is only used during training, we build a template
# for safe reuse the variables during computing loss for fake/real/wrong images
# We do not do this for G,
# because batch_norm needs different options for training and testing
if cfg.GAN.NETWORK_TYPE == "default":
# 可见 __init__ 中 可以利用self.调用在 init往后def的函数,用法
with tf.variable_scope("d_net"):
# 定义默认设置的D的网络的图像解码器,文本解码器,以及最终形成输出的网络格式
self.d_encode_img_template = self.d_encode_image()
self.d_context_template = self.context_embedding()
self.discriminator_template = self.discriminator()
elif cfg.GAN.NETWORK_TYPE == "simple":
with tf.variable_scope("d_net"):
self.d_encode_img_template = self.d_encode_image_simple()
self.d_context_template = self.context_embedding()
self.discriminator_template = self.discriminator()
else:
raise NotImplementedError
# g-net
# 此处写了一个有embedings转化为AC的输入的特征前处理
# 此处难道不是前处理好的?????
def generate_condition(self, c_var):
# 建立了一个简单的全连接层,在embedings之后
conditions =\
(pt.wrap(c_var).
flatten().
custom_fully_connected(self.ef_dim * 2).
apply(leaky_rectify, leakiness=0.2))
# 最终使用leaky_ReLu
mean = conditions[:, :self.ef_dim]
log_sigma = conditions[:, self.ef_dim:]
'''什么意思???第一个维度是什么???'''
return [mean, log_sigma]
# 建立生成器网络:此时输入需要拼接噪声以及CA之后的TEXT Features
def generator(self, z_var):
''''''
'''Stage1 的G'''
# 设立计算节点 利用prettytensor建立,超级简洁,就像在搭积木:
# 节点分为0 1 为典型的残差模块:
'''记住一点,padding时,只有步长影响featuremap大小'''
'''这一操作 仿佛在上采样'''
node1_0 =\
(pt.wrap(z_var). # 将输入张量(holder)传给warp
flatten(). # 所有特征纵向变为1维展开然后连接一个全连接层,不影响batchsize操作:与cfg.GAN.GF_DIM 有关
custom_fully_connected(self.s16 * self.s16 * self.gf_dim * 8).
fc_batch_norm(). #reshape,维度自行推测形成多通道
reshape([-1, self.s16, self.s16, self.gf_dim * 8]))# -1处的维度是batchsize
node1_1 = \
(node1_0.
custom_conv2d(self.gf_dim * 2, k_h=1, k_w=1, d_h=1, d_w=1).#定制版 没有加偏置
conv_batch_norm().
apply(tf.nn.relu).
custom_conv2d(self.gf_dim * 2, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_conv2d(self.gf_dim * 8, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm())
'''有时通道数不同不可以直接加
此时可以
1X1卷积增加通道数
也可以:zero padding'''
# 残差网络
node1 = \
(node1_0.
apply(tf.add, node1_1).
apply(tf.nn.relu))
node2_0 = \
(node1.
# custom_deconv2d([0, self.s8, self.s8, self.gf_dim * 4], k_h=4, k_w=4).
apply(tf.image.resize_nearest_neighbor, [self.s8, self.s8]).# 最近邻插值上采样
custom_conv2d(self.gf_dim * 4, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm())
node2_1 = \
(node2_0.
custom_conv2d(self.gf_dim * 1, k_h=1, k_w=1, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_conv2d(self.gf_dim * 1, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_conv2d(self.gf_dim * 4, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm())
node2 = \
(node2_0.
apply(tf.add, node2_1).
apply(tf.nn.relu))
output_tensor = \
(node2.
# custom_deconv2d([0, self.s4, self.s4, self.gf_dim * 2], k_h=4, k_w=4).
apply(tf.image.resize_nearest_neighbor, [self.s4, self.s4]).
custom_conv2d(self.gf_dim * 2, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
# custom_deconv2d([0, self.s2, self.s2, self.gf_dim], k_h=4, k_w=4).
apply(tf.image.resize_nearest_neighbor, [self.s2, self.s2]).
custom_conv2d(self.gf_dim, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
# custom_deconv2d([0] + list(self.image_shape), k_h=4, k_w=4).
apply(tf.image.resize_nearest_neighbor, [self.s, self.s]).
custom_conv2d(3, k_h=3, k_w=3, d_h=1, d_w=1).
apply(tf.nn.tanh))
'''最终经过三次上采样成为最终图片'''
return output_tensor
def generator_simple(self, z_var):
output_tensor =\
(pt.wrap(z_var).
flatten().
custom_fully_connected(self.s16 * self.s16 * self.gf_dim * 8).
reshape([-1, self.s16, self.s16, self.gf_dim * 8]).
conv_batch_norm().
apply(tf.nn.relu).
custom_deconv2d([0, self.s8, self.s8, self.gf_dim * 4], k_h=4, k_w=4).
# apply(tf.image.resize_nearest_neighbor, [self.s8, self.s8]).
# custom_conv2d(self.gf_dim * 4, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_deconv2d([0, self.s4, self.s4, self.gf_dim * 2], k_h=4, k_w=4).
# apply(tf.image.resize_nearest_neighbor, [self.s4, self.s4]).
# custom_conv2d(self.gf_dim * 2, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_deconv2d([0, self.s2, self.s2, self.gf_dim], k_h=4, k_w=4).
# apply(tf.image.resize_nearest_neighbor, [self.s2, self.s2]).
# custom_conv2d(self.gf_dim, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(tf.nn.relu).
custom_deconv2d([0] + list(self.image_shape), k_h=4, k_w=4).
# apply(tf.image.resize_nearest_neighbor, [self.s, self.s]).
# custom_conv2d(3, k_h=3, k_w=3, d_h=1, d_w=1).
apply(tf.nn.tanh))
return output_tensor
def get_generator(self, z_var):
# 是‘default’还是‘simple’NET ?
if cfg.GAN.NETWORK_TYPE == "default":
return self.generator(z_var)
elif cfg.GAN.NETWORK_TYPE == "simple":
return self.generator_simple(z_var)
else:
raise NotImplementedError
# d-net
def context_embedding(self):
template = (pt.template("input").
custom_fully_connected(self.ef_dim).
apply(leaky_rectify, leakiness=0.2))
return template
''' D0 D1 基本相同 d_encode_image+discriminator 且值在训练中使用 所以保存为template'''
def d_encode_image(self):
node1_0 = \
(pt.template("input").
custom_conv2d(self.df_dim, k_h=4, k_w=4).
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 2, k_h=4, k_w=4).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 4, k_h=4, k_w=4).
conv_batch_norm().
custom_conv2d(self.df_dim * 8, k_h=4, k_w=4).
conv_batch_norm())
node1_1 = \
(node1_0.
custom_conv2d(self.df_dim * 2, k_h=1, k_w=1, d_h=1, d_w=1).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 2, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 8, k_h=3, k_w=3, d_h=1, d_w=1).
conv_batch_norm())
node1 = \
(node1_0.
apply(tf.add, node1_1).
apply(leaky_rectify, leakiness=0.2))
return node1
'''context_embedding
d_encode_image
discriminator
直接定以一种网络格式,固定,需要使用的时候直接调用返回template,这是pt特有的方式'''
def d_encode_image_simple(self):
template = \
(pt.template("input").
custom_conv2d(self.df_dim, k_h=4, k_w=4).
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 2, k_h=4, k_w=4).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 4, k_h=4, k_w=4).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
custom_conv2d(self.df_dim * 8, k_h=4, k_w=4).
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2))
return template
def discriminator(self):
template = \
(pt.template("input"). # 128*9*4*4
custom_conv2d(self.df_dim * 8, k_h=1, k_w=1, d_h=1, d_w=1). # 128*8*4*4
conv_batch_norm().
apply(leaky_rectify, leakiness=0.2).
# custom_fully_connected(1))
custom_conv2d(1, k_h=self.s16, k_w=self.s16, d_h=self.s16, d_w=self.s16))
return template
def get_discriminator(self, x_var, c_var):
'''
:param x_var: 图形特征输入
:param c_var: 文字特征输入,需要复制扩大
:return: 返回一个D网络
'''
x_code = self.d_encode_img_template.construct(input=x_var)
c_code = self.d_context_template.construct(input=c_var)
c_code = tf.expand_dims(tf.expand_dims(c_code, 1), 1) #增加一维,再增加一维
c_code = tf.tile(c_code, [1, self.s16, self.s16, 1]) #在进行扩大
x_c_code = tf.concat( [x_code, c_code],3) #拼接
'''结合template 形成一个网络,PT特有的方式'''
return self.discriminator_template.construct(input=x_c_code)
<file_sep>/StackGAN-hjr/StackGAN/testing.py
# author: <NAME>
cap_path = 'F:\Jason Howe\Program\hjr\StackGAN-master\StackGAN\Data/birds/text_c10/001.Black_footed_Albatross/Black_Footed_Albatross_0001_796111.txt'
with open(cap_path, "r") as f:
captions = f.read().split('\n')
print(captions)
captions = [cap for cap in captions if len(cap) > 0]
print(captions)
<file_sep>/StackGAN-hjr/StackGAN/__init__.py
# author: <NAME><file_sep>/StackGAN-hjr/StackGAN/misc/datasets.py
from __future__ import division
from __future__ import print_function
import numpy as np
import pickle
import random
'''给我images的数组以及其他如下,
我将为你定义一种准备数据的方法如下,注意:你需要给出imsize,来获得64,或者是256的图片用于不同的D的训练'''
class Dataset(object):
# 整个数据集level的信息
def __init__(self, images, imsize, embeddings=None,
filenames=None, workdir=None,
labels=None, aug_flag=True,
class_id=None, class_range=None):
self._images = images
'''此处的embeddings 涵盖所有images中的所有字母对应的特征: size:图片数,句子数,特征长度 '''
self._embeddings = embeddings #这里的embedings是与选用cnn-rnn做出来的特征 对应到 TEXT文件夹每个目录下的txt中的不同字母
self._filenames = filenames
# 需要建立一个目录存储数据的呀什么的 即:/Data/birds 或者 /Data/flowers
self.workdir = workdir
self._labels = labels
self._epochs_completed = -1
self._num_examples = len(images)
'''打乱了的ID 0 1 2 3 排序'''
self._saveIDs = self.saveIDs()
self._aug_flag = aug_flag
# shuffle on first run
self._index_in_epoch = self._num_examples
self._class_id = np.array(class_id)
self._class_range = class_range
self._imsize = imsize
self._perm = None
'''property:装饰起的作用是什么???对一个class下定义的属起到监控作用
在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改:
s = Student()
s.score = 9999
这显然不合逻辑。为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩
但是这样做会很复杂!你需要对每个属性都做这样的操作!'''
@property
def images(self):
return self._images
@property
def embeddings(self):
return self._embeddings
@property
def filenames(self):
return self._filenames
@property
def num_examples(self):
return self._num_examples
@property
def epochs_completed(self):
return self._epochs_completed
'''对所有的照片进行shuufle操作:
产生一个与i长度相当的ID数组
randomshuffle之 这一样操作._saveIDs
根据什么?:根据你类的基本属性:images的长度'''
def saveIDs(self):
self._saveIDs = np.arange(self._num_examples)
np.random.shuffle(self._saveIDs)
return self._saveIDs
'''给我一个filename和对应的class_id(后续调用会用for循环对所有做处理)
我会返回相应的字符描述,为一个list 有很多句!!!但意思相同
问题????:鸟儿也是这个函数?'''
def readCaptions(self, filenames, class_id):
name = filenames
if name.find('jpg/') != -1: # 是否存在jpg/这四个字符???即:是否在前处理中已经将描述解压?
# 是的话进行如下操作
class_name = 'class_%05d/' % class_id #五位整数
name = name.replace('jpg/', class_name)
# name: 剔除jpg/换作 class_id 这样才能访问到对的text目录
cap_path = '%s/text_c10/%s.txt' %\
(self.workdir, name)
# 打开text文件 并且读取其中所有的描述 按行
with open(cap_path, "r") as f:
captions = f.read().split('\n')
captions = [cap for cap in captions if len(cap) > 0]
# 返回一个LIST
return captions
'''将所有的照片(之前比这个尺寸大)尺寸全部随即裁剪为256 64 到底是256 还是 64 这个要看你怎么定义类了,你对定义Dataset256那么就是处于stage2的训练了
输入images 为 :np数组 4D (你给几张数据我帮你裁剪几张且反转) 且包含翻转操作'''
def transform(self, images):
if self._aug_flag:
'''如果进行增强。即前处理'''
# 创建一个空的矩阵
transformed_images =\
np.zeros([images.shape[0], self._imsize, self._imsize, 3])
ori_size = images.shape[1]
for i in range(images.shape[0]):
# 确定裁剪的像素的起始位置
h1 = np.floor((ori_size - self._imsize) * np.random.random())
w1 = np.floor((ori_size - self._imsize) * np.random.random())
# cropped_image =\
# images[i][w1: w1 + self._imsize, h1: h1 + self._imsize, :]
# 索引必须是int
original_image = images[i]
cropped_image = original_image[int(w1): int(w1 + self._imsize),
int(h1): int(h1 + self._imsize),:]
# 随即翻转图像 上下
if random.random() > 0.5:
transformed_images[i] = np.fliplr(cropped_image)
else:
transformed_images[i] = cropped_image
return transformed_images
else:
return images
'''给我一个batch的embeddings,以及其filenames——list和classID-》用来调 readCaptions 读取text中的描述语句
这个embeddings包含了bacth中每一张图的很多句描述???
我给你返回一个随机选择sample_num句的embeddings特征2D batchsize*vctorlenth'''
def sample_embeddings(self, embeddings, filenames, class_id, sample_num):
# 如果只有一句话!!!!!!!!!!!!!!!! 或者只有2D 直接squezze
if len(embeddings.shape) == 2 or embeddings.shape[1] == 1:
return np.squeeze(embeddings)
else:
batch_size, embedding_num, _ = embeddings.shape
# embedding_num:有几句话就对几句做了embedding 从这几句中选几句?
# _为embedding的特征向量的长度的数目
# Take every sample_num captions to compute the mean vector
sampled_embeddings = []
sampled_captions = []
# 对batch中的每个做如下操作
for i in range(batch_size):
# # 参数意思分别 是从a 中以概率P,随机选择3个, p没有指定的时候相当于是一致的分布
# a1 = np.random.choice(a=5, size=3, replace=False, p=None)
randix = np.random.choice(embedding_num,
sample_num, replace=False)
if sample_num == 1: #如果只选一句话!!!!!!!
randix = int(randix)
# 对batch中的第i个: 读取其字幕
captions = self.readCaptions(filenames[i],
class_id[i])
sampled_captions.append(captions[randix])
sampled_embeddings.append(embeddings[i, randix, :])
else: #如果选了两句话
e_sample = embeddings[i, randix, :]
# 第i个特征图,每个图取 randix索引的行, 这些行的所有列都保留
# e_mean 为 一个text内的sample之后的embeddings 2D
# 此时我要沿着列求平均保持特征向量唯独不变 最终只提炼出来一个1维的向量 但是仍然有三个:【】
e_mean = np.mean(e_sample, axis=0)
# 录入sampled_embeddings for之后形成了整个batch的sample_embeddings
sampled_embeddings.append(e_mean)
sampled_embeddings_array = np.array(sampled_embeddings)
# 去掉多余维度:框【】 去掉了中间行(不同句子的)的维度
return np.squeeze(sampled_embeddings_array), sampled_captions
'''执行这句代表,我要为下一个batch提取数据了这将是下一个batch所需要的所有数据,输出一个list,有:
sampled_embeddings, sampled_captions,sampled_images(前三个是同一张图(batch)的!!!)labels(这个labels是干嘛用的?????),sampled_wrong_images
输入为:
定义好的Dataset大类:给我训练或测试的所有图片,对应的
batch大小
window:你要几句话我就从对应的text中提出几句话
images, imsize,
embeddings,filenames, workdir,labels, aug_flag,class_id, class_range'''
def next_batch(self, batch_size, window):
"""Return the next `batch_size` examples from this data set."""
'''给我一个起点,即上一个batch的终点(末尾剔除---》》0~start-1)
我返回一个what?'''
# _index_in_epoch 初值记为 len(_num_examples)
# 也就是在刚开始训练的时候就会创建以下
start = self._index_in_epoch
self._index_in_epoch += batch_size
#判刑一个epoch是否完成
if self._index_in_epoch > self._num_examples:
# Finished epoch
# 每完成一个Epoch 即加一
self._epochs_completed += 1
# 美国一个epoch都需要将所有训练样本shuffle
# Shuffle the data
self._perm = np.arange(self._num_examples)
np.random.shuffle(self._perm)
# 开始下一个 epoch
# Start next epoch
# 设置起点
start = 0
self._index_in_epoch = batch_size
assert batch_size <= self._num_examples
# 设置重点
end = self._index_in_epoch
# shuffle过的ID列队中拿出 start:end 这一batch的索引 (取真图)
current_ids = self._perm[start:end]
# _num_examples 是 生成数据集的类的超参images的第一维有多少!即有几张图片!!!
# 这句话产生了错图!!!!!
fake_ids = np.random.randint(self._num_examples, size=batch_size)
# 所有训练的图对应的class 我们不希望 (错图,对的描述) 和 (真确图,正确描述)成为一类!!!(在同一索引处)
collision_flag =\
(self._class_id[current_ids] == self._class_id[fake_ids])
# 再找到的冲突的索引处将去对应的ID改为之前的100~200之间的随机数
fake_ids[collision_flag] =\
(fake_ids[collision_flag] +
np.random.randint(100, 200)) % self._num_examples
# 取出真图
sampled_images = self._images[current_ids]
# 取出错图
sampled_wrong_images = self._images[fake_ids, :, :, :]
# 改变数据类型
sampled_images = sampled_images.astype(np.float32)
sampled_wrong_images = sampled_wrong_images.astype(np.float32)
# 将数据缩放到-1~1
# 先缩放到0~2 再平移到 -1~1
sampled_images = sampled_images * (2. / 255) - 1.
sampled_wrong_images = sampled_wrong_images * (2. / 255) - 1.
# 取代的不是64 256 我们需要进行裁剪
sampled_images = self.transform(sampled_images)
sampled_wrong_images = self.transform(sampled_wrong_images)
ret_list = [sampled_images, sampled_wrong_images]
if self._embeddings is not None:
# 通过上述我们得到了这批训练的图片的编号,我们可以依次从_filenames和_class_id中取出
filenames = [self._filenames[i] for i in current_ids]
class_id = [self._class_id[i] for i in current_ids]
# 调用 sample_embeddings:
# 给我一个batch的embeddings,以及其filenames——list和classID
# 我给你返回一个随机选择sample_num句的embeddings特征2D batchsize*vctorlenth
sampled_embeddings, sampled_captions = \
self.sample_embeddings(self._embeddings[current_ids],
filenames, class_id, window) # window是取多少句话?????
ret_list.append(sampled_embeddings)
ret_list.append(sampled_captions)
else:
ret_list.append(None)
ret_list.append(None)
if self._labels is not None:
ret_list.append(self._labels[current_ids])
else:
ret_list.append(None)
return ret_list
'''给我batch_size,start点(在一个epoch中的),max_captions
我返回一个[sampled_images, sampled_embeddings_batchs,
self._saveIDs[start:end], sampled_captions]
???不太懂:self._saveIDs[start:end] 干嘛用的?大概是最后检测用的把看效果用的?'''
def next_batch_test(self, batch_size, start, max_captions):
"""Return the next `batch_size` examples from this data set."""
# 我执行这一个batch会超出epoch吗? 如果超出了我下一个就不是默认的batchsize了!!!
# 但是余下的例子我还想跑, 因此:??????什么意思?意义何在
if (start + batch_size) > self._num_examples:
end = self._num_examples
#计算出我这一步的batchsize
start = end - batch_size
else:
end = start + batch_size
sampled_images = self._images[start:end]
sampled_images = sampled_images.astype(np.float32)
# from [0, 255] to [-1.0, 1.0]
sampled_images = sampled_images * (2. / 255) - 1.
sampled_images = self.transform(sampled_images)
sampled_embeddings = self._embeddings[start:end]
_, embedding_num, _ = sampled_embeddings.shape
sampled_embeddings_batchs = []
sampled_captions = []
sampled_filenames = self._filenames[start:end]
sampled_class_id = self._class_id[start:end]
for i in range(len(sampled_filenames)):
captions = self.readCaptions(sampled_filenames[i],
sampled_class_id[i])
# print(captions)
# 拿到了这一batch的所有图的所有captions
sampled_captions.append(captions)
# 对每一张图的captions 我们要拿出其中max_captions个,数量不够?全拿出来
for i in range(np.minimum(max_captions, embedding_num)):
batch = sampled_embeddings[:, i, :]
sampled_embeddings_batchs.append(np.squeeze(batch))
return [sampled_images, sampled_embeddings_batchs,
self._saveIDs[start:end], sampled_captions]
'''这个类生成了一系列方法,来定义数据集(返回一个dataset类):给我images embeddings,im.shape,filenames_list,class list
即:这样一来,我就创建了关于 birds或者flower 这一数据集的每个batch的数据读取操作:包括真,错图片,embedings,
必须TextDataset(object):工作目录# 需要一个目录 即:/Data/birds 或者 /Data/flowers,
文字embedding来源是哪里
stage1 2 处理的图像大小比例 default=4 ?'''
class TextDataset(object):
def __init__(self, workdir, embedding_type, hr_lr_ratio):
lr_imsize = 64
self.hr_lr_ratio = hr_lr_ratio
if self.hr_lr_ratio == 1:
self.image_filename = '/76images.pickle'
elif self.hr_lr_ratio == 4:
self.image_filename = '/304images.pickle'
self.image_shape = [lr_imsize * self.hr_lr_ratio,
lr_imsize * self.hr_lr_ratio, 3]
# 一张图有多少个数表示
self.image_dim = self.image_shape[0] * self.image_shape[1] * 3
self.embedding_shape = None
self.train = None
self.test = None
self.workdir = workdir
if embedding_type == 'cnn-rnn':
self.embedding_filename = '/char-CNN-RNN-embeddings.pickle'
elif embedding_type == 'skip-thought':
self.embedding_filename = '/skip-thought-embeddings.pickle'
'''使用这个方法,我需要你先给我我的pickle(存储了相片和embeddings)所在的路径'''
def get_data(self, pickle_path, aug_flag=True):
# 打开照片存入 images 中!!!!!!!!!!!!
with open(pickle_path + self.image_filename, 'rb') as f:
images = pickle.load(f,encoding='bytes')
images = np.array(images)
print('images: ', images.shape)
# 打开embeddings 存入 embeddings中!!!
with open(pickle_path + self.embedding_filename, 'rb') as f:
embeddings = pickle.load(f,encoding='bytes')
embeddings = np.array(embeddings)
self.embedding_shape = [embeddings.shape[-1]]
print('embeddings: ', embeddings.shape)
# 打开filenames_list 存入 list_filenames!!!
with open(pickle_path + '/filenames.pickle', 'rb') as f:
list_filenames = pickle.load(f,encoding='bytes')
print('list_filenames: ', len(list_filenames), list_filenames[0])
# class_info 存入 class_id!!!
with open(pickle_path + '/class_info.pickle', 'rb') as f:
class_id = pickle.load(f,encoding='bytes')
return Dataset(images, self.image_shape[0], embeddings,
list_filenames, self.workdir, None,
aug_flag, class_id)
| 219114db6803c2bbbb6671336c4ac9233400458c | [
"Python"
]
| 5 | Python | JasonHhhhh/stackgan | 81f76f5c2de7a57f5ab1c7adf0421dbe375f1388 | de63a42702917f40d4a183928d8d6c94fb555336 |
refs/heads/main | <repo_name>jkchuong/Chess<file_sep>/README.md
# Chess
Creating a Chess game in C# with WPF.
This project is to practice use of interfaces and decoupling in OOP.
When completed, this will be combined with the AccountManager project at https://github.com/jkchuong/AccountManager
<file_sep>/ChessApp/ChessTests/CellTests.cs
using NUnit.Framework;
using ChessApp;
namespace ChessTests
{
public class CellTests
{
[TestCase(1, 1, "(1, 1)")]
[TestCase(2, 5, "(2, 5)")]
public void CellReturnsCellPosition(int x, int y, string expectedOutput)
{
var cell = new Cell(x, y);
Assert.AreEqual(expectedOutput, cell.ToString());
}
}
}<file_sep>/ChessApp/ChessTests/BoardTests.cs
using NUnit.Framework;
using ChessApp;
namespace ChessTests
{
public class BoardTests
{
}
}<file_sep>/ChessApp/ChessTests/PawnTests.cs
using NUnit.Framework;
using ChessApp;
namespace ChessTests
{
public class PawnTests
{
//[TestCase(true, 1, 1, "(1, 1)")]
//[TestCase(false, 2, 5, "(2, 5)")]
//public void ReturnPawnPosition(bool colour, int x, int y, string expectedOutput)
//{
// var pawn = new Pawn(colour, new Cell(x, y));
// string result = pawn.GetPosition();
// Assert.AreEqual(expectedOutput, result);
//}
//[TestCase(true, 1, 1, 0, "(2, 1)")]
//[TestCase(true, 1, 1, 1, "(2, 2)")]
//public void MovePawns(bool colour, int x, int y, int moveIndex, string expectedOutput)
//{
// var pawn = new Pawn(colour, new Cell(x, y));
// pawn.Moving(moveIndex);
// string result = pawn.GetPosition();
// Assert.AreEqual(expectedOutput, result);
//}
//[TestCase(true, 1, 1, 0, false)]
//public void MovingPawnLeavesCellUnoccupied(bool colour, int x, int y, int moveIndex, bool expectedOutput)
//{
// Cell initialCell = new Cell(x, y);
// var pawn = new Pawn(colour, initialCell);
// pawn.Moving(moveIndex);
// bool result = initialCell.IsOccupied;
// Assert.AreEqual(expectedOutput, result);
//}
//[TestCase(true, 1, 1, 0, true)]
//public void MovingPawnOccupiesCell(bool colour, int x, int y, int moveIndex, bool expectedOutput)
//{
// Cell initialCell = new Cell(x, y);
// var pawn = new Pawn(colour, initialCell);
// pawn.Moving(moveIndex);
// bool result = pawn.Position.IsOccupied;
// Assert.AreEqual(expectedOutput, result);
//}
}
} | 2df5b24ab4ede265ff7747b9c5dd21f6dfb7e656 | [
"Markdown",
"C#"
]
| 4 | Markdown | jkchuong/Chess | 31bffc2a7e2e9477a7305183794965fce1024ed3 | f4a3c52fd292db058b5c06ed6de4889dbadc9b70 |
refs/heads/master | <repo_name>philipjohn/add-shortlink-to-posts<file_sep>/readme.txt
=== Plugin Name ===
Contributors: philipjohn
Donate link: http://philipjohn.co.uk/
Tags: shortlink, shorturl, tinyurl
Requires at least: 3.2.1
Tested up to: 4.0
Stable tag: 0.3.3
Adds a link to the shortlink for each post below the content.
== Description ==
This plugins adds a visible link to the end of every post.
Best used in conjunction with the [Goo.gl Shortlinks](http://wordpress.org/extend/plugins/googl-shortlinks/) or [Bit.ly Shortlinks](http://wordpress.org/extend/plugins/bitly-shortlinks/) plugins.
Feature requests welcomed with open arms!
== Installation ==
Simple install in /wp-content/plugins and activate like any other!
== Frequently Asked Questions ==
= Why is the shortlink just using the default permalink structure (e.g. http://example.com/?p=4)? =
That's the default shortlink format provided by WordPress. You might want to take a look at the [Goo.gl Shortlinks](http://wordpress.org/extend/plugins/googl-shortlinks/) or [Bit.ly Shortlinks](http://wordpress.org/extend/plugins/bitly-shortlinks/) plugins.
== Changelog ==
= 0.1 =
* First version - nothing changed of course!
= 0.2 =
* Added rel="shortlink"
= 0.3 =
* WP v3.2.1 compatibility
* changed format
* new function name
* localised
= 0.3.1 =
* Fix for title appearing again at the beginning of post content
= 0.3.3 =
* Stop appearing on excerpts
* Code tidy up
* Better HTML generation<file_sep>/add-shortlink-to-posts.php
<?php
/*
Plugin Name: Add Shortlink to Posts
Plugin URI: http://philipjohn.co.uk
Description: Adds a link to the shortlink for each post below the content.
Version: 0.3.3
Author: <NAME>
Author URI: http://philipjohn.co.uk
License: GPL2
*/
/*
* Localise the plugin
*/
load_plugin_textdomain('astp');
/*
* Adds the shortlink on the end of posts
*/
function astp_add_shortlink($content){
// Don't add shortlink to excerpts
if ( ! is_single() )
return $content;
// Generate the shortlink
$shortlink = wp_get_shortlink();
$shortlink = ( ! empty( $shortlink ) ? $shortlink : get_permalink() );
// Generate the html
$html = sprintf(
'<p class="the_shortlink">%s <a rel="shortlink" href="%s" title="%s">%s</p>',
__("Shortlink for this post:", 'astp'),
$shortlink,
get_the_title(),
$shortlink
);
// Add to the content
return $content . $html;
}
add_filter( "the_content", "astp_add_shortlink", 11 );
?> | 7c3ed19809facc43ff8c12d89942224758fb75af | [
"Text",
"PHP"
]
| 2 | Text | philipjohn/add-shortlink-to-posts | f7f0dd7931adc9a49b092fe19abe1151ef8e51a2 | 071b28ae37e6b2c564771d85f0df3b22fd6c4220 |
refs/heads/master | <repo_name>nghiatran0103/c4ejs108<file_sep>/session4/index.js
// alert('hello');
let Hung = {
tuoi: 25,
chieuCao: 180,
congViec: 'lap trinh'
}
let movie = {
title: 'batman',
year: 2012,
rate: 8.4,
}
// cach dung .
// console.log(movie.title);
// cach dung object['prop']
// console.log(movie['title']);
// let propName = 'year';
// console.log(movie[propName]); // movie['year'] ~ movie.year
// // đọc tên thuộc tính từ người dùng
// let input = prompt('nhap ten thuoc tinh');
// // in ra giá trị qua console/alert
// console.log(movie[input]);
movie.rate = 8.7;
console.log(movie);
// giam di 0.5
movie.rate = movie.rate - 0.5;
console.log(movie); // rate = 8.2
// lay ten thuoc tinh tu nguoi dung
let input = prompt('nhap ten thuoc tinh');
// lay gia tri thuoc tinh tu nguoi dung
let value = prompt('nhap gia tri thuoc tinh');
// update gia tri cua object
movie[input] = value;
// in ra
console.log(movie);<file_sep>/session4/hw4.js
let dict = {
debug:
"The process of figuring out why your program has a certain error and how to fix it done",
done:
"When your task is complete, the only thing you have to do is to wait for users to use it (no additional codes or actions needed)",
defect: "The formal word for ‘error’",
pm:
"The short version of Project Manager, the person in charge of the final result of a project",
"ui/ux":
"UI means User Interface, UX mean User Experience, are the process to define how your products looks and feels",
};
while (true) {
let input = prompt('Enter a keyword:');
if (dict[input]) {
alert(`${input}\n${dict[input]}`);
} else {
const definitionInput = prompt(`We cannot find your keyword: ${input}. Leave your definition: `);
dict[input] = definitionInput;
}
}<file_sep>/session4/hw1.js
const product = {
name: '<NAME>',
price: 1700,
brand: 'Xiaomi',
color: 'white'
};
for (let prop in product) {
console.log(prop + ': '+ product[prop]);
}
<file_sep>/session4/hw5.js
const products = [
{
name: 'Xiaomi portable charger 20000mah',
brand: 'Xiaomi',
price: '428',
color: 'White',
category: 'Charger',
providers: ['Phukienzero', 'Dientuccc'],
},
{
name: 'VSmart Active 1',
brand: 'VSmart',
price: '5487',
color: 'Black',
category: 'Phone',
providers: ['Tgdd', 'Ddghn', 'VhStore'],
},
{
name: 'IPhone X',
brand: 'Apple',
price: '21490',
color: 'Gray',
category: 'Phone',
providers: ['Tgdd'],
},
{
name: 'Samsung Galaxy A9',
brand: 'Samsung',
price: '8490',
color: 'Blue',
category: 'Phone',
providers: ['Tgdd'],
},
]
// 5.1
// for (let i = 0; i < products.length; i++) {
// let product = products[i];
// console.log(`Name: ${product.name}`);
// console.log(`Price: ${product.price}`);
// console.log('--------------------------------')
// }
// 5.2, 5.4
for (let i = 0; i < products.length; i++) {
let product = products[i];
console.log(`#${i + 1}. ${product.name}`);
console.log(`Price: ${product.price}`);
console.log(`Providers: ${product.providers.join(' ')}`);
console.log('--------------------------------')
}
// let position = Number(prompt('Enter product position:'));
// // check vi tri co hop le khong, khong hop le thi nhap lai
// while (position < 1 || position > products.length) {
// position = Number(prompt('Invalid position. Enter product position:'));
// }
// const product = products[position - 1];
// console.log(`Name: ${product.name}`);
// console.log(`Brand: ${product.brand}`);
// console.log(`Price: ${product.price}`);
// console.log(`Color: ${product.color}`);
// console.log(`Category: ${product.category}`);
// 5.3
// let category = prompt('Enter category:');
// for (let i = 0; i < products.length; i++) {
// let product = products[i];
// if (product.category === category) {
// console.log(`Name: ${product.name}`);
// console.log(`Price: ${product.price}`);
// console.log('--------------------------------')
// }
// }
// 5.5
let provider = prompt('Enter provider:');
for (let i = 0; i < products.length; i++) {
let product = products[i];
// cach 1: dung ham includes cua array
// if (product.providers.includes(provider)) {
// console.log(`Name: ${product.name}`);
// console.log(`Price: ${product.price}`);
// console.log(`Providers: ${product.providers.join(' ')}`);
// console.log('--------------------------------')
// }
// cach 2: dung bien tam contained. check voi tung provider cua product.
// neu co provider day thi set contained bang true
let contained = false;
for (prov of product.providers) {
if (prov === provider) {
contained = true;
break;
}
}
if (contained) {
console.log(`Name: ${product.name}`);
console.log(`Price: ${product.price}`);
console.log(`Providers: ${product.providers.join(' ')}`);
console.log('--------------------------------')
}
}<file_sep>/session5/index.js
// bai 1, dung bien tam, dung vong for chay nguoc
// str[2]
// let str = 'abc';
// let newStr = '';
// for (let i = str.length - 1; i >= 0; i--) {
// newStr = newStr + str[i];
// }
// console.log(newStr);
// bai 2
// let str = 'this is a test';
// // output 'This Is A Test';
// // 1.tach thanh cac tu nho
// let strs = str.split(' ');
// console.log(strs);
// 2. viet hoa chu cai dau cua tung tu
// let newStr = '';
// // for (let i = 0; i < strs.length; i++) {
// // let strCon = strs[i];
// // }
// for (let tu of strs) {
// // str[0] = 'a'
// // di qua tung phan tu cua tu, chuyen ky tu dau
// // thanh chu viet hoa
// // gan vao newStr
// for (let i = 0; i < tu.length; i++) {
// if (i === 0) {
// newStr += tu[i].toUpperCase();
// } else {
// newStr += tu[i];
// }
// }
// newStr += ' ';
// }
// console.log(newStr);
// bai 3
let arr = ['one','two','three','one','one',
'four','five','four','five'];
// tạo 1 mảng lưu kết quả
// let newArr = [];
// // đi qua từng phần tử trong mảng gốc
// for (element of arr) {
// if (newArr.includes(element)) {
// // không add vào mảng kết quả
// } else {
// // nếu mảng lưu kết quả không chứa phần tử đó,
// // thì add vào mảng lưu kết quả
// newArr.push(element);
// }
// }
// console.log(`array goc: ${arr}`);
// console.log(`array kết quả: ${newArr}`);
console.log([...new Set(arr)]);
// bai 4
// tao mang employee chua 3 phan tu
const employees = [
{
name: 'Hung',
age: 25,
position: 'dev',
},
{
name: 'Phong',
age: 27,
position: 'manager',
},
{
name: 'Loc',
age: 20,
position: 'dev moi',
},
]
while (true) {
// loop, cho nguoi dung nhap lenh
const command = prompt('Enter command: C, R, U, D:');
// check lenh, if else
if (command === 'R') {
const str = 'Danh sach nhan vien:\n';
for (const employee of employees) {
str += `Ten: ${employee.name}, Tuoi: ${employee.age}, Vi tri: ${employee.position}`;
}
alert(str);
} else if (command === 'C') {
// 3 propmt, nhap cac truong ten, tuoi, vi tri
// tao 1 object moi, push vao mang
}
// delete cho nguoi dung nhap index
// dung arr.splice(index, 1)
// update cho nguoi dung nhap index
// 3 propmt, nhap cac truong ten, tuoi, vi tri
// arr[index].name = nameInput
// cac truong con lai, tuong tu
}
// bai 5
// check nam
// check ngay va check thang
// if (check dieu kien thang 1, 3, 5, 7, 8, 10, 12) {
// // check ngay trong khoang 1-31
// } else if (check dieu thang 2)
// // check nam % 4 === 0 && nam % 100 !== 0
// // check ngay trong khoang 1-29
// // else
// // check ngay trong khoang 1-28
// } else if (check thang 4, 6, 9, 11) {
// // check ngay trong khoang 1-30
// } else {
// // thang khong hop le
// } | 4f5e8c600c8b4911c7c8f06360b32fb33a2f22fb | [
"JavaScript"
]
| 5 | JavaScript | nghiatran0103/c4ejs108 | 6c71f4bd1be98b03030c9e02d5155b0c1040ca81 | 91db107d3dd3182d22e03356873339701dbd271e |
refs/heads/master | <file_sep>package jp.co.scsac.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import jp.co.scsac.entity.Book;
import jp.co.scsac.entity.BookStatusMaster;
public interface BookStatusMasterRepository extends PagingAndSortingRepository<BookStatusMaster, Integer> {
}
<file_sep>spring.datasource.url=jdbc:postgresql://localhost:5432/bookon
spring.datasource.username=postgres
spring.datasource.password=<PASSWORD>
spring.datasource.driverClassName=org.postgresql.Driver
server.port=18081<file_sep>package jp.co.scsac.entity;
import java.io.Serializable;
import javax.persistence.*;
import jp.co.scsac.entity.Book;
import java.sql.Timestamp;
/**
* The persistent class for the book_status_history database table.
*
*/
@Entity
@Table(name = "book_status_history")
public class BookStatusHistory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Integer id;
@Column(name = "created_at")
private Timestamp createdAt;
@Column(name = "update_account_id")
private String updateAccountId;
@Column(name = "update_at")
private Timestamp updateAt;
private Integer version;
// bi-directional many-to-one association to BookInfo
@ManyToOne
@JoinColumn(name = "book_info_id")
private BookInfo bookInfo;
// bi-directional many-to-one association to Book
@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
// bi-directional many-to-one association to ProcessTypeMaster
@ManyToOne
@JoinColumn(name = "process_type_master_id")
private ProcessTypeMaster processTypeMaster;
public BookStatusHistory() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Timestamp getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public String getUpdateAccountId() {
return this.updateAccountId;
}
public void setUpdateAccountId(String updateAccountId) {
this.updateAccountId = updateAccountId;
}
public Timestamp getUpdateAt() {
return this.updateAt;
}
public void setUpdateAt(Timestamp updateAt) {
this.updateAt = updateAt;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
public BookInfo getBookInfo() {
return this.bookInfo;
}
public void setBookInfo(BookInfo bookInfo) {
this.bookInfo = bookInfo;
}
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
public ProcessTypeMaster getProcessTypeMaster() {
return this.processTypeMaster;
}
public void setProcessTypeMaster(ProcessTypeMaster processTypeMaster) {
this.processTypeMaster = processTypeMaster;
}
}<file_sep>-- Project Name : BOOK-ON
-- Date/Time : 2016/07/29 17:49:18
-- Author : mishima_manabu
-- RDBMS Type : PostgreSQL
-- Application : A5:SQL Mk-2
-- 書籍状態マスタテーブル
create table BOOK_STATUS_MASTER (
ID character varying(5) not null
, STATUS_NAME character varying(32) not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint BOOK_STATUS_MASTER_PKC primary key (ID)
) ;
-- 書籍タグテーブル
create table BOOK_TAG (
ID serial not null
, BOOK_INFO_ID integer not null
, TAG_NAME_MANAGEMENT_ID integer not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint BOOK_TAG_PKC primary key (ID)
) ;
-- タグ名管理テーブル
create table TAG_NAME_MANAGEMENT (
ID serial not null
, TAG_NAME character varying(32) not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint TAG_NAME_MANAGEMENT_PKC primary key (ID)
) ;
alter table TAG_NAME_MANAGEMENT add constraint TAG_NAME_MANAGEMENT_IX1
unique (TAG_NAME) ;
-- 推奨記録テーブル
create table RECOMMENDED_RECORD (
ID serial not null
, BOOK_INFO_ID integer not null
, ACCOUNT_ID character varying(32) not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint RECOMMENDED_RECORD_PKC primary key (ID)
) ;
-- 読書記録テーブル
create table READING_RECORD (
ID serial not null
, BOOK_INFO_ID integer not null
, ACCOUNT_ID character varying(32) not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint READING_RECORD_PKC primary key (ID)
) ;
-- 処理種別マスタテーブル
create table PROCESS_TYPE_MASTER (
ID character varying(5) not null
, PROCESS_TYPE_NAME character varying(32) not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint PROCESS_TYPE_MASTER_PKC primary key (ID)
) ;
-- 書籍状態履歴テーブル
create table BOOK_STATUS_HISTORY (
ID serial not null
, PROCESS_TYPE_MASTER_ID character varying(5) not null
, BOOK_ID integer
, BOOK_INFO_ID integer not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint BOOK_STATUS_HISTORY_PKC primary key (ID)
) ;
-- 貸出情報テーブル
create table RENTAL_INFO (
ID serial not null
, BOOK_ID integer not null
, ACCOUNT_ID character varying(32) not null
, RENTAL_DATE date not null
, RETURN_DUE_DATE date not null
, RETURN_DATE date
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint RENTAL_INFO_PKC primary key (ID)
) ;
-- 書籍テーブル
create table BOOK (
ID character varying(5) not null
, BOOK_INFO_ID integer not null
, BOOK_STATUS_MASTER_ID integer not null
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint BOOK_PKC primary key (ID)
) ;
-- 書籍情報テーブル
create table BOOK_INFO (
ID serial not null
, BOOK_NAME character varying(256) not null
, AUTHOR character varying(126) not null
, ISBN integer not null
, PUBLISHED_DATE date
, CREATED_AT timestamp not null
, UPDATE_AT timestamp
, VERSION integer not null
, UPDATE_ACCOUNT_ID character varying(32)
, constraint BOOK_INFO_PKC primary key (ID)
) ;
alter table BOOK_INFO add constraint BOOK_INFO_IX1
unique (ISBN) ;
comment on table BOOK_STATUS_MASTER is '書籍状態マスタテーブル 書籍状態マスタテーブル';
comment on column BOOK_STATUS_MASTER.ID is 'ID';
comment on column BOOK_STATUS_MASTER.STATUS_NAME is '状態名';
comment on column BOOK_STATUS_MASTER.CREATED_AT is '登録日時';
comment on column BOOK_STATUS_MASTER.UPDATE_AT is '更新日時';
comment on column BOOK_STATUS_MASTER.VERSION is 'バージョン';
comment on column BOOK_STATUS_MASTER.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table BOOK_TAG is '書籍タグテーブル 書籍タグテーブル';
comment on column BOOK_TAG.ID is 'ID';
comment on column BOOK_TAG.BOOK_INFO_ID is '書籍情報ID';
comment on column BOOK_TAG.TAG_NAME_MANAGEMENT_ID is 'タグ名管理ID';
comment on column BOOK_TAG.CREATED_AT is '登録日時';
comment on column BOOK_TAG.UPDATE_AT is '更新日時';
comment on column BOOK_TAG.VERSION is 'バージョン';
comment on column BOOK_TAG.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table TAG_NAME_MANAGEMENT is 'タグ名管理テーブル タグ名管理テーブル';
comment on column TAG_NAME_MANAGEMENT.ID is 'ID';
comment on column TAG_NAME_MANAGEMENT.TAG_NAME is 'タグ名';
comment on column TAG_NAME_MANAGEMENT.CREATED_AT is '登録日時';
comment on column TAG_NAME_MANAGEMENT.UPDATE_AT is '更新日時';
comment on column TAG_NAME_MANAGEMENT.VERSION is 'バージョン';
comment on column TAG_NAME_MANAGEMENT.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table RECOMMENDED_RECORD is '推奨記録テーブル 推奨記録テーブル';
comment on column RECOMMENDED_RECORD.ID is 'ID';
comment on column RECOMMENDED_RECORD.BOOK_INFO_ID is '書籍情報ID';
comment on column RECOMMENDED_RECORD.ACCOUNT_ID is 'アカウントID';
comment on column RECOMMENDED_RECORD.CREATED_AT is '登録日時';
comment on column RECOMMENDED_RECORD.UPDATE_AT is '更新日時';
comment on column RECOMMENDED_RECORD.VERSION is 'バージョン';
comment on column RECOMMENDED_RECORD.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table READING_RECORD is '読書記録テーブル 読書記録テーブル';
comment on column READING_RECORD.ID is 'ID';
comment on column READING_RECORD.BOOK_INFO_ID is '書籍情報ID';
comment on column READING_RECORD.ACCOUNT_ID is 'アカウントID';
comment on column READING_RECORD.CREATED_AT is '登録日時';
comment on column READING_RECORD.UPDATE_AT is '更新日時';
comment on column READING_RECORD.VERSION is 'バージョン';
comment on column READING_RECORD.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table PROCESS_TYPE_MASTER is '処理種別マスタテーブル 処理種別マスタテーブル';
comment on column PROCESS_TYPE_MASTER.ID is 'ID';
comment on column PROCESS_TYPE_MASTER.PROCESS_TYPE_NAME is '処理種別名';
comment on column PROCESS_TYPE_MASTER.CREATED_AT is '登録日時';
comment on column PROCESS_TYPE_MASTER.UPDATE_AT is '更新日時';
comment on column PROCESS_TYPE_MASTER.VERSION is 'バージョン';
comment on column PROCESS_TYPE_MASTER.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table BOOK_STATUS_HISTORY is '書籍状態履歴テーブル 書籍操作履歴テーブル';
comment on column BOOK_STATUS_HISTORY.ID is 'ID';
comment on column BOOK_STATUS_HISTORY.PROCESS_TYPE_MASTER_ID is '処理種別マスタID';
comment on column BOOK_STATUS_HISTORY.BOOK_ID is '書籍ID';
comment on column BOOK_STATUS_HISTORY.BOOK_INFO_ID is '書籍情報ID';
comment on column BOOK_STATUS_HISTORY.CREATED_AT is '登録日時';
comment on column BOOK_STATUS_HISTORY.UPDATE_AT is '更新日時';
comment on column BOOK_STATUS_HISTORY.VERSION is 'バージョン';
comment on column BOOK_STATUS_HISTORY.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table RENTAL_INFO is '貸出情報テーブル 貸出情報テーブル';
comment on column RENTAL_INFO.ID is 'ID';
comment on column RENTAL_INFO.BOOK_ID is '書籍ID';
comment on column RENTAL_INFO.ACCOUNT_ID is 'アカウントID';
comment on column RENTAL_INFO.RENTAL_DATE is 'レンタル日';
comment on column RENTAL_INFO.RETURN_DUE_DATE is '返却予定日';
comment on column RENTAL_INFO.RETURN_DATE is '返却日';
comment on column RENTAL_INFO.CREATED_AT is '登録日時';
comment on column RENTAL_INFO.UPDATE_AT is '更新日時';
comment on column RENTAL_INFO.VERSION is 'バージョン';
comment on column RENTAL_INFO.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table BOOK is '書籍テーブル 書籍テーブル';
comment on column BOOK.ID is 'ID';
comment on column BOOK.BOOK_INFO_ID is '書籍情報ID';
comment on column BOOK.BOOK_STATUS_MASTER_ID is '書籍状態マスタID';
comment on column BOOK.CREATED_AT is '登録日時';
comment on column BOOK.UPDATE_AT is '更新日時';
comment on column BOOK.VERSION is 'バージョン';
comment on column BOOK.UPDATE_ACCOUNT_ID is '更新アカウントID';
comment on table BOOK_INFO is '書籍情報テーブル 書籍情報テーブル';
comment on column BOOK_INFO.ID is 'ID';
comment on column BOOK_INFO.BOOK_NAME is '書籍名';
comment on column BOOK_INFO.AUTHOR is '著者';
comment on column BOOK_INFO.ISBN is 'ISBN';
comment on column BOOK_INFO.PUBLISHED_DATE is '発行年月';
comment on column BOOK_INFO.CREATED_AT is '登録日時';
comment on column BOOK_INFO.UPDATE_AT is '更新日時';
comment on column BOOK_INFO.VERSION is 'バージョン';
comment on column BOOK_INFO.UPDATE_ACCOUNT_ID is '更新アカウントID';
<file_sep>package jp.co.scsac.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import jp.co.scsac.entity.Book;
import jp.co.scsac.entity.RentalInfo;
public interface RentalInfoRepository extends PagingAndSortingRepository<RentalInfo, Integer> {
}
<file_sep>package jp.co.scsac.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.sql.Timestamp;
import java.util.List;
import jp.co.scsac.entity.Book;
/**
* The persistent class for the book_info database table.
*
*/
@Entity
@Table(name = "book_info")
public class BookInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Integer id;
private String author;
@Column(name = "book_name")
private String bookName;
@Column(name = "created_at")
private Timestamp createdAt;
private Integer isbn;
@Temporal(TemporalType.DATE)
@Column(name = "published_date")
private Date publishedDate;
@Column(name = "update_account_id")
private String updateAccountId;
@Column(name = "update_at")
private Timestamp updateAt;
private Integer version;
// bi-directional many-to-one association to BookTag
@OneToMany(mappedBy = "bookInfo")
private List<BookTag> bookTags;
// bi-directional many-to-one association to Book
@OneToMany(mappedBy = "bookInfo")
private List<Book> books;
// bi-directional many-to-one association to RecommendedRecord
@OneToMany(mappedBy = "bookInfo")
private List<RecommendedRecord> recommendedRecords;
// bi-directional many-to-one association to ReadingRecord
@OneToMany(mappedBy = "bookInfo")
private List<ReadingRecord> readingRecords;
// bi-directional many-to-one association to BookStatusHistory
@OneToMany(mappedBy = "bookInfo")
private List<BookStatusHistory> bookStatusHistories;
public BookInfo() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBookName() {
return this.bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Timestamp getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public Integer getIsbn() {
return this.isbn;
}
public void setIsbn(Integer isbn) {
this.isbn = isbn;
}
public Date getPublishedDate() {
return this.publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public String getUpdateAccountId() {
return this.updateAccountId;
}
public void setUpdateAccountId(String updateAccountId) {
this.updateAccountId = updateAccountId;
}
public Timestamp getUpdateAt() {
return this.updateAt;
}
public void setUpdateAt(Timestamp updateAt) {
this.updateAt = updateAt;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
public List<BookTag> getBookTags() {
return this.bookTags;
}
public void setBookTags(List<BookTag> bookTags) {
this.bookTags = bookTags;
}
public BookTag addBookTag(BookTag bookTag) {
getBookTags().add(bookTag);
bookTag.setBookInfo(this);
return bookTag;
}
public BookTag removeBookTag(BookTag bookTag) {
getBookTags().remove(bookTag);
bookTag.setBookInfo(null);
return bookTag;
}
public List<Book> getBooks() {
return this.books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public Book addBook(Book book) {
getBooks().add(book);
book.setBookInfo(this);
return book;
}
public Book removeBook(Book book) {
getBooks().remove(book);
book.setBookInfo(null);
return book;
}
public List<RecommendedRecord> getRecommendedRecords() {
return this.recommendedRecords;
}
public void setRecommendedRecords(List<RecommendedRecord> recommendedRecords) {
this.recommendedRecords = recommendedRecords;
}
public RecommendedRecord addRecommendedRecord(RecommendedRecord recommendedRecord) {
getRecommendedRecords().add(recommendedRecord);
recommendedRecord.setBookInfo(this);
return recommendedRecord;
}
public RecommendedRecord removeRecommendedRecord(RecommendedRecord recommendedRecord) {
getRecommendedRecords().remove(recommendedRecord);
recommendedRecord.setBookInfo(null);
return recommendedRecord;
}
public List<ReadingRecord> getReadingRecords() {
return this.readingRecords;
}
public void setReadingRecords(List<ReadingRecord> readingRecords) {
this.readingRecords = readingRecords;
}
public ReadingRecord addReadingRecord(ReadingRecord readingRecord) {
getReadingRecords().add(readingRecord);
readingRecord.setBookInfo(this);
return readingRecord;
}
public ReadingRecord removeReadingRecord(ReadingRecord readingRecord) {
getReadingRecords().remove(readingRecord);
readingRecord.setBookInfo(null);
return readingRecord;
}
public List<BookStatusHistory> getBookStatusHistories() {
return this.bookStatusHistories;
}
public void setBookStatusHistories(List<BookStatusHistory> bookStatusHistories) {
this.bookStatusHistories = bookStatusHistories;
}
public BookStatusHistory addBookStatusHistory(BookStatusHistory bookStatusHistory) {
getBookStatusHistories().add(bookStatusHistory);
bookStatusHistory.setBookInfo(this);
return bookStatusHistory;
}
public BookStatusHistory removeBookStatusHistory(BookStatusHistory bookStatusHistory) {
getBookStatusHistories().remove(bookStatusHistory);
bookStatusHistory.setBookInfo(null);
return bookStatusHistory;
}
}<file_sep>resourcePrototype
===============
<file_sep>package jp.co.scsac.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import jp.co.scsac.entity.Book;
public interface BookRepository extends PagingAndSortingRepository<Book, Integer> {
}
<file_sep>package jp.co.scsac.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import jp.co.scsac.entity.TagNameManagement;
public interface TagNameManagementRepository extends PagingAndSortingRepository<TagNameManagement, Integer> {
}
<file_sep>package jp.co.scsac.entity;
import java.io.Serializable;
import javax.persistence.*;
import jp.co.scsac.entity.Book;
import java.util.Date;
import java.sql.Timestamp;
/**
* The persistent class for the rental_info database table.
*
*/
@Entity
@Table(name="rental_info")
/*@NamedQuery(name="RentalInfo.findAll", query="SELECT r FROM RentalInfo r")*/
public class RentalInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Integer id;
@Column(name="account_id")
private String accountId;
@Column(name="created_at")
private Timestamp createdAt;
@Temporal(TemporalType.DATE)
@Column(name="rental_date")
private Date rentalDate;
@Temporal(TemporalType.DATE)
@Column(name="return_date")
private Date returnDate;
@Temporal(TemporalType.DATE)
@Column(name="return_due_date")
private Date returnDueDate;
@Column(name="update_account_id")
private String updateAccountId;
@Column(name="update_at")
private Timestamp updateAt;
private Integer version;
//bi-directional many-to-one association to Book
@ManyToOne
@JoinColumn(name="book_id")
private Book book;
public RentalInfo() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccountId() {
return this.accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public Timestamp getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public Date getRentalDate() {
return this.rentalDate;
}
public void setRentalDate(Date rentalDate) {
this.rentalDate = rentalDate;
}
public Date getReturnDate() {
return this.returnDate;
}
public void setReturnDate(Date returnDate) {
this.returnDate = returnDate;
}
public Date getReturnDueDate() {
return this.returnDueDate;
}
public void setReturnDueDate(Date returnDueDate) {
this.returnDueDate = returnDueDate;
}
public String getUpdateAccountId() {
return this.updateAccountId;
}
public void setUpdateAccountId(String updateAccountId) {
this.updateAccountId = updateAccountId;
}
public Timestamp getUpdateAt() {
return this.updateAt;
}
public void setUpdateAt(Timestamp updateAt) {
this.updateAt = updateAt;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
public Book getBook() {
return this.book;
}
public void setBook(Book book) {
this.book = book;
}
} | e94bc3c06a25ddd771c156f497fd823ce72a6642 | [
"Markdown",
"Java",
"SQL",
"INI"
]
| 10 | Java | sha-dev/spring-jpa-rest_test | 69fb7733d972af81fc3730083519bda28defd387 | 36c5e9497972909a61bff6a1a3ce339b74939541 |
refs/heads/master | <file_sep>package com.example.wall_i.utils
object Constants {
const val baseUrl = "https://pixabay.com/"
const val apiKey = "11809334-b8b2b529a4dd728dc8663833a"
}<file_sep>package com.example.wall_i.data.api
import com.example.wall_i.utils.Constants
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ServiceBuilder {
operator fun invoke(): PixBayInterface {
return Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(GsonConverterFactory.create()).build()
.create(PixBayInterface::class.java)
}
}<file_sep>package com.example.wall_i.view.favoriteScreen
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.wall_i.R
import com.example.wall_i.model.ListDataModel
import kotlinx.android.synthetic.main.activity_favorite_screen.*
class FavoriteScreen : AppCompatActivity(),onObjClicked{
private lateinit var Fadapter: FavoriteListAdapter
val col=2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_favorite_screen)
initRecyclerView()
}
fun initRecyclerView(){
FavRecyclerView.apply {
TODO("do after database is working")
layoutManager=StaggeredGridLayoutManager(col,1)
// var Data = DataSource.createDataSet(initListView(response.body()!!.imageList))
// Fadapter = FavoriteListAdapter(data,click)
// adapter = fadapter
}
}
override fun onfavClicked(data: ListDataModel, I: Int) {
TODO("do after database is working")
}
}
<file_sep>package com.example.wall_i.view.ListingScreen
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.wall_i.R
import com.example.wall_i.model.ListDataModel
import kotlinx.android.synthetic.main.list_model.view.*
class ListAdapter(var items:ArrayList<ListDataModel>,var click:onItemClick): RecyclerView.Adapter<ListAdapter.ListViewHolder>() {
class ListViewHolder(view: View):RecyclerView.ViewHolder(view){
var mImage=view.Images
fun bind(model:ListDataModel,DataClick:onItemClick){
var requestoptions= RequestOptions()
.placeholder(R.drawable.ic_launcher_foreground)
.error(R.drawable.ic_launcher_background)
Glide.with(itemView.context)
.applyDefaultRequestOptions(requestoptions)
.load(model.img)
.into(mImage)
itemView.setOnClickListener {
DataClick.onclick(model,absoluteAdapterPosition)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder =
ListViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_model,parent,false)
)
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.bind(items.get(position),click)
}
}
interface onItemClick{
fun onclick(data:ListDataModel,I: Int)
}<file_sep>package com.example.wall_i.data.api
import ImageListResponse
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface PixBayInterface {
@GET("api/")
fun getAllImages(@Query("key") key: String, @Query("q") q: String): Call<ImageListResponse>
}<file_sep>rootProject.name='Wall-i'
include ':app'
<file_sep>package com.example.wall_i.view.favoriteScreen
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.wall_i.R
import com.example.wall_i.model.ListDataModel
import kotlinx.android.synthetic.main.list_model.view.*
class FavoriteListAdapter(var items:ArrayList<ListDataModel>,var clickfav: onObjClicked):
RecyclerView.Adapter<FavoriteListAdapter.FavListViewHolder>() {
class FavListViewHolder(view : View):RecyclerView.ViewHolder(view){
private var favImg=view.Images
fun bindFav(model:ListDataModel,clicked:onObjClicked){
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavListViewHolder=
FavListViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_model,parent,false)
)
override fun getItemCount(): Int=items.size
override fun onBindViewHolder(holder: FavListViewHolder, position: Int) {
holder.bindFav(items.get(position),clickfav)
}
}
interface onObjClicked{
fun onfavClicked(data:ListDataModel,I :Int)
}<file_sep>package com.example.wall_i.view
import android.content.Intent
import android.os.Bundle
import android.view.WindowManager
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import com.example.wall_i.R
import com.example.wall_i.view.ListingScreen.ResultListingScreen
import kotlinx.android.synthetic.main.activity_search.*
class SearchActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setCustomView(R.layout.custom_toolbar)
searchEditText?.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_SEND) {
if (searchEditText.text.toString().isNotBlank() || searchEditText.text.toString()
.isNotEmpty()
) openActivity(searchEditText.text.toString())
true
} else {
if (searchEditText.text.toString().isNotBlank() || searchEditText.text.toString()
.isNotEmpty()
) {
Toast.makeText(
this, "else" + searchEditText.text.toString(), Toast.LENGTH_SHORT
).show()
openActivity(searchEditText.text.toString())
}
false
}
}
}
private fun openActivity(searchedText: String) {
val intent = Intent(this, ResultListingScreen::class.java)
intent.putExtra("image", searchedText)
startActivity(intent)
}
}<file_sep>
package com.example.wall_i.view.PreviewScreen
import android.Manifest
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.core.net.toUri
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.wall_i.R
import kotlinx.android.synthetic.main.activity_preview.*
class Preview : AppCompatActivity() {
private val STORAGE_PERMISSION_CODE: Int = 1000
// var url:Uri
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_preview)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setCustomView(R.layout.custom_toolbar)
download.setOnClickListener {
checkPermission()
}
share.setOnClickListener {
onShareButtonClicked(intent.getStringExtra("image"))
}
var requestoptions = RequestOptions()
.placeholder(R.drawable.ic_launcher_foreground)
.error(R.drawable.ic_launcher_background)
Glide.with(this)
.applyDefaultRequestOptions(requestoptions)
.load(intent.getStringExtra("image"))
.into(preview)
}
private fun startDownloading() {
val request = DownloadManager.Request(Uri.parse(intent.getStringExtra("image")))
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
request.setTitle("Downloading")
request.setDescription("Image is being downloaded")
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,"${System.currentTimeMillis()}".plus(".jpg"))
Log.d("Myapp","${System.currentTimeMillis()}")
val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
manager.enqueue(request)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode) {
STORAGE_PERMISSION_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission is granted , start downloading
startDownloading()
} else {
//permission denied, show error
Toast.makeText(this, "Storage Permission is Required", Toast.LENGTH_SHORT)
.show()
}
}
}
}
fun favbuttonClicked(view: View) {
favorite.setImageResource(R.drawable.ic_favorite_black_24dp)
//add the image into database
}
fun checkPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission is denied , Request it back
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), STORAGE_PERMISSION_CODE)
} else {
//permission already granted start downloading
startDownloading()
}
} else {
//system os is less than marshmallo, runtime permission is not required , just start downloading
startDownloading()
}
}
fun onShareButtonClicked(link:String){
var shareIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "Hey Check this awsome image\n".plus(link))
//this.`package`="com.whatsapp"
type = "image/plain"
flags=Intent.FLAG_GRANT_READ_URI_PERMISSION
flags=Intent.FLAG_GRANT_WRITE_URI_PERMISSION
}
startActivity(Intent.createChooser(shareIntent, resources.getText(R.string.share)))
}
}
<file_sep>package com.example.wall_i.model
data class ListDataModel(var img:String)<file_sep>package com.example.wall_i.data
import com.example.wall_i.model.ListDataModel
class DataSource {
//Store the Data from the Api here and the use it EveryWhere
companion object {
fun createDataSet(list:ArrayList<ListDataModel>): ArrayList<ListDataModel> {
var createData= ArrayList<ListDataModel>()
createData.addAll(list)
return createData
}
}
}<file_sep>import com.example.wall_i.model.ImageResponse
import com.google.gson.annotations.SerializedName
data class ImageListResponse(
@SerializedName("total") val total: Int,
@SerializedName("totalHits") val totalHits: Int,
@SerializedName("hits") val imageList: List<ImageResponse>
)<file_sep>package com.example.wall_i.view.ListingScreen
import ImageListResponse
import com.example.wall_i.model.ImageResponse
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.ActionBar
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.wall_i.data.DataSource
import com.example.wall_i.R
import com.example.wall_i.data.api.ServiceBuilder
import com.example.wall_i.model.ListDataModel
import com.example.wall_i.utils.Constants
import com.example.wall_i.view.PreviewScreen.Preview
import kotlinx.android.synthetic.main.activity_result_listing_screen.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class ResultListingScreen : AppCompatActivity(),onItemClick {
private lateinit var Ladapter: ListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_result_listing_screen)
supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
supportActionBar?.setCustomView(R.layout.custom_toolbar)
val imageSearched = intent.getStringExtra("image")!!
val request = ServiceBuilder.invoke()
val call = request.getAllImages(Constants.apiKey, imageSearched)
call.enqueue(object : Callback<ImageListResponse> {
override fun onResponse(
call: Call<ImageListResponse>,
response: Response<ImageListResponse>
) {
if (response.isSuccessful) {
Toast.makeText(
this@ResultListingScreen,
" LINK " + response.body()!!.imageList[0].id.toString(),
Toast.LENGTH_LONG
).show()
ListRecyclerView.apply {
layoutManager = StaggeredGridLayoutManager(3, 1)
var data = DataSource.createDataSet(initListView(response.body()!!.imageList))
Ladapter = ListAdapter(data, this@ResultListingScreen)
adapter = Ladapter
}
}
}
override fun onFailure(call: Call<ImageListResponse>, t: Throwable) {
Toast.makeText(this@ResultListingScreen, "${t.message}", Toast.LENGTH_LONG).show()
}
})
}
override fun onclick(data: ListDataModel, I: Int) {
var intent= Intent(this,Preview::class.java)
intent.putExtra("image",data.img)
startActivity(intent)
}
fun initListView(imgLst: List<ImageResponse>):ArrayList<ListDataModel>{
var list=ArrayList<ListDataModel>()
for (i in imgLst){
list.add(ListDataModel(i.webFormatURL))
}
return list
}
}
| 6e07c78a9d671174a14199cdca869d4ff5745666 | [
"Kotlin",
"Gradle"
]
| 13 | Kotlin | Abhishek38/Wallpaper | f5a01071a0dc2e97952b44d1f71ffcd0230f25ca | bf47ba3b7af274fb23ca56d063940b1ea03897fa |
refs/heads/master | <repo_name>radoslawglowacki/hangman-python<file_sep>/hangman.py
import random as random
import file_reader as file_reader
IS_RUNNING = True
TRIES = 6
FILE_WITH_WORDS = "countries-and-capitals.txt"
list_of_words = file_reader.read_file_to_list(FILE_WITH_WORDS)
def preparing_word_to_answer():
underscores = []
chosen_word = list_of_words[random.randint(0, len(list_of_words) - 1)]
for i in range(len(chosen_word)):
underscores.append("_")
return chosen_word, underscores
def check_if_letter_exist(user_input, chosen_word, underscores):
global TRIES
chosen_word = list(chosen_word)
if user_input in chosen_word:
index_of_char = []
for i in range(len(chosen_word)):
if chosen_word[i] == user_input:
index_of_char.append(i)
for item in index_of_char:
underscores[item] = chosen_word[item]
else:
TRIES -= 1
def check_game_status(chosen_word, underscores):
if TRIES >= 1:
if list(chosen_word) == underscores:
print("\n")
print("Correct word was: " + chosen_word)
print("You win!")
return False
else:
return True
else:
print("\n")
print("Correct word was: " + chosen_word)
print("You loose")
return False
def main_game(is_running):
chosen_word, underscores = preparing_word_to_answer()
print("Welcome to simply Hangman!")
print("Category of words are capitals of countries")
while is_running:
print(f"""
Tries left: {str(TRIES)}
""")
underscores_to_print = " ".join([str(elem) for elem in underscores])
print(underscores_to_print)
print("\n")
user_input = input('Please give me your guess: ')
check_if_letter_exist(user_input, chosen_word, underscores)
is_running = check_game_status(chosen_word, underscores)
main_game(IS_RUNNING)
<file_sep>/file_reader.py
def read_file_to_list(filename):
list_with_words = []
with open(filename, "r") as file:
reader = file.read().split("\n")
for word in reader:
list_with_words.append(word)
list_with_words.remove(list_with_words[-1])
return list_with_words
| b9736f27c81f89ec829e310fed63471e463da936 | [
"Python"
]
| 2 | Python | radoslawglowacki/hangman-python | ccb154995a2b971c61c158be66ae10275152d353 | 3b5e57283eef4d4c694e896dc82c2b6764c1038f |
refs/heads/master | <file_sep>(function() {
'use strict';
window._ = {};
// Returns whatever value is passed as the argument. This function doesn't
// seem very useful, but remember it--if a function needs to provide an
// iterator when the user does not pass one in, this will be handy.
_.identity = function(val) {
//not sure if trap?
return val;
};
/**
* COLLECTIONS
* ===========
*
* In this section, we'll have a look at functions that operate on collections
* of values; in JavaScript, a 'collection' is something that can contain a
* number of values--either an array or an object.
*
*
* IMPORTANT NOTE!
* ===========
*
* The .first function is implemented for you, to help guide you toward success
* in your work on the following functions. Whenever you see a portion of the
* assignment pre-completed, be sure to read and understanding it fully before
* you proceed. Skipping this step will lead to considerably more difficulty
* implementing the sections you are responsible for.
*/
// Return an array of the first n elements of an array. If n is undefined,
// return just the first element.
_.first = function(array, n) {
return n === undefined ? array[0] : array.slice(0, n);
};
// Like first, but for the last elements. If n is undefined, return just the
// last element.
_.last = function(array, n) {
//first, let's check to see if "n" is undefined
if(n === undefined) {
//if "n" is indeed undefined, we want to return the last element of the array that is being passed. no matter how many elements are in this array, using "[array.length - 1]" will give us the very last element
return array[array.length - 1];
//we reach the "else if" block if "n" has a value other than "undefined". now "else if" will evaluate whether or not "n" is larger than the length of the array being passed
} else if(n > array.length) {
//since "n" is larger than the length of the array, we will return all of the elements of the array
return array;
//we reach the following "else" block if "n" has a value that is not "undefined" AND if that value is smaller than the array's length
} else {
//now, we want to return the last n elements of the array. using the ".slice" array method returns a new array of elements based on the arguments we give it, with the first argument as our starting point and the second argument as our ending point
return array.slice(array.length - n, array.length);
}
};
// Call iterator(value, key, collection) for each element of collection.
// Accepts both arrays and objects.
//
// Note: _.each does not have a return value, but rather simply runs the
// iterator function over each item in the input collection.
_.each = function(collection, iterator) {
//first, let's check if the collection passed as an argument is an array
if(Array.isArray(collection) === true) {
//if it is an array, we'll use a "for" loop to iterate from the first to last index in the given collection
for(var i = 0; i < collection.length; i++) {
//here, we're calling the iterator function with the value, index, and collection
iterator(collection[i], i, collection);
}
//if our collection doesn't pass our first condition, let's then check to see if it's an object using "typeof"
} else if(typeof collection === "object") {
//if it is an object, let's use a "for-in" loop to iterate through each key in the collection
for(var key in collection) {
//here, we're calling the iterator function with the value, key, and collection
iterator(collection[key], key, collection);
}
}
};
// Returns the index at which value can be found in the array, or -1 if value
// is not present in the array.
_.indexOf = function(array, target){
// TIP: Here's an example of a function that needs to iterate, which we've
// implemented for you. Instead of using a standard `for` loop, though,
// it uses the iteration helper `each`, which you will need to write.
var result = -1;
_.each(array, function(item, index) {
if (item === target && result === -1) {
result = index;
}
});
return result;
};
// Return all elements of an array that pass a truth test.
_.filter = function(collection, test) {
//first we need to create an empty array for our results that pass the truth test
var filterArr = [];
//next, let's use "each" to iterate through the collection that will be passed in as an argument
_.each(collection, function(value) {
//"each" will also take in a truth test function as an argument. if the value does pass the truth test...
if(test(value)) {
//add that value to "filterArr"
filterArr.push(value);
}
});
//once we have iterated through our entire collection, "filterArr" will be populated with each value that has passed our given truth test
return filterArr;
};
// Return all elements of an array that don't pass a truth test.
_.reject = function(collection, test) {
// TIP: see if you can re-use _.filter() here, without simply
// copying code in and modifying it
//create a variable called "rejectArr" which will store the results of our filter function
var rejectArr = _.filter(collection, function(value) {
//our filter function performs a truth test on the value at the current iteration, but the parent function "_.reject" is only interested in the values that DON'T pass that truth test
if(!test(value)) {
//if the current value does NOT pass the truth test, return the current value (which will then be stored into the array called "rejectArr")
return value;
}
});
//here, we return the results of our array
return rejectArr;
};
// Produce a duplicate-free version of the array.
_.uniq = function(array) {
//first, let's sort the array so that we can bunch all duplicate values next to each other
array.sort();
//we'll create an empty array in which we will push our unique results
var uniqArr = [];
//we'll create a variable called "duplicateCheck" that has no value yet. we'll use this variable to check against the value of the current iteration
var duplicateCheck;
//we'll iterate through the given array using "_.each". our goal is to compare the current iteration's value with our duplicateCheck variable
_.each(array, function(value) {
//here, we'll check to see if the current value is NOT equal to our value stored in "duplicateCheck". if these two values don't match, we have discovered that the current value is, indeed, a unique value
if(value !== duplicateCheck) {
//since we've found a unique value, we'll populate our "uniqArr" with the current value
uniqArr.push(value);
//now that we've stored that value in "uniqArray", we'll set our "duplicateCheck" variable to this current value. this is crucial because now that we have the current value in our new array, we want to establish that any value in future iteration's should not be pushed into the new array
duplicateCheck = value;
}
});
//lastly, we'll return the results of our newly-populated "uniqArr"
return uniqArr;
};
// Return the results of applying an iterator to each element.
_.map = function(collection, iterator) {
// map() is a useful primitive iteration function that works a lot
// like each(), but in addition to running the operation on all
// the members, it also maintains an array of results.
//first, we need to create an empty array for our results
var mapResults = [];
//then, we'll use _.each to iterate through the collection that is passed in to our _.map function
_.each(collection, function(value, index, collection) {
//our iterator is a function that will transform all of the original values in our collection. the results of the iterator will be pushed into our "mapResults" array
mapResults.push(iterator(value));
});
//once we have iterated through our entire collection and our "mapResults" array has been populated, we will return our results in the new array
return mapResults;
};
/*
* TIP: map is really handy when you want to transform an array of
* values into a new array of values. _.pluck() is solved for you
* as an example of this.
*/
// Takes an array of objects and returns and array of the values of
// a certain property in it. E.g. take an array of people and return
// an array of just their ages
_.pluck = function(collection, key) {
// TIP: map is really handy when you want to transform an array of
// values into a new array of values. _.pluck() is solved for you
// as an example of this.
return _.map(collection, function(item){
return item[key];
});
};
// Reduces an array or object to a single value by repetitively calling
// iterator(accumulator, item) for each item. accumulator should be
// the return value of the previous iterator call.
//
// You can pass in a starting value for the accumulator as the third argument
// to reduce. If no starting value is passed, the first element is used as
// the accumulator, and is never passed to the iterator. In other words, in
// the case where a starting value is not passed, the iterator is not invoked
// until the second element, with the first element as it's second argument.
//
// Example:
// var numbers = [1,2,3];
// var sum = _.reduce(numbers, function(total, number){
// return total + number;
// }, 0); // should be 6
//
// var identity = _.reduce([5], function(total, number){
// return total + number * number;
// }); // should be 5, regardless of the iterator function passed in
// No accumulator is given so the first element is used.
_.reduce = function(collection, iterator, accumulator) {
//using _.each, we will iterate through the collection being passed into _.reduce
_.each(collection, function(value) {
//if a starting value is passed as our "accumulator", we know that it won't be an undefined value
if(accumulator !== undefined) {
//accumulator is our starting value. the iterator then takes in the accumulator and the current iteration's value and does some sort of action to them. once that iteration is complete, the accumulator (on the left side of the "=") is updated, and the iterator function runs again until the entire collection has been iterated through
accumulator = iterator(accumulator, value);
//else, we know that no starting value was passed as our "accumulator" in the first place. that value will be interpreted as "undefined" and skip over our "if" on the first iteration
} else {
//since no starting value was passed, the first value is used as the accumulator
accumulator = value;
//now that the accumulator is set to a value that will evaluate to NOT(!) "undefined", all following iterations will perform its action inside of the "if" block
}
});
//we need to return the accumulator outside of the _.each function in order to retrieve the results of our _.reduce function
return accumulator;
};
// Determine if the array or object contains a given value (using `===`).
_.contains = function(collection, target) {
// TIP: Many iteration problems can be most easily expressed in
// terms of reduce(). Here's a freebie to demonstrate!
return _.reduce(collection, function(wasFound, item) {
if (wasFound) {
return true;
}
return item === target;
}, false);
};
// Determine whether all of the elements match a truth test.
_.every = function(collection, iterator) {
// TIP: Try re-using reduce() here.
//we'll use reduce to try to narrow down our entire list of values to just one "true" or "false" value at the very end. _.reduce takes in a list and iteratee as paramaters. since, by default, we want it to pass for an empty collection, our starting value will be "true"
return _.reduce(collection, function(list,iteratee) {
//our "if" statement will iterate through our list and check to see if every element in that list is a "true" value. by using "!list" as our conditional, we're saying that if the current iteration's element is not a true value, to return "false"
if(!list) {
return false;
//our first "else-if" statement checks to see if we have an iterator function being passed in as an argument. if there is an iterator being passed, iterator will have a definitive value.
} else if (iterator !== undefined) {
//we can use the Boolean function to evaluate whether or not the expression inside of its parentheses is a true or false value. our "iterator" is our truth test and our "iteratee" is the element in the list that is being checked. based on the results, we'll return a Boolean value.
return Boolean(iterator(iteratee));
//our second "else-if" statement checks to see if no iterator has been passed into _.every. if no function is passed through, the iterator's value will be undefined.
} else if (iterator === undefined) {
//since we have no "iterator", but we want _.every to work even with no callback function provided, we can use our Boolean function to evaluate the "iteratee"
return Boolean(iteratee);
}
//"true" indicate the starting value in _.reduce. we want to start with true in the event that there is an empty collection passed into the function
}, true);
};
// Determine whether any of the elements pass a truth test. If no iterator is
// provided, provide a default one
_.some = function(collection, iterator) {
// TIP: There's a very clever way to re-use every() here.
//console.log("COLLECTIONS ARE ARRAYS: ",collection);
//console.log("ITERATORS ARE FUNCTIONS/UNDEFINED: ",iterator);
// console.log("ARGUMENTS: ", arguments);
// return _.every(collection, function(somethingCool) {
// console.log("COLLECTION IN EVERY: ",collection);
// // console.log("COOL: ",somethingCool);
if(collection.length === 0) {
return false;
} else if(iterator!== undefined) {
return !_.every(collection, function(secretUnicornPowers) {
return !iterator(secretUnicornPowers);
});
} else if(iterator === undefined) {
//do something here? i may have scope issues with my _.every statement, but this passes the most tests for now.
}
};
/**
* OBJECTS
* =======
*
* In this section, we'll look at a couple of helpers for merging objects.
*/
// Extend a given object with all the properties of the passed in
// object(s).
//
// Example:
// var obj1 = {key1: "something"};
// _.extend(obj1, {
// key2: "something new",
// key3: "something else new"
// }, {
// bla: "even more stuff"
// }); // obj1 now contains key1, key2, key3 and bla
_.extend = function(obj,x,y) {
//since _.extend takes in an object and other properties as arguments, and the "arguments" keyword returns an array, we can use _.each to iterate through the arguments array. the value parameter ("obj2") of each will be another object which has the properties we want to merge with our original object ("obj")
_.each(arguments, function(obj2) {
//we want to gain access to "obj2"s key:value pairs because we want to take those properties and add them onto our original object ("obj"). in order to do that, we'll nest another _.each and set our parameters to "value" and "key"
_.each(obj2, function(value, key) {
//now, we can dynamically add our key:value pairs to "obj" using bracket notation.
obj[key] = value;
});
});
//lastly, we'll return "obj" outside of _.each so we can access our updated object
return obj;
};
// Like extend, but doesn't ever overwrite a key that already
// exists in obj
_.defaults = function(obj) {
//since _.defaults works similarly to _.extend, we can use _.each and the "arguments" keyword to iterate through our second object that's passed into _.defaults
_.each(arguments, function(obj2) {
//we'll nest another _.each function in order to gain access to "obj2"s keys. what we want to do is compare obj's keys to obj2's keys to see if there are any duplicates
_.each(obj2, function(value, key) {
//if there are duplicates, we don't want any action to happen. where we do want the action to happen, though, is when we discover a key in obj2 that doesn't exist in our original obj. we can do this by checking to see if "obj[key]" is undefined
if(obj[key] === undefined) {
//now that we know there is a key that exists in obj2 that doesn't exist in our original obj, we can dynamically add that key:value pair to "obj"
obj[key] = value;
}
})
})
//lastly, we return obj which has our new properties
return obj;
};
/**
* FUNCTIONS
* =========
*
* Now we're getting into function decorators, which take in any function
* and return out a new version of the function that works somewhat differently
*/
// Return a function that can be called at most one time. Subsequent calls
// should return the previously returned value.
_.once = function(func) {
// TIP: These variables are stored in a "closure scope" (worth researching),
// so that they'll remain available to the newly-generated function every
// time it's called.
var alreadyCalled = false;
var result;
// TIP: We'll return a new function that delegates to the old one, but only
// if it hasn't been called before.
return function() {
if (!alreadyCalled) {
// TIP: .apply(this, arguments) is the standard way to pass on all of the
// infromation from one function call to another.
result = func.apply(this, arguments);
alreadyCalled = true;
}
// The new function always returns the originally computed result.
return result;
};
};
// Memorize an expensive function's results by storing them. You may assume
// that the function takes only one argument and that it is a primitive.
// memoize could be renamed to oncePerUniqueArgumentList; memoize does the
// same thing as once, but based on many sets of unique arguments.
//
// _.memoize should return a function that, when called, will check if it has
// already computed the result for the given argument and return that value
// instead if possible.
_.memoize = function(func) {
//all tests:
//should produce the same result as the non-memoized version
//should give different results for different arguments
//should not run the memoized function twice for any given set of arguments
//_.memoize takes in a callback function as an argument
//the callback function takes in one primitive argument itself
//if the callback function has been previous called with the arguments that it is being currently passed, retrieve the results from memory and do NOT invoke the callback function
//else if the current arguments have not been previously been passed into the callback function, invoke the function with these arguments
//GOAL: find out if we've done the work already and re-use that answer instead of invoking the function.
var memory = [];
return function() {
//need to refactor this to not use hard-coding
if(memory[0] !== func.apply(this,arguments)) {
memory[0] = func.apply(this, arguments);
return memory[0];
}
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
//
// The arguments for the original function are passed after the wait
// parameter. For example _.delay(someFunction, 500, 'a', 'b') will
// call someFunction('a', 'b') after 500ms
_.delay = function(func, wait) {
//first, we'll create a variable called "optionalArgs" to store the optional arguments that can be passed into "_.delay". since the "arguments" keyword returns only an array-like object, we can't use JS' array methods on it, but we can use the Array.prototype method to access our optional arguments (Array.prototype is itself an array). the number "2" that is pased into our Array.prototype method indicates to JS at which index in our "arguments" array-like object to perform our slice, and can do so because the "arguments" keyword has a ".length" property. now, our variable "optionalArgs" stores the results of the Array.prototype method, and now can be referenced into setTimeout
var optionalArgs = Array.prototype.slice.call(arguments, 2);
//here, we'll pass in "setTimeout" as our callback function to "_.delay". this function also takes in a callback function, and will execute the anonymous function being passed into it after a given amount of time(indicated by the value that the "wait" parameter will be given).
setTimeout(function() {
//using the "apply" method on "func" will allow us to use this function with an array of arguments being passed in, which is what we have stored in our "optionalArgs" variable.
func.apply(this, optionalArgs);
//"wait" will be a numeric value expressed in milliseconds
}, wait)
};
/**
* ADVANCED COLLECTION OPERATIONS
* ==============================
*/
// Randomizes the order of an array's contents.
//
// TIP: This function's test suite will ask that you not modify the original
// input array. For a tip on how to make a copy of an array, see:
// http://mdn.io/Array.prototype.slice
_.shuffle = function(array) {
//tests:
//should not modify the original object
//should have the same elements as the original object
//should not be in the same order as the original object
//PSEUDO CODE:
//_.shuffle takes in an array as an argument
//the original array should not be modified, so we need to copy all of the arrays contents over to a new array
//in the new array, we need to randomly shuffle the elements
//return the new array, with the order of its contents shuffled
//create a variable called "newArr" that is a copy of our original array
var arrCopy = Array.prototype.slice.call(array,0)
//console.log("arrCopy: ", arrCopy);
//maybe we can use Math.random to randomize arrCopy's indices? since given fraction, need to convert to integer
//console.log("RANDOM: ",Math.random())
};
/**
* EXTRA CREDIT
* =================
*
* Note: This is the end of the pre-course curriculum. Feel free to continue,
* but nothing beyond here is required.
*/
// Calls the method named by functionOrKey on each value in the list.
// Note: You will need to learn a bit about .apply to complete this.
_.invoke = function(collection, functionOrKey, args) {
};
// Sort the object's values by a criterion produced by an iterator.
// If iterator is a string, sort objects by that property with the name
// of that string. For example, _.sortBy(people, 'name') should sort
// an array of people by their name.
_.sortBy = function(collection, iterator) {
};
// Zip together two or more arrays with elements of the same index
// going together.
//
// Example:
// _.zip(['a','b','c','d'], [1,2,3]) returns [['a',1], ['b',2], ['c',3], ['d',undefined]]
_.zip = function() {
};
// Takes a multidimensional array and converts it to a one-dimensional array.
// The new array should contain all elements of the multidimensional array.
//
// Hint: Use Array.isArray to check if something is an array
_.flatten = function(nestedArray, result) {
};
// Takes an arbitrary number of arrays and produces an array that contains
// every item shared between all the passed-in arrays.
_.intersection = function() {
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. See the Underbar readme for extra details
// on this function.
//
// Note: This is difficult! It may take a while to implement.
_.throttle = function(func, wait) {
};
}());
| 19678da1f64eb25610d3a0cc2566ace12d493e42 | [
"JavaScript"
]
| 1 | JavaScript | alohaglenn/underbar | 7770375dff9d15641aadf512a8f9d20ffdbe72bd | 38f3771580f8186d51e76350aea31eba97100f1b |
refs/heads/main | <repo_name>alpha-oss/HYDRA<file_sep>/gen.py
import string
import random
if __name__ == "__main__":
s1 = string.ascii_lowercase
#print(s1)
s2 = string.ascii_uppercase
#print(s2)
s3 = string.digits
# print(s3)
s4 = string.punctuation
#print(s4)
plen = int(input("Enter the password length:"))
p = []
p.extend(list(s1))
p.extend(list(s2))
p.extend(list(s3))
p.extend(list(s4))
#random.shuffle(p) - this can be one option to generate password
print("YOUR NEW PASSWORD IS :")
#print("".join(p[0:plen]))
#This is another alternative to generate password.
print("".join(random.sample(p,plen)))
<file_sep>/README.md
# HYDRA
-So it is a password generator 🔐 done using python scripts and some basic librarires ,
### TO TRY THIS
-Run this script on cmd terminal 💻 or any other terminal you can generate password for yourself .
| 419e3a812377040945b1603cb35830494d28af1e | [
"Markdown",
"Python"
]
| 2 | Python | alpha-oss/HYDRA | 04d04147b92f85f24f45f1253e38538374760916 | 0b1570aece0bdb926fdfb1a1a1571f417eb1fff8 |
refs/heads/master | <file_sep>
export class EbayCalls {
let
} | 30e07035d9ffc266a08e40655db53c2e80f38497 | [
"JavaScript"
]
| 1 | JavaScript | HarMinas/ProductSearch_Angluar2_Node | 685d397e295918fa264a93691a32728da96b650d | 6aa27975d9b41c0b4a913b851b5f7d163e66ef8c |
refs/heads/master | <repo_name>jeffreyerikson/Jest<file_sep>/jest/src/test/java/io/searchbox/core/IndexIntegrationTest.java
package io.searchbox.core;
import io.searchbox.action.Action;
import io.searchbox.client.JestResult;
import io.searchbox.client.JestResultHandler;
import io.searchbox.common.AbstractIntegrationTest;
import io.searchbox.indices.mapping.PutMapping;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.junit.Test;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
/**
* @author <NAME>
*/
@ElasticsearchIntegrationTest.ClusterScope(scope = ElasticsearchIntegrationTest.Scope.SUITE, numDataNodes = 1)
public class IndexIntegrationTest extends AbstractIntegrationTest {
public static final String INDEX_NAME = "twitter";
public static final String TYPE_NAME = "tweet";
Map<Object, Object> source = new HashMap<Object, Object>();
@Test
public void indexDocumentWithValidParametersAndWithoutSettings() throws IOException {
source.put("user", "searchbox");
JestResult result = client.execute(new Index.Builder(source).index(INDEX_NAME).type(TYPE_NAME).id("1").build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
}
@Test
public void automaticIdGeneration() throws IOException {
source.put("user", "jest");
JestResult result = client.execute(new Index.Builder(source).index(INDEX_NAME).type(TYPE_NAME).build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
}
@Test
public void indexAsynchronously() throws InterruptedException, ExecutionException, IOException {
source.put("user", "jest");
Action action = new Index.Builder(source).index(INDEX_NAME).type(TYPE_NAME).build();
client.executeAsync(action, new JestResultHandler<JestResult>() {
@Override
public void completed(JestResult result) {
assertTrue(result.getErrorMessage(), result.isSucceeded());
}
@Override
public void failed(Exception ex) {
fail("Failed during the running asynchronous call");
}
});
//wait for asynchronous call
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void shouldIndexDateFieldsWithoutFormatConversion() throws Exception {
putMappingAndCheckSuccess();
source.put("user", "searchbox");
source.put("creationDate", new Date());
JestResult result = client.execute(new Index.Builder(source).index(INDEX_NAME).type(TYPE_NAME).id("1").build());
assertTrue(result.getErrorMessage(), result.isSucceeded());
}
private void putMappingAndCheckSuccess() throws IOException {
createIndex(INDEX_NAME);
PutMapping putMapping = new PutMapping.Builder(INDEX_NAME, TYPE_NAME,
"{ \"" + TYPE_NAME + "\" : { \"properties\" : { \"creationDate\" : {\"type\" : \"date\"} } } }"
).build();
JestResult result = client.execute(putMapping);
assertNotNull("Can't put mapping", result);
assertTrue(result.isSucceeded());
}
}
| 1a0c97740e11a7de5c6271023b3d0f37b3458e72 | [
"Java"
]
| 1 | Java | jeffreyerikson/Jest | 06dcef1e2bf52de43205bca98c5b66f1b5b42a4d | 6531a31b2cc174591da940fcef4656b26491c40a |
refs/heads/master | <repo_name>SDIBTACM/2018-Fun-programming-contest<file_sep>/D/program.c
#include <stdio.h>
#include <math.h>
//只有相邻的两个点斜率才可能是最大
double max(double a,double b){return a>b?a:b;}
int main(){
double MaxK,x,y; //当前点
double frontX,frontY; //前一个点
int n;
scanf("%d",&n);
int i;
for(i=0;i<n;i++){
scanf("%lf%lf",&x,&y);
if(i!=0)
MaxK = max(MaxK,(y-frontY)/(x-frontX));
frontX = x;
frontY = y;
}
printf("%.2lf\n",MaxK);
return 0;
}
<file_sep>/E/program.c
#include <stdio.h>
int main(){
long long n, x, y, x2, y2;
scanf("%lld%lld%lld%lld", &x, &y, &x2, &y2);
long long res = (y2 - y + 1) * (x2 - x + 1);
if (res%2 && x%2+y%2 == 1)
res++;
printf("%lld\n", res/2);
return 0;
}
<file_sep>/B/program.c
#include <stdio.h>
#include <math.h>
#define maxn 40020
int cnt[20010];
int a[10001];
int prime[maxn];
int isHaveOne(int n) {
if (cnt[1] == 0)
return 0;
for (int i = 0; i < n; i++)
if (prime[a[i] + 1] == 0 && a[i] != 1)
return cnt[1] + 1;
return cnt[1] == 1 ? 0 : cnt[1];
}
int main() {
prime[1] = 1;
for (int i = 2; i < maxn; i++)
if (!prime[i])
for (int j = i * i; j < maxn; j += i)
prime[j] = 1;
int n;
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
cnt[a[i]]++;
}
int res = isHaveOne(n);
for (int i = 0; res == 0 && i < n; i++)
for (int j = 0; res == 0 && j < i; j++)
if (prime[a[i]+a[j]] == 0)
res = 2;
printf("%d\n", res);
}
return 0;
}
<file_sep>/A/question.md
# Problem A
## Title
苗童大作战之绝地求生
## Description
童童和苗苗最近入坑绝地求生了,这一次她们终于苟到了决赛圈,她们已经把药都用完了,但马上又要跑毒了。
假设她们距离安全区最近的直线距离为 n 米,她们的移动速度为 2 米每秒,她们想知道如果按照这个方式跑到安全区最需要多少秒。
## Input
输入包含一个整数 n (0 < n < 10000), 代表她们到安全区的距离。
## OutPut
输出一个整数,代表需要的最少时间。
## Sample InPut
4
## Sample OutPut
2
## Hint
<file_sep>/C/question.md
# Problem C
## Title
苗童大作战之怪物猎人
## Description
苗苗又开始玩一些游戏,这次是RPG游戏。在游戏中,苗苗接受了一个任务:杀死童童所控制的怪物。怪物具有一定的生命值 h2 和一定的攻击力 a2 。苗苗现在拥有 h1 生命值。 此外,她还有两个技能:
1. 燃烧卡路里(Burn my calories),使用此技能,苗苗将会回复 c1 点生命值。
2. 天马流星拳(Pegasus Ryuseiken),使用此技能,苗苗将会对怪物造成 a1 点伤害。
战斗包括多个回合。在每个回合的开始阶段,苗苗可以使用 技能1 或者 技能2,因为苗苗尚未完全领悟到魔法的精髓,所以每回合她只能释放一次技能 。接下来,如果战斗尚未结束,怪物会攻击苗苗,将会对她的造成 a2 点伤害 。当苗苗(或怪物)的生命值降至 0 或更低时,战斗结束。在苗苗释放技能后,战斗可能会结束。
当然,苗苗想想尽快赢得这场战斗。所以她想制定一个策略:让她以最少的回合数赢得战斗。
策略必须是有效的:在杀死怪物之前,苗苗的生命值必须大于0;并且苗苗在释放最后一次技能后,怪物的生命值必须为0或更低。你可以认为苗苗的技能没有使用次数限制,而且她总能获胜。
你能帮助苗苗制定策略吗?
## Input
第一行包含三个整数h1, a1, c1 (1 ≤ h1, a1 ≤ 100,2 ≤ c1 ≤ 100)
第二行包含两个整数h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 < c1)
## Output
在第一行打印一个整数,代表赢得战斗所需的最少回合数。
然后打印n行。如果苗苗在第i回合使用了技能1,那么第i行输出"Burn my calories!!!!",如果她使用了技能2则输出"Pegasus Ryuseiken!!!!"。
输出不含双引号。如果有多个最佳解决方案,请打印其中任何一个。
## Sample Input
10 6 100
17 5
## Sample Output
4
Pegasus Ryuseiken!!!!
Burn my calories!!!!
Pegasus Ryuseiken!!!!
Pegasus Ryuseiken!!!!
## Sample Input
11 6 100
12 5
## Sample Output
2
Pegasus Ryuseiken!!!!
Pegasus Ryuseiken!!!!
<file_sep>/C/spj.cpp
#include<cstdio>
#include<cstring>
FILE *inf, *outf, *ansf;
int main(int argc, char **argv)
{
inf = fopen(argv[1], "r");//样例输入
ansf = fopen(argv[2], "r");//样例输出
outf = fopen(argv[3], "r");//用户输出
int a1,h1,c1,a2,h2;
fscanf(inf,"%d%d%d%d%d",&h1,&a1,&c1,&h2,&a2);
char ans[100],res[100],a[100]="Pegasus",b[100]="Burn";
int n1,n2;
if(fscanf(outf,"%d",&n1)==NULL)
return 1;
fscanf(ansf,"%d",&n2);
if(n1!=n2)//用户次数与样例不同WA
return 1;
for(int i=0;i<n1;i++)
{
if(fscanf(outf," %s",res)==EOF)
return 1;
if(strcmp(res,a)==0)
{
h2-=a1;
if (h2 <= 0) break;
h1-=a2;
if(h1<=0)//过程中猎人死了WA
return 1;
fscanf(outf," %s",res);
if(strcmp(res,"Ryuseiken!!!!"))//样列一定要对
return 1;
}
else if(strcmp(res,b)==0)
{
h1-=a2,h1+=c1;
fscanf(outf," %s",res);
if(strcmp(res,"my"))
return 1;
fscanf(outf," %s",res);
if(strcmp(res,"calories!!!!"))
return 1;
}
}
if(h1<=0||h2>0)//最后猎人死了或者怪物没死WA
return 1;
return 0;//最后AC
}<file_sep>/I/program.c
/**
* 想拿奖吗?先来掷个骰子!
* 题解: 排序后直接根据规则模拟比较即可
*
* Dear maintainer:
* Once you are done trying to 'optimize' this routine, and have realized what a
* terrible mistake that was, please increment the following counter as a warning
* to the next guy, total_wasted_here: 0
* @author jiaying created on 09/11/2018.
*/
#include <stdio.h>
#define LARGEST 3 // 豹子
#define SECOND_LARGEST 2 // 顺子
#define THIRD_LARGEST 1 // 对子
#define SMALLEST 0 // 点子
#define WIN 666 // 获胜
#define LOSE 555 // 失败
#define DRAW 999 // 平局
/**
* 获取摇到的骰子的牌型
*/
int getDiceType(int dice[]) {
// 豹子
if (dice[0] == dice[1] && dice[0] == dice[2]) {
return LARGEST;
}
// 顺子
if (dice[0] - dice[1] == 1 && dice[1] - dice[2] == 1) {
return SECOND_LARGEST;
}
// 对子
if (dice[0] == dice[1] || dice[1] == dice[2]) {
return THIRD_LARGEST;
}
// 点子
return SMALLEST;
}
/**
* 交换两个数
*/
void swap(int* x_addr, int* y_addr) {
int temp = *x_addr;
*x_addr = *y_addr;
*y_addr = temp;
}
/**
* 从大到小排序手上的牌型
*/
void sortDice(int dice[]) {
if (dice[0] < dice[1]) {
swap(&dice[0], &dice[1]);
}
if (dice[0] < dice[2]) {
swap(&dice[0], &dice[2]);
}
if (dice[1] < dice[2]) {
swap(&dice[1], &dice[2]);
}
}
/**
* 比较两个点数
*/
int compareTwoDicePoint(int diceA, int diceB) {
if (diceA > diceB) {
return WIN;
} else if (diceA < diceB) {
return LOSE;
} else {
return DRAW;
}
}
/**
* 比较两者的牌型
*/
int doCompare(int diceForA[], int diceForB[]) {
int diceTypeOfA = getDiceType(diceForA);
int diceTypeOfB = getDiceType(diceForB);
// 先比较牌型, 牌型一样的时候比较点数
if (diceTypeOfA > diceTypeOfB) {
return WIN;
} else if (diceTypeOfA < diceTypeOfB) {
return LOSE;
} else {
int result;
if (diceTypeOfA == THIRD_LARGEST && diceForA[1] != diceForB[1]) {
result = compareTwoDicePoint(diceForA[1], diceForB[1]);
} else {
for (int i = 0; i < 3; i++) {
result = compareTwoDicePoint(diceForA[i], diceForB[i]);
if (result != DRAW) {
break;
}
}
}
return result;
}
}
int main(int argc, char const *argv[])
{
int testCase;
int diceForA[3], diceForB[3];
scanf("%d", &testCase);
for (int _case = 0; _case < testCase; _case++) {
for (int i = 0; i < 3; i++) {
scanf("%d", &diceForA[i]);
}
sortDice(diceForA);
for (int i = 0; i < 3; i++) {
scanf("%d", &diceForB[i]);
}
sortDice(diceForB);
int result = doCompare(diceForA, diceForB);
puts(result == WIN ? "RED" : (result == LOSE ? "BLUE" : "DRAW"));
}
return 0;
}
<file_sep>/H/question.md
# Problem H
## Title
苗童大作战之跑跑卡丁车
## Description
苗苗开始飙车了,苗苗将会穿过一个小区到达终点,已知她现在在 n 位置,终点在 m 位置。这个小区的房子按矩阵样式排列。其楼房的编号为1, 2, 3...
当排满一行时,从下一行相邻的楼往反方向排号。
比如:当小区排数为3时,排列方式如下
1 2 3
6 5 4
7 8 9
……
当小区排数为6时,排列方式如下:
1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 .....
要知道苗苗是一个遵守交通规则的好孩纸,所以她只会横着走或者竖着走,不会在马路上斜着走。可是苗苗的车因为速度实在太快了,她甚至都忘了自己经过了多少栋房子,你能告诉她吗
## Input
包含三个整数w、n、m(1 ≤ w, n, m ≤ 10000000),分别表示一排有多少栋楼,苗苗的位置,终点的位置
## Output
输出一个整数,代表最少要经过的楼房数。
## Sample Input
6 6 14
## Sample Output
7
## Hint
样例中苗苗分别经过了6,7,8,9,10,15,14.总共7栋楼房
<file_sep>/F/program.c
#include <stdio.h>
#include <math.h>
int main()
{
double px,py,ans1,ans2;
scanf("%lf%lf",&px,&py);
ans1=(4.0*px*py)/3.0; //二次函数所占面积
ans2=3.0*px*px*sqrt(3)/4.0; //半个六边形所占面积
printf("%.2lf %.2lf\n",ans1,ans2);
return 0;
}
<file_sep>/E/question.md
# Problem E
## Title
苗童大作战之开心农场
## Description
童童和苗苗最近迷上了开心农场,可是苗苗总是偷童童的菜,愤怒的童童现在要进行反击了!!!
苗苗的农场是一块无限大的矩形土地(如下图),其黑色部分都被种上了值钱的黑凤梨,白色部分都种上了颜值爆表的猴赛雷。爱美的童童决定选择一个矩形区域偷走其中的猴赛雷。
苗苗的农场(左下角坐标为(1,1))如下:

白色部分与黑色部分都是 1 * 1 的正方形。
童童已经做好了计划,现在她给出了她要偷的矩形区域的左下角点的坐标和右上角点的坐标,现在她想请你帮忙计算一下,她能偷走多少块土地的猴赛雷。
## Input
第一行输入两个整数Px1和Py1,分别代表左下角点的横坐标和纵坐标。
第二行输入两个整数Px2和Py2,分别代表右上角点的横坐标和纵坐标。
## Output
输出一个整数,代表指定的矩形区域中总共有多少块种猴赛雷的土地。
## Sample Input
2 2
4 4
## Sample Output
4
## Hint
<file_sep>/F/question.md
# Problem F
## Title
苗童大作战之爱洗澡的鳄鱼
## Description
童童和苗苗准备邀请小鳄鱼来观看大作战,可是小鳄鱼是出了名的爱洗澡,没有游泳池是请不到小鳄鱼的哟!于是童童和苗苗准备比比谁先请到小鳄鱼,为了公平起见,苗苗和童童画出的泳池底长必须相同。

童童画了一个弧状的游泳池,而苗苗把正六边形的一半用来当作游泳池,可是小鳄鱼觉得洗澡的地方越大越好,那么问题来了,你能告诉小鳄鱼这两个图形的面积吗?
如下图:

x轴上方是童童画的游泳池,为了好看童童用某二元一次方程 y = ax^2 + c 的一部分画出了这段弧,给你二次函数与 x 轴的交点 Px 的绝对值和二次函数与 y 轴的交点 Py, 你能告诉小鳄鱼x轴上方和x轴下方的图形面积吗?
## Input
输入两个数 Px 和 Py (0 < Px, Py < 10000)
## Output
输出两个数,分别代表 x 轴上方的图形面积和 x 轴下方的图形面积。(保留两位小数)
## Simple input
2 4
## Simple output
10.67 5.20
<file_sep>/README.md
# 2018-Fun-programming-contest
2018 Fun programming contest
<file_sep>/H/program.c
#include<stdio.h>
#include<stdlib.h>
int main()
{
int w,m,n,x1,y1,x2,y2;
scanf("%d%d%d",&w,&n,&m);
x1=(m-1)/w+1;//利用排列规律算出两个房间分别在第几行第几列,之后坐标差求和。
y1=(m-1)%w+1;
if(x1%2==0)
y1=w-y1+1;//注意当前行排列顺序
x2=(n-1)/w+1;
y2=(n-1)%w+1;
if(x2%2==0)
y2=w-y2+1;
printf("%d\n",abs(x1-x2)+abs(y1-y2)+1);//一定不要忘记当前所在的房间。
}
<file_sep>/B/question.md
# Problem B
## Title
苗童大作战之亲友团
## Description
在开始比赛前,童童决定邀请她的亲友团来给自己打气,童童的最多可以邀请 n 个人,可是其中有些人与其他人关系不太好,要知道内部不和可是会出大问题的。为了打造一个融洽的亲友团,童童都快急哭了。
这里我们用一个数组 a 表示童童的将要邀请的名单,如果 a[i] + a[j](i != j) 为素数,则表示第 i 个人和第 j 个人相处融洽,否则代表他们关系不好,你能告诉童童这个亲友团的最大人数吗?要求团内每个人跟其他人都相处融洽。
为了不要使亲友团太孤单,请不要只邀请 1 个人
## Input
第一行是一个整数 n (1 < n ≤ 10000)
第二行是a[0], a[1], ... , a[n-1] 共 n 个整数 (1 ≤ ai, aj ≤ 20000)
## OutPut
输出一个整数,代表童童可邀请的最大人数。
## Sample InPut
3
2 3 5
## Sample OutPut
2
<file_sep>/G/question.md
# Problem G
## Title
苗童大作战之跳一跳
## Description
你们都玩过微信跳一跳吧~ 要知道苗苗和童童可是跳一跳大神呢。可是她们今天被一个新的跳一跳难倒了,你能帮帮她们吗?
#### 游戏规则:
现在有n 个连续且长为 1 的格子,上面标有一些数字,苗苗和童童站在两端。游戏开始,先将两人中间夹着的(包括所站的地方)所有格子都进行翻转(例如中间夹着的格子如果为1 2 3,则变为3 2 1),然后两个人同时往中间跳一步,直到两人面对面或者站在同一格子上为止。
现在她们想知道走到最后这 n 个格子的数字顺序是什么,你能帮帮她们吗?
## Input
第一行包含一个整数 n (0 < n < 1000000)
第二行包含 n 个整数,第 i (1 <= i <= n) 个整数代表第 i 个格子上所标的数字 。
## Output
按照从左到右的顺序输出这n个数,代表翻转之后每个格子上的数字。
## Sample Input
5
10 11 12 13 14
## Sample Output
14 11 12 13 10
## Sample Input
2
10 13
## Sample Output
13 10
<file_sep>/I/question.md
# Problem I
## Title
苗童大作战之神之预言
## Description
苗童大作战已经接近尾声了,可是消息闭塞的小伙伴们都不知道比赛情况,好奇的他们决定请教万能的上帝,上帝告诉他们骰子知道结果。于是支持苗苗的红队和支持童童的蓝队决定来一场骰子大战,红蓝双方各有三个普通的六面骰子,同时投掷,最后比较大小。
比较的规则如下:
1. 如果三个骰子的点数都一样,称为豹子,如果双方都是豹子,则按点数比大小。
2. 如果只有两个骰子的点数一样,称为对子,如果双方都是对子,则先按对子的点数比大小,对子点数相同的,按剩余骰子的点数比大小。
3. 如果没有一个点数相同,但是从大到小排序后,相邻两个骰子点数只相差 1,我们称之为顺子,如 5 4 3,如果双方都是顺子,则比较最大点数。
4. 其他情况下称为点子,则比较双方的最大点数,最大点数相同的比较第二大,以此类推。
5. 豹子 > 顺子 > 对子 > 点子
好了,让红蓝来一决高下吧,你能帮忙判断一下他们的胜负情况吗?
同时,为了感谢你帮助他们,**第一个**做出这个题的同学将会有**神秘奖励**
## Input
第一行包含一个整数 n ,表示扔骰子的次数。
每次游戏包含两行样例,第一行是红队投掷的三个骰子的点数,第二行是蓝队投掷的三个骰子的点数。
## Output
如果是红队赢了,输出"RED",如果是蓝队赢了,输出"BLUE",平局输出"DRAW", 不包含引号。
## Sample Input
1
2 5 6
1 3 4
## Sample Output
RED
<file_sep>/G/program.c
#include <stdio.h>
#include <stdlib.h>
int num[10000005];
//找规律,对于一个长为n的数组,第i和第n-i-1个点互换(2x+1)次和互换一次等价,互换2x次和不换等价
int main()
{
int n;
scanf("%d", &n);
int i;
for (i = 0; i < n; i++) scanf("%d", &num[i]);
int flag = 1;
for (i=0;i < n/2;i++) {
if (flag) {
int temp = num[i]; //互换
num[i] = num[n-i-1];
num[n-i-1] = temp;
}
flag = !flag;
}
for (i = 0; i < n; i++) printf("%d ", num[i]);
return 0;
}
<file_sep>/D/question.md
# Problem D
## Title
苗童大作战之愤怒的小鸟
## Description
继愤怒的小鸟N.0版本之后,系统又推出了愤怒的小鸟(N+1).0版。
在最新版中,系统给出了 n 个可供选择的点。苗苗和童童已经是大学生了,运用所学知识,她们很机智的选择了使用平面直角坐标系来表示这些点。她们可以在这 n 个位置中任选两个,一个用于架设支架,一个用于放置小鸟。
现给出这 n 个点的坐标,在击打力度和鸟的种类均相同的条件下,求小鸟和支架可能组成的斜率最大值。
## Input
第一行输入一个整数 n(1 < n < 1000000) ,代表系统给出 n 个可供选择的点。
接下来的 n 行,每行输入两个整数x,y(1 < x, y < 1000000),分别代表该点的横纵坐标,保证输入按照横坐标递增,且不存在横坐标相同的点。
## OutPut
输出一个数,代表可能组成的仰角正切值的最大值,结果保留两位小数。
## Sample InPut
3
1 2
2 5
3 4
## Sample OutPut
3.00
## Hint

| f8f3e0204f3eeaeba8224e39f0a0ca45f7374538 | [
"Markdown",
"C",
"C++"
]
| 18 | C | SDIBTACM/2018-Fun-programming-contest | 32cb234857157880ca5733e7c5ed915e6788cd97 | b932da7d9ce523ba823e733958ebd8be90907962 |
refs/heads/master | <file_sep>import log
import config
import GenericNode
nodes = []
nodes_inst = {}
def init(collector):
if not len(nodes) == 0:
raise BaseException("Already Initialized")
for node in config.nodes:
module = None
try:
module = __import__('collect.newnodes.%s' % node, fromlist=['%s' % node])
#globals()[node] = module
except ImportError, e:
log.error('failed to import module [%s]: %s' % (node, str(e)))
return False
nodes.append(module)
for node in nodes:
nconfig = {}
try:
nconfig = getattr(config, node.__name__)
except AttributeError: pass
nodename = node.__name__.split('.')[-1]
nodeinfo = config.nodes[nodename]
# guess the class, if its superclass is GenericNode, go for it
for k in node.__dict__:
try:
if node.__dict__[k].mro()[1] is GenericNode.GenericNode:
n = node.__dict__[k](collector)
break
except AttributeError: pass
#try:
n.init(nodename, nodeinfo, config=config.application)
nodes_inst[nodename] = n
#except Exception, e:
# log.error( 'failed to initialize module [%s]: %s' % (node, str(e)) )
if not len(nodes_inst):
return False
return True
def start():
global nodes_inst
for node in nodes_inst:
nodes_inst[node].start()
while not nodes_inst[node].interface.isInitialized():
pass
return True
def stop():
global nodes_inst
for node in nodes_inst:
nodes_inst[node].stop()
return True
def command(nodename, cmd):
global nodes_inst
if nodename in nodes_inst:
return nodes_inst[nodename].command(cmd)
return 'NODE_NOT_FOUND'
def nodes_list():
nl = []
for n in nodes_inst:
nl.append(n)
return nl
<file_sep>/*
* HGWDemoServiceMain.java
*
* Created on November 5, 2007, 10:39 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
import net.netcarity.hgw.DemoHGWService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.ws.Endpoint;
import net.netcarity.ncscclient.jaxws.WebServiceClient;
import net.netcarity.ncscclient.jaxws.WebServiceClientService;
/**
*
* @author aubrech
*/
public class HGWDemoServiceMain {
/**
* Creates a new instance of HGWDemoServiceMain
*/
public HGWDemoServiceMain() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new HGWDemoServiceMain().run();
}
public void run() {
try {
// first, launch listening web service
System.out.println("going to publish the hgwdemo web service");
DemoHGWService demoHGW = new DemoHGWService();
Endpoint wsEnpoint = Endpoint.publish("http://localhost:2000/ncsc/hgwnodedemo", demoHGW);
// connect to NCSC web service
System.out.println("connecting to the NCSC ws");
WebServiceClientService service = null;
WebServiceClient ncsc = null;
boolean connected = false;
while(!connected) {
try {
service = new WebServiceClientService();
ncsc = service.getWebServiceClientPort();
connected = ncsc.isConnected();
} catch(Exception e) {
System.out.println(""+new Date()+": Waiting for connection to be open...");
Thread.sleep(300);
}
}
// then, simulate some work
// 1. register demo sensor
System.out.println("registering devices");
ncsc.sendMessage(10,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ncmessage msgid=\"SitCom_"+getMsgId()+"\" priority=\"10\" source=\"SitCom\" timestamp=\""+getCurrTime()+"\" type=\"node_list\" version=\"1.0\">" +
"<node id=\"SMNode_FallDown\" type=\"SitCom_SM\">" +
"<value key=\"WebServiceURL\">http://localhost:2000/sitcomlistener/sitcomlistener</value>" +
"</node>" +
"<node id=\"SMNode_DoorLock\" type=\"SitCom_SM\">" +
"<value key=\"WebServiceURL\">http://localhost:2000/sitcomlistener/sitcomlistener</value>" +
"</node>" +
"</ncmessage>",null);
// 2. send sensor data for some time
Thread.sleep(1000);
// 3. then send some alarm
while(true) {
System.out.println(""+new Date()+": sending alarm");
long messageSendTime = System.currentTimeMillis();
ncsc.sendMessage(10,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ncmessage msgid=\"SitCom_"+getMsgId()+"\" priority=\"80\" source=\"SitCom\" timestamp=\""+getCurrTime()+"\" type=\"node_data\" version=\"1.0\">" +
"<node id=\"SMNode_FallDown\" type=\"SitCom_SM\">" +
"<value key=\"WebServiceURL\">http://localhost:2000/sitcomlistener/sitcomlistener</value>" +
"<value key=\"text\">Fall in kitchen</value>" +
"<value key=\"location\">kitchen</value>" +
"<value key=\"position\">246,390,0</value>" +
"</node>" +
"</ncmessage>",null);
// 4. acquire acknowledge
System.out.println("waiting for incoming message");
synchronized(this) {
wait();
}
long messageAckTime = System.currentTimeMillis();
System.out.println(""+new Date()+": processing time: "+(messageAckTime-messageSendTime)+" ms");
// If you want to try stress testing, comment out the next line:
Thread.sleep(30000);
}
/*
//Thread.sleep(2000);
// 5. it's all, folks
wsEnpoint.stop();
System.out.println("finishing");
//*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
protected int msgId = 0;
protected int getMsgId() {
return msgId++;
}
protected SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");
/**
* return time in yyyyMMddhhmmssS format
*/
private String getCurrTime() {
return sdf.format(new Date());
}
public void messageReceived(String msg) {
synchronized(this) {
notifyAll();
}
}
public void disconnected(String msg) {
// break all waitings due to disconnected channel
synchronized(this) {
notifyAll();
}
}
public void messageSent(String id) {
//notifyAll();
}
}
<file_sep>import dbus
import dbus.glib
import dbus.service
import sys
class PasskeyAgent(dbus.service.Object):
def __init__(self, path, keystore):
dbus.service.Object.__init__(self, 'SYSTEM', path)
self.keystore = keystore
@dbus.service.method(dbus_interface='org.bluez.PasskeyAgent',
in_signature='ssb', out_signature='s')
def Request(self, path, address, numeric):
try:
pin = self.keystore[address]
print "Request",path,address,numeric,"OK"
return pin
except:
print "Request",path,address,numeric,"failed"
return ""
if __name__ == "__main__":
keystore = {}
devs = [
"00:A0:96:16:9D:05/0000",
]
for arg in devs:
addr, pin = arg.split("/")
keystore[addr] = pin
PATH = '/my/PasskeyAgent'
bus = dbus.SystemBus();
handler = PasskeyAgent(PATH, keystore)
adapter = bus.get_object('org.bluez', '/org/bluez/hci0')
sec = dbus.Interface(adapter, 'org.bluez.Security')
sec.RegisterDefaultPasskeyAgent(PATH)
import time
while True:
time.sleep(1)
<file_sep>import logging
import sys
import traceback
logger = logging.getLogger()
debug = logger.debug
info = logger.info
warning = logger.warning
error = logger.error
critical = logger.critical
exception = logger.exception
def traced(func):
"""Decorator useful to log all function/method calls."""
def traced_wrapper(*args):
ret = None
debug('tracing [%(module)s::%(funcName)s()]: entering', {'funcName': func.func_name, 'module': func.__module__})
try:
ret = func(*args)
except Exception, e:
debug('tracing [%(module)s::%(funcName)s()]: exiting after EXCEPTION', {'funcName': func.func_name, 'module': func.__module__})
#FIXME: traceback.print_exc()
raise e
debug('tracing [%(module)s::%(funcName)s()]: exiting', {'funcName': func.func_name, 'module': func.__module__})
return ret
return traced_wrapper
def init(verbosity=None):
COMPLETE='%(asctime)s %(levelname)s %(module)s::%(funcName)s() - %(message)s'
COMPACT='%(levelname)s %(module)s::%(funcName)s() - %(message)s'
if verbosity is None:
verbosity = logging.DEBUG
#INFO # DEBUG
logging.basicConfig(
level=verbosity,
format=COMPACT,
#filename='/tmp/myapp.log',
#filemode='w'
)
logging.info('logging initialized')
def stop():
logging.shutdown()
<file_sep>import threading
import Queue
import utils
from utils.misc import Singleton
# FIXME: duplicated
class NotImplemented(BaseException):
"""Not implemented method exception."""
pass
class GenericInterface(Singleton):
"""Root class for all the interfaces, like GenericNode implements common code and some hidden magic."""
def __init__(self):
self._thread = threading.Thread(target = self.runloop)
self._thread.setDaemon(1)
self._isInitialized = False
self.__shouldStop = False
self.__queues = {}
## to not reimplment
def isInitialized(self):
return self._isInitialized
def generic_start(self):
self.__shouldStop = False
self.start()
self._thread.start()
def generic_stop(self):
self.__shouldStop = True
self.stop()
## no need to always reimplement
def start(self): pass
def stop(self): pass
def command(self, vid, cmd):
return 'NOT_SUPPORTED'
def idToNodename(self, nid):
assert type(nid) is type(1)
name = ''
if nid == -1:
nid = config.nodes[self.nodename]['id']
assert type(name) is type('')
return (nid, self.nodename)
## to implement
def runloop(self):
raise NotImplemented
def init(self, config={}):
raise NotImplemented
## to overload in the node
def newValue(self, vid, timestamp, values):
raise NotImplemented
<file_sep>cd ncscServer/ncsecurechannel/; java -jar NCSecureChannel.jar
<file_sep>import sys
import time
from net.netcarity.securechannel.webservice import *
import net.netcarity.hgw.DemoHGWService
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import javax.xml.ws.Endpoint
def initClient():
locator = WebServiceClientServiceLocator()
port = locator.getWebServiceClientPort()
return port
def initServer():
demoHGW = net.netcarity.hgw.DemoHGWService()
endpoint = javax.xml.ws.Endpoint.publish("http://localhost:2000/ncsc/hgwnodedemo", demoHGW)
return endpoint
global msgId
msgId = 0
def getMsgId():
global msgId
msgId += 1
return str(msgId)
def getCurrTime():
sdf = java.text.SimpleDateFormat("yyyyMMddHHmmssS")
return str(sdf.format(java.util.Date()))
def log(msg):
print("%s - %s" % (time.ctime(), msg))
def main():
initServer()
ncsc = initClient()
log("sleeping for 10s")
time.sleep(10)
log("calling isConnected()")
if ncsc.isConnected():
log("isConnected(): 1")
log("sending message")
ncsc.sendMessage(10,"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ncmessage msgid=\"SitCom_" + getMsgId() +
"\" priority=\"10\" source=\"SitCom\" timestamp=\"" + getCurrTime() +
"\" type=\"node_list\" version=\"1.0\">" +
"<node id=\"SMNode_FallDown\" type=\"SitCom_SM\">" +
"<value key=\"WebServiceURL\">http://localhost:2000/sitcomlistener/sitcomlistener</value>" +
"</node>" +
"<node id=\"SMNode_DoorLock\" type=\"SitCom_SM\">" +
"<value key=\"WebServiceURL\">http://localhost:2000/sitcomlistener/sitcomlistener</value>" +
"</node>" +
"</ncmessage>", None)
log("done")
else:
log("not connected!")
log("exiting")
sys.exit()
main()
<file_sep>import GenericNode
from interfaces import barionetInterface
class RingBell(GenericNode.GenericNode):
"""Gets values from barionet and uses the ringbell I/O to generate press/release events."""
interface = barionetInterface.BarionetInterface()
interfacename = 'barionet'
def newValue(self, nodename, value):
assert type(value) is type([])
msg = ''
if len(value) == 15: #stato I/O
pass
if len(value) == 1:
if value[0][0] == 'statechange':
#HACK:
if not value[0][1] == self.interface.config['barionet_ringbell_ionum']:
return {}
if value[0][2] == '0':
msg = 'pressed'
else:
msg = 'released'
return {'ringbell_status': msg}
return {}
def command(self, cmd):
if cmd == 'open_door':
print '\nCALLING self.interface.open_door()\n'
self.interface.open_door()
return cmd
<file_sep>from __future__ import with_statement
import threading
import xmlrpclib
import log
from utils import locked
class DeliveryChannel(object):
"""Generic class for protocol-specific delivery channels."""
def __init__(self):
self.failures = 0
self.maxfailures = 3
self.timeout = 1
@log.traced
def send(self, addr, *args):
while self.failures < self.maxfailures:
if self.protocol_send(addr, *args):
break
self.failures += 1
if self.failures >= self.maxfailures:
log.warning('self.maxfailures reached - invalidating subscription')
self.failures = 0
return False
return True
class NCSCChannel(DeliveryChannel):
def protocol_send(self, addr, *args):
log.info('sending "%s" to "%s"' % (msg, addr))
class XMLRPCChannel(DeliveryChannel):
@log.traced
def protocol_send(self, addr, *args):
sp = xmlrpclib.ServerProxy('http://' + addr)
try:
sp.HGWCollector.receiveData(*args)
except Exception, e:
log.warning('delivery failure: %s' % str(e))
return False
return True
class AsynchronousDataCarrier(object):
"""Asynchronous pub/sub data request interface for RemoteInterface."""
def __init__(self):
self.subscriptions = {}
self._subscriptions_lock = threading.Lock()
self.broker = None
self._ncscChannel = NCSCChannel()
self._xmlrpcChannel = XMLRPCChannel()
def deliver(self, subscriptionUUID, message):
"""Walks through subscriptions list and delivers the given message."""
with self._subscriptions_lock:
if not self.subscriptions.has_key(subscriptionUUID):
log.warning('AsyncDelivery::deliver(): subscription not found!')
replyAddress = self.subscriptions[subscriptionUUID][1]
protocol, address = replyAddress.split('://')
ret = False
if protocol == 'ncsc':
ret = self._ncscChannel.send(address, subscriptionUUID, message)
if protocol == 'xmlrpc' or protocol == 'http':
ret = self._xmlrpcChannel.send(address, subscriptionUUID, message)
if ret is False:
try:
self.unsubscribe(self.subscriptions[subscriptionUUID][0], subscriptionUUID)
except KeyError: pass
def isValidSubscription(self, subscriptionUUID, replyAddress):
if self.subscriptions.has_key(subscriptionUUID):
if self.subscriptions[subscriptionUUID][1] == replyAddress:
return True
return False
def subscribe(self, publisherName, replyAddress):
subscriptionUUID = self.broker.subscribe(publisherName)
with self._subscriptions_lock:
self.subscriptions[subscriptionUUID] = (publisherName, replyAddress)
return subscriptionUUID
def unsubscribe(self, publisherName, subscriptionUUID):
self.broker.unsubscribe(publisherName, subscriptionUUID)
with self._subscriptions_lock:
self.subscriptions.pop(subscriptionUUID)
<file_sep>from ZSI.ServiceContainer import ServiceContainer, SOAPRequestHandler
from NodeListenerService_server import NodeListenerService
import os
def initServer():
cs = []
cs.append(NodeListenerService())
s = ServerSOAP('localhost',2000,cs,RHandlerClass=CustomSOAPRequestHandler)
s.start()
class CustomSOAPRequestHandler(SOAPRequestHandler):
def do_GET(self):
self.send_xml(NodeListenerService._wsdl)
class ServerSOAP(object):
def __init__(self, host, p=2000, serv=(), RHandlerClass=SOAPRequestHandler):
self._hostname = host
self._port = p
self._services = serv
self._RequestHandlerClass = RHandlerClass
def start(self):
address = (self._hostname, self._port)
sc = ServiceContainer(address, (), self._RequestHandlerClass)
for service in self._services:
path = service.getPost()
sc.setNode(service,path)
sc.serve_forever()
if __name__=="__main__":
initServer()
<file_sep>import GenericNode
from interfaces import serialExample
class TempExample(GenericNode.GenericNode):
"""Forwards serialExample data for testing."""
interface = serialExample.SerialExample()
interfacename = 'serial'
def newValue(self, nodename, value):
return {'example': value}
<file_sep>##################################################
# file: NodeListenerService_server.py
#
# skeleton generated by "ZSI.generate.wsdl2dispatch.ServiceModuleWriter"
# /usr/local/bin/wsdl2py http://localhost:2000/ncsc/hgwnodedemo/?wsdl
#
##################################################
from ZSI.schema import GED, GTD
from ZSI.TCcompound import ComplexType, Struct
from NodeListenerService_types import *
from ZSI.ServiceContainer import ServiceSOAPBinding
# Messages
connected = GED("http://hgw.netcarity.net/", "connected").pyclass
connectedResponse = GED("http://hgw.netcarity.net/", "connectedResponse").pyclass
disconnected = GED("http://hgw.netcarity.net/", "disconnected").pyclass
disconnectedResponse = GED("http://hgw.netcarity.net/", "disconnectedResponse").pyclass
messageSent = GED("http://hgw.netcarity.net/", "messageSent").pyclass
messageSentResponse = GED("http://hgw.netcarity.net/", "messageSentResponse").pyclass
errorReported = GED("http://hgw.netcarity.net/", "errorReported").pyclass
errorReportedResponse = GED("http://hgw.netcarity.net/", "errorReportedResponse").pyclass
message = GED("http://hgw.netcarity.net/", "message").pyclass
messageResponse = GED("http://hgw.netcarity.net/", "messageResponse").pyclass
# Service Skeletons
class NodeListenerService(ServiceSOAPBinding):
soapAction = {}
root = {}
_wsdl = """<?xml version=\"1.0\" ?><definitions name=\"NodeListenerService\" targetNamespace=\"net.netcarity.hgw\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:tns=\"net.netcarity.hgw\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<binding name=\"NodeListenerPortBinding\" type=\"ns1:NodeListener\" xmlns:ns1=\"http://hgw.netcarity.net/\">
<soap:binding style=\"document\" transport=\"http://schemas.xmlsoap.org/soap/http\"/>
<operation name=\"connected\">
<soap:operation soapAction=\"\"/>
<input>
<soap:body use=\"literal\"/>
</input>
<output>
<soap:body use=\"literal\"/>
</output>
</operation>
<operation name=\"disconnected\">
<soap:operation soapAction=\"\"/>
<input>
<soap:body use=\"literal\"/>
</input>
<output>
<soap:body use=\"literal\"/>
</output>
</operation>
<operation name=\"messageSent\">
<soap:operation soapAction=\"\"/>
<input>
<soap:body use=\"literal\"/>
</input>
<output>
<soap:body use=\"literal\"/>
</output>
</operation>
<operation name=\"errorReported\">
<soap:operation soapAction=\"\"/>
<input>
<soap:body use=\"literal\"/>
</input>
<output>
<soap:body use=\"literal\"/>
</output>
</operation>
<operation name=\"message\">
<soap:operation soapAction=\"\"/>
<input>
<soap:body use=\"literal\"/>
</input>
<output>
<soap:body use=\"literal\"/>
</output>
</operation>
</binding>
<service name=\"NodeListenerService\">
<port binding=\"tns:NodeListenerPortBinding\" name=\"NodeListenerPort\">
<soap:address location=\"http://localhost:2000/ncsc/hgwnodedemo/\"/>
</port>
</service>
<types targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<xsd:schema>
<xsd:import namespace=\"http://hgw.netcarity.net/\" schemaLocation=\"http://localhost:2000/ncsc/hgwnodedemo/?xsd=1\"/>
</xsd:schema>
</types><message name=\"connected\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:connected\" name=\"parameters\"/>
</message><message name=\"connectedResponse\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:connectedResponse\" name=\"parameters\"/>
</message><message name=\"disconnected\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:disconnected\" name=\"parameters\"/>
</message><message name=\"disconnectedResponse\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:disconnectedResponse\" name=\"parameters\"/>
</message><message name=\"messageSent\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:messageSent\" name=\"parameters\"/>
</message><message name=\"messageSentResponse\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:messageSentResponse\" name=\"parameters\"/>
</message><message name=\"errorReported\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:errorReported\" name=\"parameters\"/>
</message><message name=\"errorReportedResponse\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:errorReportedResponse\" name=\"parameters\"/>
</message><message name=\"message\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:message\" name=\"parameters\"/>
</message><message name=\"messageResponse\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<part element=\"tns:messageResponse\" name=\"parameters\"/>
</message><portType name=\"NodeListener\" targetNamespace=\"http://hgw.netcarity.net/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:tns=\"http://hgw.netcarity.net/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
<operation name=\"connected\">
<input message=\"tns:connected\"/>
<output message=\"tns:connectedResponse\"/>
</operation>
<operation name=\"disconnected\">
<input message=\"tns:disconnected\"/>
<output message=\"tns:disconnectedResponse\"/>
</operation>
<operation name=\"messageSent\">
<input message=\"tns:messageSent\"/>
<output message=\"tns:messageSentResponse\"/>
</operation>
<operation name=\"errorReported\">
<input message=\"tns:errorReported\"/>
<output message=\"tns:errorReportedResponse\"/>
</operation>
<operation name=\"message\">
<input message=\"tns:message\"/>
<output message=\"tns:messageResponse\"/>
</operation>
</portType></definitions>"""
def log(msg):
print("%s - %s" % (time.ctime(), msg))
def __init__(self, post='/ncsc/hgwnodedemo/', **kw):
ServiceSOAPBinding.__init__(self, post)
def soap_connected(self, ps, **kw):
request = ps.Parse(connected.typecode)
#log(connected.typecode)
return request,connectedResponse()
soapAction[''] = 'soap_connected'
root[(connected.typecode.nspname,connected.typecode.pname)] = 'soap_connected'
def soap_disconnected(self, ps, **kw):
request = ps.Parse(disconnected.typecode)
return request,disconnectedResponse()
soapAction[''] = 'soap_disconnected'
root[(disconnected.typecode.nspname,disconnected.typecode.pname)] = 'soap_disconnected'
def soap_messageSent(self, ps, **kw):
request = ps.Parse(messageSent.typecode)
#log(messageSent.typecode)
return request,messageSentResponse()
soapAction[''] = 'soap_messageSent'
root[(messageSent.typecode.nspname,messageSent.typecode.pname)] = 'soap_messageSent'
def soap_errorReported(self, ps, **kw):
request = ps.Parse(errorReported.typecode)
return request,errorReportedResponse()
soapAction[''] = 'soap_errorReported'
root[(errorReported.typecode.nspname,errorReported.typecode.pname)] = 'soap_errorReported'
def soap_message(self, ps, **kw):
request = ps.Parse(message.typecode)
return request,messageResponse()
soapAction[''] = 'soap_message'
root[(message.typecode.nspname,message.typecode.pname)] = 'soap_message'
<file_sep>gcc -o pk passkey-agent.c -I/usr/include/dbus-1.0 -I /usr/lib/dbus-1.0/include -ldbus-1
<file_sep>##################################################
# file: NodeListenerService_types.py
#
# schema types generated by "ZSI.generate.wsdl2python.WriteServiceModule"
# /usr/local/bin/wsdl2py http://localhost:2000/ncsc/hgwnodedemo/?wsdl
#
##################################################
import ZSI
import ZSI.TCcompound
from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED
##############################
# targetNamespace
# net.netcarity.hgw
##############################
class ns0:
targetNamespace = "net.netcarity.hgw"
# end class ns0 (tns: net.netcarity.hgw)
##############################
# targetNamespace
# http://hgw.netcarity.net/
##############################
class ns1:
targetNamespace = "http://hgw.netcarity.net/"
class errorReported_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "errorReported")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.errorReported_Def.schema
TClist = [ZSI.TC.String(pname="arg0", aname="_arg0", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._arg0 = None
return
Holder.__name__ = "errorReported_Holder"
self.pyclass = Holder
class errorReportedResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "errorReportedResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.errorReportedResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "errorReportedResponse_Holder"
self.pyclass = Holder
class messageSent_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "messageSent")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.messageSent_Def.schema
TClist = [ZSI.TC.String(pname="arg0", aname="_arg0", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._arg0 = None
return
Holder.__name__ = "messageSent_Holder"
self.pyclass = Holder
class messageSentResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "messageSentResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.messageSentResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "messageSentResponse_Holder"
self.pyclass = Holder
class connected_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "connected")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.connected_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "connected_Holder"
self.pyclass = Holder
class connectedResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "connectedResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.connectedResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "connectedResponse_Holder"
self.pyclass = Holder
class message_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "message")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.message_Def.schema
TClist = [ZSI.TC.String(pname="arg0", aname="_arg0", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._arg0 = None
return
Holder.__name__ = "message_Holder"
self.pyclass = Holder
class messageResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "messageResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.messageResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "messageResponse_Holder"
self.pyclass = Holder
class disconnected_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "disconnected")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.disconnected_Def.schema
TClist = [ZSI.TC.String(pname="arg0", aname="_arg0", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._arg0 = None
return
Holder.__name__ = "disconnected_Holder"
self.pyclass = Holder
class disconnectedResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://hgw.netcarity.net/"
type = (schema, "disconnectedResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns1.disconnectedResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "disconnectedResponse_Holder"
self.pyclass = Holder
class connected_Dec(ElementDeclaration):
literal = "connected"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","connected")
kw["aname"] = "_connected"
if ns1.connected_Def not in ns1.connected_Dec.__bases__:
bases = list(ns1.connected_Dec.__bases__)
bases.insert(0, ns1.connected_Def)
ns1.connected_Dec.__bases__ = tuple(bases)
ns1.connected_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "connected_Dec_Holder"
class connectedResponse_Dec(ElementDeclaration):
literal = "connectedResponse"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","connectedResponse")
kw["aname"] = "_connectedResponse"
if ns1.connectedResponse_Def not in ns1.connectedResponse_Dec.__bases__:
bases = list(ns1.connectedResponse_Dec.__bases__)
bases.insert(0, ns1.connectedResponse_Def)
ns1.connectedResponse_Dec.__bases__ = tuple(bases)
ns1.connectedResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "connectedResponse_Dec_Holder"
class disconnected_Dec(ElementDeclaration):
literal = "disconnected"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","disconnected")
kw["aname"] = "_disconnected"
if ns1.disconnected_Def not in ns1.disconnected_Dec.__bases__:
bases = list(ns1.disconnected_Dec.__bases__)
bases.insert(0, ns1.disconnected_Def)
ns1.disconnected_Dec.__bases__ = tuple(bases)
ns1.disconnected_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "disconnected_Dec_Holder"
class disconnectedResponse_Dec(ElementDeclaration):
literal = "disconnectedResponse"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","disconnectedResponse")
kw["aname"] = "_disconnectedResponse"
if ns1.disconnectedResponse_Def not in ns1.disconnectedResponse_Dec.__bases__:
bases = list(ns1.disconnectedResponse_Dec.__bases__)
bases.insert(0, ns1.disconnectedResponse_Def)
ns1.disconnectedResponse_Dec.__bases__ = tuple(bases)
ns1.disconnectedResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "disconnectedResponse_Dec_Holder"
class errorReported_Dec(ElementDeclaration):
literal = "errorReported"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","errorReported")
kw["aname"] = "_errorReported"
if ns1.errorReported_Def not in ns1.errorReported_Dec.__bases__:
bases = list(ns1.errorReported_Dec.__bases__)
bases.insert(0, ns1.errorReported_Def)
ns1.errorReported_Dec.__bases__ = tuple(bases)
ns1.errorReported_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "errorReported_Dec_Holder"
class errorReportedResponse_Dec(ElementDeclaration):
literal = "errorReportedResponse"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","errorReportedResponse")
kw["aname"] = "_errorReportedResponse"
if ns1.errorReportedResponse_Def not in ns1.errorReportedResponse_Dec.__bases__:
bases = list(ns1.errorReportedResponse_Dec.__bases__)
bases.insert(0, ns1.errorReportedResponse_Def)
ns1.errorReportedResponse_Dec.__bases__ = tuple(bases)
ns1.errorReportedResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "errorReportedResponse_Dec_Holder"
class message_Dec(ElementDeclaration):
literal = "message"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","message")
kw["aname"] = "_message"
if ns1.message_Def not in ns1.message_Dec.__bases__:
bases = list(ns1.message_Dec.__bases__)
bases.insert(0, ns1.message_Def)
ns1.message_Dec.__bases__ = tuple(bases)
ns1.message_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "message_Dec_Holder"
class messageResponse_Dec(ElementDeclaration):
literal = "messageResponse"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","messageResponse")
kw["aname"] = "_messageResponse"
if ns1.messageResponse_Def not in ns1.messageResponse_Dec.__bases__:
bases = list(ns1.messageResponse_Dec.__bases__)
bases.insert(0, ns1.messageResponse_Def)
ns1.messageResponse_Dec.__bases__ = tuple(bases)
ns1.messageResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "messageResponse_Dec_Holder"
class messageSent_Dec(ElementDeclaration):
literal = "messageSent"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","messageSent")
kw["aname"] = "_messageSent"
if ns1.messageSent_Def not in ns1.messageSent_Dec.__bases__:
bases = list(ns1.messageSent_Dec.__bases__)
bases.insert(0, ns1.messageSent_Def)
ns1.messageSent_Dec.__bases__ = tuple(bases)
ns1.messageSent_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "messageSent_Dec_Holder"
class messageSentResponse_Dec(ElementDeclaration):
literal = "messageSentResponse"
schema = "http://hgw.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://hgw.netcarity.net/","messageSentResponse")
kw["aname"] = "_messageSentResponse"
if ns1.messageSentResponse_Def not in ns1.messageSentResponse_Dec.__bases__:
bases = list(ns1.messageSentResponse_Dec.__bases__)
bases.insert(0, ns1.messageSentResponse_Def)
ns1.messageSentResponse_Dec.__bases__ = tuple(bases)
ns1.messageSentResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "messageSentResponse_Dec_Holder"
# end class ns1 (tns: http://hgw.netcarity.net/)
<file_sep>import Queue
import log
class Cabinet(Queue.Queue):
"""Contains messages from a single publisher."""
pass
class FilingCabinet(object):
"""Contains group of messages from multiple publishers."""
def __init__(self):
self.poboxes = {}
# reference to the message broker object, used to call newMessageFrom()
self.broker = None
#<EMAIL>
def push(self, publisherName, msg):
"""Push a new message to the publisher queue.
Arguments:
publisherName -- the name of the publisher sending the message \
msg -- the publisher's message
"""
if not self.poboxes.has_key(publisherName):
self.poboxes[publisherName] = {'queue': Cabinet(), 'last': None}
self.poboxes[publisherName]['queue'].put(msg)
self.poboxes[publisherName]['last'] = msg
self.broker.newMessageFrom(publisherName) ## notify the message broker
<EMAIL>
def pull(self, publisherName):
"""Pull a message from the publisher queue.
Arguments:
publisherName -- the name of the publisher to access the right queue and get the message.
"""
log.info('pulling data by %s' % publisherName)
ret = None
if self.poboxes.has_key(publisherName):
try:
ret = self.poboxes[publisherName]['queue'].get_nowait()
except Queue.Empty: pass
return ret
<EMAIL>
def pull_last(self, publisherName):
"""Pull the newest message from the publisher queue.
Arguments:
publisherName -- the name of the publisher to access the right queue and get the message.
"""
log.info('pulling last data by %s' % publisherName)
ret = None
if self.poboxes.has_key(publisherName):
ret = self.poboxes[publisherName]['last']
return ret
<file_sep>/*
* NodeListener.java
*/
package net.netcarity.hgw;
/**
* Interface for home gateway nodes
* @author aubrech
*/
public interface NodeListener {
/** NCSC has connected to the server
*/
void connected();
/** including connection failure
*/
void disconnected(String reason);
/** error appeared
*/
void errorReported(String msg);
/** send message to this node
*/
void message(String msg);
/** inform about message with the provided id successfully sent
*/
void messageSent(String id);
}
<file_sep>from __future__ import with_statement
import time
import uuid
import log
import threading
import copy
from utils import locked
class NotFoundSubscription(BaseException):
"""Subscription not found exception. """
pass
class NotFoundPublisher(BaseException):
"""Publisher not found exception."""
pass
# http://en.wikipedia.org/wiki/Publish/subscribe
class MessageBroker(object):
"""Handle the publisher/subscriber relations. Schedule and start the message delivery."""
def __init__(self):
# NOTE: {'publisherName': set('UUID1', 'UUID2', ...), ...}
self.subscriptions = {}
self._subscriptions_lock = threading.Lock()
# references to DataCarrier and FilingCabinet
self.carrier = None
self.cabinet = None
# Timer obj, modification time, timeout
self._timer = [None, None, None]
@log.traced
def subscribe(self, publisherName):
"""Subscribes the caller by creating a pub/sub relation and adding the relation identifier
to the subscriptions list. Returns the subscriptionUUID (the relation identifier).
Arguments:
publisherName -- the publisher part of the relation.
"""
with self._subscriptions_lock:
if not self.subscriptions.has_key(publisherName):
self.subscriptions[publisherName] = set()
# avoid UUID collisions
subscriptionUUID = str(uuid.uuid4())
while subscriptionUUID in self.subscriptions[publisherName]:
subscriptionUUID = str(uuid.uuid4())
self.subscriptions[publisherName].add(subscriptionUUID)
return subscriptionUUID
@log.traced
def unsubscribe(self, publisherName, subscriptionUUID):
"""Unsubscribes the caller by removing the pub/sub relation from the subscriptions list.
Arguments:
publisherName -- the publisher part of the relation.
subscriptionUUID -- the unique identifier of the subscription.
"""
with self._subscriptions_lock:
if not self.subscriptions.has_key(publisherName):
raise NotFoundPublisher
if not subscriptionUUID in self.subscriptions[publisherName]:
raise NotFoundSubscription
self.subscriptions[publisherName].remove(subscriptionUUID)
#<EMAIL>
def publish(self, publisherName):
"""Start the delivery of the last message for a given publisher."""
subs = []
with self._subscriptions_lock:
if publisherName in self.subscriptions:
# to protect us in case a subscriber unsubs in the middle of publish()
subs = copy.copy(self.subscriptions[publisherName])
if len(subs) == 0:
return
# basic message rate control:
# timeslice - if this publisher is looping try to let others have deliveries
timeslice = 128
while True:
if not timeslice:
break
timeslice -= 1
message = self.cabinet.pull(publisherName)
if message == None:
break
for subscriber in subs:
try:
self.carrier.deliver(subscriber, message)
except NotFoundSubscription: pass
#<EMAIL>
def newMessageFrom(self, publisherName):
"""Called by FilingCabinet to notify of a new message from the given publisher."""
self.publish(publisherName)
return
## NOTE: not needed for now
defaultTimeout = 3.0
if self._timer[0] is not None:
now = time.time()
mtime = self._timer[1]
oldTimeout = self._timer[2]
if (now + defaultTimeout) - (mtime + oldTimeout) < 1.0:
return # if publish gets called in less than a second do nothing
self._timer[0] = threading.Timer(defaultTimeout, self.publish, args=[publisherName])
self._timer[1] = time.time()
self._timer[2] = defaultTimeout
<file_sep>import sqlite3
import os
import time
from utils.misc import Singleton
class Storage(Singleton):
"""sqlite3-based message storage class."""
def __init__(self):
self._dbpath = False
self._initialized = False
def init(self, dbpath):
if self._initialized:
return
self._dbpath = dbpath
self._opendb()
if os.lstat(self._dbpath)[6] == 0:
query = "CREATE TABLE hgw2_data ( id VARCHAR, timestamp REAL, data VARCHAR );"
cursor = self.connection.cursor()
cursor.execute(query)
self._initialized = True
def _opendb(self):
self.connection = sqlite3.connect(self._dbpath)
def close(self):
self.connection.close()
def add(self, nodeid, data):
self._opendb()
query = "INSERT INTO hgw2_data VALUES ('%s', %s, '%s');" % (nodeid, time.time(), data)
cursor = self.connection.cursor()
cursor.execute(query)
self.connection.commit()
cursor.close()
def get(self, nodeid, startdate=None, enddate=None):
self._opendb()
query = "SELECT * FROM hgw2_data WHERE id = '%s';" % nodeid
if startdate and enddate:
query = query[:-1] + ' AND timestamp > %s AND timestamp < %s;' % (startdate, enddate)
cursor = self.connection.cursor()
cursor.execute(query)
ret = cursor.fetchall()
cursor.close()
return ret
if __name__ == '__main__':
testPath = '/tmp/hgw2.db'
try:
os.unlink(testPath)
except: pass
s = Storage()
s.init(testPath)
for x in range(40, 70):
s.add('test%s' % x, 'fakedata%s' % x)
time.sleep(0.01)
for x in range(50, 60):
print s.get('test%s' % x)
s.close()
<file_sep>import GenericNode
from interfaces import tcpInterface
class TcpExample(GenericNode.GenericNode):
"""Forwards data from the testing tcp interface."""
interface = tcpInterface.TcpInterface()
interfacename = 'tcp'
def newValue(self, nodename, value):
return {'example': value}
<file_sep>import string
import os,sys
class Nodes_configurator:
""" manage nodes configuration """
def __init__(self):
self._nodes_list = [] #memorizzo i dizionari _sensor
self._nodes = {} #key,value
def pick_node(self,id):
for elem in self._nodes_list:
_keylist=[]
_keylist = [b for a,b in elem.items()]
if id in _keylist:
return elem
def save_config(self,filename):
#per ora carico solo le config bisogna scrivere editor
pass
def load_config(self,filename):
_line=''
_part =[]
_file = open(filename)
while 1:
_line = _file.readline()
if _line.find("end") >= 0:
print _line.find("end")
break
else:
if _line == "\n" :
self._nodes_list.append(self._nodes)
self._nodes= {}
else:
_part = _line.split(':')
self._nodes[_part[0]] = _part[1].rstrip("\n")
def main():
_aaa=Nodes_configurator()
_aaa.load_config(os.path.dirname(sys.argv[0]) + "/nodes_installed.txt")
print _aaa.pick_node("001")
if __name__ == '__main__':
main()
<file_sep>import threading
import log
class DataCollector(object):
"""Interface between sensors and postOffice."""
def __init__(self):
# refence to the filing cabinet object
self.cabinet = None
def collect(self, publisherName, data):
"""Collect data from a publisher.
Arguments:
publisherName -- the name of the publisher, usually a sensor
data -- new data from the given publisher
"""
assert type(publisherName) is type('')
log.debug('received data [%s] from [%s]' % (data, publisherName))
self.cabinet.push(publisherName, data)
<file_sep>import serial
import threading
import Queue
import string
import binascii
import time
import base64
import nodes.zigbee_configurator as zb
class MySerial(threading.Thread):
def __init__(self, myport, dataCollector = None):
self._MODE = 1
self._POLL_MODE = 1
self._CMD_MODE = 2
self._PARSE_MODE = 3
self._cmd_buf_lines = 0
self._nbyte = 0
self._buffer = ""
self._count_buffer_reads = 0
self._max_count_buffer_reads = 0
self._active_cmd = ""
self._max_buf_count = 1
#dataCollector e' per callback inoltro dati
self._dataCollector = dataCollector
self._ser = serial.Serial(
port = myport,
baudrate = 9600,
bytesize = serial.EIGHTBITS, #number of databits
parity = serial.PARITY_NONE, #enable parity checking
stopbits = serial.STOPBITS_ONE, #number of stopbits
timeout = 0, #set a timeout value, None for waiting forever
xonxoff = 0, #enable software flow control
rtscts = 0 #enable RTS/CTS flow control
)
# print "port: %s" % myport
self._data_queue = Queue.Queue(1024) #per ora cosi' todo dinamica
self._mode_dic = {
self._POLL_MODE : self.poll_data,
self._CMD_MODE : self.get_rsp_to_cmd,
self._PARSE_MODE : self.parse_buffer_data
}
self._zb_cmds = zb.Zigbee_protocol_cmd(self)
threading.Thread.__init__(self, target=self.runloop)
self.setDaemon(1)
def runloop(self):
# print "running serial thread"
# self._mylock = threading.Lock()
self.open_port()
while 1:
#print "_MODE: %s" % self._MODE
self._mode_dic.get(self._MODE,0)()
self.close_port()
def poll_data(self):
if self._ser.inWaiting() > self._max_buf_count :
sread = self._ser.read(self._max_buf_count + 1)
self._ser.flushInput()
if sread != '':
self.data_queue_push_data( (sread) )
# self.data_queue_push_data( base64.b64encode(sread) )
def get_rsp_to_cmd(self):
# print "in get rsp cmd"
if self._ser.inWaiting() >= self._nbyte:
self._cmd_buf_lines=self._cmd_buf_lines + 1
print "->char in buf: %s " % self._ser.inWaiting()
print "->nbyte: %s " % self._nbyte
self._buffer = self._buffer + self._ser.read(self._nbyte)
print "->buffer native: %s" % self._buffer
self._ser.flushInput() #reset del _buffer della seriale
if self._cmd_buf_lines >= self._max_count_buffer_reads:
#todo: gestione dei terminatori delle risposte
if string.find(self._buffer,"OK") > 0:
print "-->returned ok"
self._cmd_buf_lines = 0
self._nbyte=0
self._buffer=""
self._zb_cmds.exec_zb_cmd(self._active_cmd)
return
for i0 in self._buffer:
print "->buffer read(hex): %s" % binascii.hexlify(i0)
self._cmd_buf_lines = 0
self._buffer=""
self._nbyte=0
self._MODE = self._PARSE_MODE
self._MODE = self._POLL_MODE
def parse_buffer_data(self):
print "-> in parse buffer data"
zb_data = []
for i0 in self._buffer:
if i0 != "0D":
zb_data.append(i0)
self._buffer=""
self._MODE = self._POLL_MODE
self._zb_cmds.parse_zb_responses(zb_data)
def data_queue_push_data(self,data):
try:
self._data_queue.put(data)
except Queue.Full:
print "out_of_bound_in _data_queue" #todo: da vedere come gestire
def data_queue_pull_data(self):
data = self._data_queue.get()
return data
def data_queue_status(self):
return self._data_queue.empty()
def close_port(self):
self._ser.close()
def send_data(self,data):
print "send data: %s" % data
self._ser.write(data)
def open_port(self):
self._ser.open()
def scan(self):
"""scan for _available ports return a list of tuples (num, name)"""
_available = []
for i in range(256):
try:
s = serial.Serial(i)
_available.append( (i, s.portstr))
s.close() #explicit close 'cause of delayed GC in java
except serial.SerialException:
pass
print "Found ports:"
for n,s in _available:
print "(%d) %s" % (n,s)
def set_mode(self,mode):
self._MODE = mode
def set_num_byte_to_read(self,byte):
self._nbyte = byte
def set_buf_counter_reads(self,num):
self._count_buffer_reads = 0
self._max_count_buffer_reads = num
def set_active_cmd(self,cmd):
self._active_cmd = cmd
def set_CMD_MODE(self):
print "set cmd mode"
self.set_mode(self._CMD_MODE)
def set_POLL_MODE(self):
print"set poll mode"
self.set_mode(self._POLL_MODE)
# FIXME: fixa il nome
class NotFoundConfig(BaseException): pass
def init(collector, config=None):
if type(config) is not dict or not config.has_key('device'):
raise NotFoundConfig
return MySerial(config['device'], collector)
<file_sep>import GenericInterface
import serial
class SerialInterface(GenericInterface.GenericInterface):
"""Serial interface used to read values from ziqbee receiver."""
def init(self, config={'device': '/dev/ttyS0'}):
self.ser = serial.Serial(config['device'])
return True
def runloop(self):
self.ser.open()
while True:
vid = 1
timestamp = -1
data = self.ser.read(15)
self.newValue(vid, timestamp, data)
self.ser.close()
def _fakeNewValue(a, b, c):
"""for testing."""
print a, b, c
if __name__ == '__main__':
s = SerialInterface()
s.init()
s.newValue = _fakeNewValue
s.runloop()
<file_sep>import pygame, Image
from scipy import *
import sys
import socket
import threading
from pygame.locals import *
class VideoReceiver(threading.Thread):
def __init__(self,server_ip,port,buf_size,mode):
self._mode = mode
self._host = server_ip
self._port = port
self._buf_size = buf_size
self._addr = (self._host,self._port)
self._max_x_screen = 352
self._max_y_screen = 288
self.Tcp_sock0 = 0
self._exitflag = 0
self._vid_surface1=pygame.Surface((self._max_x_screen,self._max_y_screen))
threading.Thread.__init__(self)
def run(self):
print "-> start image receiver thread"
pygame.init()
if self._mode == 0:
self._screen = pygame.display.set_mode( (self._max_x_screen,self._max_y_screen) )
self.Tcp_sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.Tcp_sock0.bind(self._addr)
self.Tcp_sock0.listen(5)
conn,addr=self.Tcp_sock0.accept()
img_buf =''
while not pygame.event.get( pygame.QUIT ) and self._exitflag== 0:
img_buf = img_buf + conn.recv( self._buf_size )
if len(img_buf) >= (self._max_x_screen * self._max_y_screen *3):
img_buf0 = Image.frombuffer( 'RGB', (self._max_x_screen,self._max_y_screen), img_buf ) #img_buf un oggetto di modulo IMAGE(pil)
self._vid_surface1 = pygame.image.fromstring( img_buf0.tostring('raw','BGR'), (self._max_x_screen,self._max_y_screen), 'RGB')
if self._mode == 0:
self._screen.blit( self._vid_surface1,(0,0) )
pygame.display.flip()
img_buf =''
pygame.event.pump()
self.Tcp_sock0.close()
pygame.quit()
def getvideobuffer(self):
#print "video buffer:" ,self._vid_surface1.get_size()
return self._vid_surface1
def close_socket(self):
self._exitflag=1
def main():
mtu=(352*288*3) / 1024
eth0ImgReceiver = VideoReceiver('',12345,mtu,0)
eth0ImgReceiver.start()
if __name__ == '__main__':
main()<file_sep>##################################################
# file: NodeListenerService_client.py
#
# client stubs generated by "ZSI.generate.wsdl2python.WriteServiceModule"
# /usr/local/bin/wsdl2py http://localhost:2000/ncsc/hgwnodedemo/?wsdl
#
##################################################
from NodeListenerService_types import *
import urlparse, types
from ZSI.TCcompound import ComplexType, Struct
from ZSI import client
from ZSI.schema import GED, GTD
import ZSI
# Locator
class NodeListenerServiceLocator:
NodeListenerPort_address = "http://localhost:2000/ncsc/hgwnodedemo/"
def getNodeListenerPortAddress(self):
return NodeListenerServiceLocator.NodeListenerPort_address
def getNodeListenerPort(self, url=None, **kw):
return NodeListenerPortBindingSOAP(url or NodeListenerServiceLocator.NodeListenerPort_address, **kw)
# Methods
class NodeListenerPortBindingSOAP:
def __init__(self, url, **kw):
kw.setdefault("readerclass", None)
kw.setdefault("writerclass", None)
# no resource properties
self.binding = client.Binding(url=url, **kw)
# no ws-addressing
# op: connected
def connected(self, request, **kw):
if isinstance(request, connected) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(connectedResponse.typecode)
return response
# op: disconnected
def disconnected(self, request, **kw):
if isinstance(request, disconnected) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(disconnectedResponse.typecode)
return response
# op: messageSent
def messageSent(self, request, **kw):
if isinstance(request, messageSent) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(messageSentResponse.typecode)
return response
# op: errorReported
def errorReported(self, request, **kw):
if isinstance(request, errorReported) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(errorReportedResponse.typecode)
return response
# op: message
def message(self, request, **kw):
if isinstance(request, message) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(messageResponse.typecode)
return response
connected = GED("http://hgw.netcarity.net/", "connected").pyclass
connectedResponse = GED("http://hgw.netcarity.net/", "connectedResponse").pyclass
disconnected = GED("http://hgw.netcarity.net/", "disconnected").pyclass
disconnectedResponse = GED("http://hgw.netcarity.net/", "disconnectedResponse").pyclass
messageSent = GED("http://hgw.netcarity.net/", "messageSent").pyclass
messageSentResponse = GED("http://hgw.netcarity.net/", "messageSentResponse").pyclass
errorReported = GED("http://hgw.netcarity.net/", "errorReported").pyclass
errorReportedResponse = GED("http://hgw.netcarity.net/", "errorReportedResponse").pyclass
message = GED("http://hgw.netcarity.net/", "message").pyclass
messageResponse = GED("http://hgw.netcarity.net/", "messageResponse").pyclass
<file_sep>creato con:
wget http://screwdriver.felk.cvut.cz/school/netcarity/NCSecureChannel071213.zip
unzip NCSecureChannel071213.zip
<file_sep>import GenericInterface
import socket
class TcpInterface(GenericInterface.GenericInterface):
"""ASCII-based tcp interface that reads id,timestamp,data. Used only for testing."""
def init(self, config={}):
self._socket = None
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._socket.bind((config['host'], config['port']))
self._socket.listen(1)
except socket.error, e:
#raise e
return False
return True
def runloop(self):
while True:
conn, addr = self._socket.accept()
while True:
data = conn.recv(1024)
if not data:
break
data = data.split(',')
if len(data) != 3:
conn.send('ERROR:: format: id,timestamp,data\n')
else:
conn.send('ECHO:: [%s]\n' % str(data))
self.newValue(data[0], data[1], data[2])
conn.close()
<file_sep>import binascii
import log
import nodes.serial_if as ser
import nodes.zigbee_configurator as zb
import nodes.img_receiver as img_rcvr
import pygame
import sys,time,os
import threading
from pygame.locals import *
def doKeyEvent(key):
print ord(key)
def doQuitEvent():
os._exit(1)
def hex2dec(s):
return int(s, 16)
class main_interface(threading.Thread):
def __init__(self):
self.mtu = (352*288*3) /1024
self.curcomm = ser.MySerial('/dev/ttyUSB0',0)
self.zb0 = zb.Zigbee_common(self.curcomm)
self.video0 = img_rcvr.VideoReceiver('',12345,self.mtu)
self.val=['00','00']
self.gradi = 0.0
self.test_rect = pygame.Rect
self.posx_text_sens = 110
self.posy_text_sens = 0
self.posx_text_zb = 110
self.posy_text_zb = 210
self.cmds={"print_ser_data" : self.print_ser_data,
"update_keyboard" : self.update_keyboard,
"update_video":self.update_video}
self.cmd ="print_ser_data"
threading.Thread.__init__(self)
def run(self):
print "-> run main interface Thread"
pygame.init()
self.screen = pygame.display.set_mode((1024, 768))
pygame.display.set_caption('test_zigbee v.0.1')
# pygame.mouse.set_visible(1)
# sfondo = pygame.image.load("./res/sfondo_ale_0.jpg")
mybackgroundsurface = pygame.Surface(self.screen.get_size())
# mybackgroundsurface.fill((0,0,0))
# self.screen.blit(mybackgroundsurface, (0, 0))
# self.screen.blit(sfondo, (0, 0))
# self.video_surface = pygame.Surface((352,288))
self.curcomm.start()
self.video0.start()
while 1:
pygame.display.flip()
# print"executing : %s" % self.cmd
self.cmds.get(self.cmd,0)()
def print_ser_data(self):
# print "print_ser_data"
if not self.curcomm.data_queue_status():
self.val = self.curcomm.data_queue_pull_data()
print "val data serial: %s" % self.val
if len(self.val) > 1 and len(self.val) <=2:
# if len(self.val) > 1 :
self.gradi = float( hex2dec( binascii.hexlify(self.val[1])+ binascii.hexlify(self.val[0]) ) )
self.gradi = -0.08 * self.gradi + 68.0
# da (0,110) a (110,200) output sensori
print "gradi: %s" % self.gradi
text='gradi: ' + str(self.gradi)
back_color = (0,0,0)
text_color = (255,240,165)
text_height =self.print_text(text,(self.posx_text_sens,self.posy_text_sens),back_color,text_color)
self.posy_text_sens = self.posy_text_sens + text_height
if self.posy_text_sens > 200 :
# background = pygame.Surface((1024,768))
# background.fill((0, 0, 0))
# self.screen.blit(background, (0, 0))
# pygame.display.update()
self.posy_text_sens = 0
self.gradi = 0.0
self.cmd="update_keyboard"
def update_keyboard(self):
# print "update keyboard"
for event in pygame.event.get():
if event.type == KEYDOWN:
if (event.key == K_t): #b print cmd data buffer
text='test_ale'
back_color = (0,0,0)
text_color = (255,240,165)
self.print_text(text,(self.posx_text_zb,self.posy_text_zb),back_color,text_color)
self.posy_text_zb = self.posy_text_zb + 1
if (event.key == K_b): # b print cmd data buffer
self.zb0.get_cmd_buffer()
if (event.key == K_f): # f get fw version
self.zb0.send_AT_cmd("read_fw_ver")
if (event.key == K_n): # n node discover
self.zb0.send_AT_cmd("node_discover")
if (event.key == K_q): # q quit
print"quit"
doQuitEvent()
self.cmd ="update_video"
def update_video(self):
if self.video0.buf_exist():
# print "-> updating video"
buf = self.video0.get_data()
# print "len buf: %s " % buf
self.screen.blit(buf,(400,0))
self.cmd ="print_ser_data"
def get_size_text(self,text,font_color,back_color):
font = pygame.font.Font(None, 17)
text = font.render(text, True, font_color, back_color)
textRect = text.get_rect()
return textRect,text
def print_text(self,text,pos,back_color,text_color):
test_rect,text = self.get_size_text(text,text_color,back_color)
temp_surf = pygame.Surface((test_rect.right,test_rect.bottom))
temp_rect = pygame.Rect(0,0,test_rect.right,test_rect.bottom)
test_rect.left = pos[0]
test_rect.top = pos[1]
canc_rect = pygame.draw.rect(temp_surf, back_color, temp_rect, 0)
self.screen.blit(self.screen,canc_rect )
self.screen.blit(text, test_rect)
pygame.display.update()
return test_rect.height
def main():
main_if = main_interface()
main_if.start()
if __name__ == '__main__':
main()
<file_sep>from delivery import RemoteInterface
from asyncDelivery import AsynchronousDataCarrier
from syncDelivery import SynchronousDataCarrier
<file_sep>import lightblue as bt
print bt.finddevices()
s = bt.socket()
print s.connect( ( "00:A0:96:16:9D:05", 1) )
print 'connesso'
<file_sep>import threading
import time
import config
import storage
class NotImplemented(BaseException):
"""Method not implemented exception."""
pass
class NotSupportedCommand(BaseException):
"""Command not supported exception."""
pass
class NotInitializedInterface(BaseException):
"""Interface not initialized exception."""
pass
class GenericNode(object):
"""Root class for all the nodes, implements common code and some hidden magic."""
def __init__(self, dataCollector):
self._dataCollector = dataCollector
self.__shouldStop = False
self._thread = threading.Thread(target=self.run)
self._thread.setDaemon(1)
self.nodename = None
self.nodeinfo = None
self.config = None
## to not reimplment
def shouldStop(self):
return self.__shouldStop
def collect(self, vid, data):
return self._dataCollector.collect(self.nodename, data)
def command(self, cmd):
vid = self.nodeinfo['id']
return self.interface.command(vid, cmd)
## no need to always reimplement
def start(self):
self.__shouldStop = False
self._thread.start()
def stop(self):
self.__shouldStop = True
self.storage.close()
def init(self, nodename, nodeinfo, config={}):
self.nodename = nodename
self.nodeinfo = nodeinfo
self.config = config
self.storage = storage.Storage()
self.storage.init(config['dbpath'])
def generic_newValue(self, nid, timestamp, value):
assert type(nid) is type(1) and nid >= -1
assert type(timestamp) is type(1) or type(timestamp) is type(1.0)
assert timestamp >= -1
if nid == -1:
nid = int(self.nodeinfo['id'])
nodename = self.nodename
if timestamp == -1:
timestamp = time.time()
else:
timestamp = float(timestamp)
timestamp = time.strftime('%Y%m%d%H%M%S00', time.gmtime(timestamp))
msgdict = self.newValue(nodename, value)
msgstr = ''
for key in msgdict:
msgstr += "%s:%s," % (key, msgdict[key])
msgstr = msgstr[:-1]
if len(msgdict):
if not 'timestamp' in msgdict:
msgdict['timestamp'] = timestamp
if not 'nid' in msgdict:
msgdict['nid'] = nid
self.storage.add(nodename, msgstr)
self.collect(nodename, msgdict)
def run(self):
if not self.interface.isInitialized():
self.interface._isInitialized = self.interface.init(config=config.interfaces[self.interfacename])
if not self.interface.isInitialized:
raise NotInitializedInterface
self.interface.newValue = self.generic_newValue
self.interface.generic_start()
## must implement
def newValue(self, nodename, timestamp, value):
raise NotImplemented
<file_sep>import nodes.serial_if as ser
import time
import threading
class Fake_sensor(threading.Thread):
def __init__(self,refSerial):
print "fake sensor win version"
self.curSerial = refSerial
threading.Thread.__init__(self)
def run(self):
start_time = time.time()
stop_time = 0.0
delta = 5.0
while 1:
if (stop_time - start_time)> delta:
self.send_mesg("sens:0,value:10")
start_time = stop_time
stop_time = time.time()
def send_mesg(self,msg):
self.curSerial.send_data(msg)
def main():
serial0 = ser.MySerial(0,0)
fake0 = Fake_sensor(serial0)
serial0.start()
fake0.start()
if __name__ == '__main__':
main()<file_sep>import threading
class Singleton(object):
def __new__(type):
if not '_the_instance' in type.__dict__:
type._the_instance = object.__new__(type)
return type._the_instance
def locked(func):
def locked_wrapper(*args):
lock = getattr(func, "__lock", threading.Lock())
lock.acquire()
try:
result = func(*args)
finally:
lock.release()
return result
return locked_wrapper
<file_sep>import sys,os
import threading
import gooeypy as gui
import pygame
from gooeypy.const import *
import nodes.fake_img_receiver as imgreceiver
MAXX = 1280
MAXY = 1024
VIDEOMAXX = 352
VIDEOMAXY = 288
MTU = (352*288*3) / 1024
class Hgw_user_interface(threading.Thread):
#ricordati di inserire il tema in site-packages/goooypy... di netcarity
def __init__(self,eth0ImgReceiver,xmlrpc_server):
self._curVideoReceiver = eth0ImgReceiver
self._curVideoReceiverStatus = 0
self._curXmlrpc_server = xmlrpc_server
self._curpath = os.path.dirname(sys.argv[0])
self._clock = pygame.time.Clock()
self._main_screen = pygame.display.set_mode((MAXX, MAXY),pygame.NOFRAME )
self._doorcamera_rect = pygame.Rect(0,0,MAXX,MAXY)
gui.init(myscreen = self._main_screen)
self._app = gui.App("netcarity",width = MAXX, height = MAXY)
self._btnReset = gui.Button("reset ", x=20, y=110)
self._btnGetTemp = gui.Button("get_temp ", x=20, y=150)
self._btnSendTemp = gui.Button("send_temp", x=20, y=190)
self._btnOpenVideo = gui.Button("video_on", x=20, y=230)
self._btnCloseVideo = gui.Button("video_off", x=20, y=270)
self.video_surface = pygame.Surface((VIDEOMAXX,VIDEOMAXY))
self._app.add(self._btnReset,self._btnGetTemp,self._btnSendTemp,self._btnOpenVideo,self._btnCloseVideo)
self._btnReset.connect(CLICK,self.click_button1)
self._btnOpenVideo.connect(CLICK,self.click_startvideo)
self._btnCloseVideo.connect(CLICK,self.click_stopvideo)
threading.Thread.__init__(self)
def run(self):
quit = False
while not quit:
self._clock.tick(30)
events = pygame.event.get()
for event in events:
if event.type == QUIT:
quit = True
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self._curVideoReceiver.close_socket()
sys.exit()
self._app.run(events)
self._app.draw()
myupdaterects = []
if self._curVideoReceiverStatus == 1:
self._doorcamera_rect = self._main_screen.blit( self._curVideoReceiver.getvideobuffer(),(300,0) )
myupdaterects.append(self._doorcamera_rect)
pygame.display.update(myupdaterects)
else:
pass
myupdaterects = []
#self._main_screen.blit(self._image, (0,0))
gui.update_display()
self.stop_video_thread()
def click_button1(self):
print "reset"
def click_startvideo(self):
print "-> start door camera video"
self._curVideoReceiverStatus = 1
def click_stopvideo(self):
print "-> stop door camera video"
self._curVideoReceiverStatus = 0
class RpcCommander:
def __init__(self):
import xmlrpclib
self._server= xmlrpclib.ServerProxy('http://localhost:8081/')
def command(self,cmd):
return self._server.action('xyzv_cmd')
def main():
print os.path.dirname(sys.argv[0])
xmlrpc_server = RpcCommander()
eth0ImgReceiver = imgreceiver.VideoReceiver('',12345,MTU,1)
eth0ImgReceiver.start()
main_if = Hgw_user_interface(eth0ImgReceiver,xmlrpc_server)
main_if.start()
if __name__ == '__main__':
main()<file_sep>hgw
===
<file_sep>from messageBroker import MessageBroker
from filingCabinet import FilingCabinet
<file_sep>import sys
import time
import threading
from WebServiceClientService_client import *
ENDPOINT = "http://0.0.0.0:2000/ncsc/hgwnodedemo"
def initClient():
logfile = file('zsiclient.log', 'w+')
loc = WebServiceClientServiceLocator()
kw = { 'tracefile' : logfile }
port = loc.getWebServiceClientPort(**kw)
return port
import wserver
def initServer():
t1 = threading.Thread(target=wserver.initServer)
t1.setDaemon(0)
t1.start()
def log(msg):
print("%s - %s" % (time.ctime(), msg))
global msg_id
msg_id = 0
def temp_sendMessage(ncsc, temp, priority=30):
global msg_id
msg_id += 1
msg = '<?xml version="1.0" encoding="UTF-8"?>' + \
'<ncmessage priority="%s" msgid="temperature_%s" source="temperature#1" ' + \
'timestamp="2007103117150000" type="node_data" version="1.0">' + \
'<node id="temperature#1" type="temperature_sensor">' + \
'<value key="temperature">%s</value>' + \
'<value key="location">bedroom</value>' + \
'<value key="text">testext</value>' + \
'<value key="coordinates">13,17,69</value>' + \
'</node>' + \
'</ncmessage>'
msg = msg % (priority, msg_id, temp)
log("sending message: " + msg)
sm = sendMessage()
sm._arg0 = priority
sm._arg1 = msg
sm._arg2 = ENDPOINT
result = ncsc.sendMessage(sm)
#log("sendMessage result: " + str(dir(result)))
return result
def main():
initServer()
ncsc = initClient()
log("waiting 5s for startServer")
time.sleep(5)
ret_isConnected = False
while ret_isConnected is False:
log("calling isConnected()")
iscon = isConnected()
ret = ncsc.isConnected(iscon)
ret_isConnected = ret._return
log("connected")
temp_sendMessage(ncsc, '21.0')
#NOTA: crasha il demone, a cosa serve se non c'e' connect() ?
#time.sleep(5)
#log("disconnecting...")
#disc = disconnect()
#ret = ncsc.disconnect(disc)
#log("disconnected: " + str(ret))
time.sleep(5)
log("exiting")
sys.exit()
main()
<file_sep>from collection import DataCollector
<file_sep>class Zigbee_common:
""" all you need to config a zigbee network with """
def __init__(self,serref):
self._sercom_ref = serref
def send_AT_cmd(self,new_cmd):
print "_cmd: %s" % new_cmd
self._cmd = new_cmd
self._sercom_ref.set_active_cmd(new_cmd)
self.send_AT_start()
def send_AT_start(self):
self._sercom_ref.set_CMD_MODE()
self._sercom_ref.set_num_byte_to_read(5)
self._sercom_ref.set_buf_counter_reads(0)
self._sercom_ref.send_data('+++')
class Zigbee_protocol_cmd:
""" zb at command set """
def __init__(self,serref):
self._cmds={
"read_fw_ver" : self.read_fw_ver,
"node_discover" : self.node_discover,
"read_pan_id" : self.read_pan_id
}
self._cmd ="dummy"
self._sercom_ref = serref
def exec_zb_cmd(self,cmd):
self._cmds.get(cmd,0)()
def read_fw_ver(self):
print "->in read fw version"
self._sercom_ref.set_CMD_MODE()
self._sercom_ref.set_num_byte_to_read(5)
self._sercom_ref.set_buf_counter_reads(0)
self._sercom_ref.send_data('AT VR \r\n')
def read_pan_id(self):
self._sercom_ref.set_CMD_MODE()
self._sercom_ref.set_num_byte_to_read(5)
self._sercom_ref.set_buf_counter_reads(1)
self._sercom_ref.send_data('AT ID \r\n')
def node_discover(self):
self._sercom_ref.set_CMD_MODE()
self._sercom_ref.set_num_byte_to_read(5)
self._sercom_ref.set_buf_counter_reads(10)
self._sercom_ref.send_data('AT ND \r\n')
def parse_zb_responses(self,data):
print "-> in zigbee parse zb resp %s" % data
if self._cmd =="read_fw_ver" :
print"data0: %s" % data[0]
print"data1: %s" % data[1]
class ZigBee_net_status:
"""hold data e configs of current zigbee networks status"""
def __init__(self):
pass
<file_sep>import threading
import socket
import vidcap
import fake_img_receiver
import sys
class VideoSender(threading.Thread):
def __init__(self,server_ip,port,buf_size):
self.host = server_ip
self.port = port
self.tcp_buf_len = buf_size
self.addr = (self.host ,self.port)
threading.Thread.__init__(self)
self.dev = vidcap.new_Dev( 1, False )
def run(self):
print "-> start image sender"
_retry = 0
self.Tcp_sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while _retry < 1000:
_retry = _retry + 1
try:
self.Tcp_sock0.connect(self.addr)
except socket.error:
print "connection error retry"
img_buf = ''
while 1:
img_buf, width, height = self.dev.getbuffer()
if len(img_buf) > 0 :
start = 0
for i0 in range(0,len(img_buf)+self.tcp_buf_len,self.tcp_buf_len):
try:
self.Tcp_sock0.send(img_buf[start:i0])
except socket.error:
sys.exit()
start = i0
self.Tcp_sock0.close()
def main():
#test mando immagini
mtu=(352*288*3) / 1024
eth0ImgSender = VideoSender('10.0.0.59',12345,mtu)
#eth0ImgReceiver = fake_img_receiver.VideoReceiver('',12345,mtu)
#eth0ImgReceiver.start()
eth0ImgSender.start()
if __name__ == '__main__':
main()
<file_sep>import Image
from scipy import *
import sys
import socket
import threading
import pygame
class VideoReceiver(threading.Thread):
def __init__(self,server_ip,port,buf_size):
self._host = server_ip
self._port = port
self._buf_size = buf_size
self._addr = (self._host,self._port)
self._max_x_screen = 352
self._max_y_screen = 288
self.vid_surface1 = ''
threading.Thread.__init__(self)
def run(self):
print "-> run image receiver thread"
Tcp_sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Tcp_sock0.bind(self._addr)
Tcp_sock0.listen(2)
conn,addr=Tcp_sock0.accept()
print " conn:%s addr: %s" % (conn,addr)
img_buf =''
while 1 :
img_buf = img_buf + conn.recv( self._buf_size )
if len(img_buf) >= (self._max_x_screen * self._max_y_screen *3):
img_buf0 = Image.frombuffer( 'RGB', (self._max_x_screen,self._max_y_screen), img_buf ) #img_buf un oggetto di modulo IMAGE(pil)
self.vid_surface1 = pygame.image.fromstring( img_buf0.tostring('raw','BGR'), (self._max_x_screen,self._max_y_screen), 'RGB')
self.img_queue_count = 1
img_buf =''
def get_data(self):
self.img_queue_count = 0
return self.vid_surface1
def buf_exist(self):
if self.img_queue_count == 1:
return 1
else:
return 0
<file_sep>CONFIG=hgw2/docs/epydoc.conf
TARGET=api-hgw2
cd ..; mkdir -p $TARGET; rm -f ./$TARGET/*; epydoc --config $CONFIG
echo
echo
echo
echo "CREATA DOCUMENTAZIONE IN ../"$TARGET
echo "CONFIGURAZIONE UTILIZZATA: "$CONFIG
echo
<file_sep>##################################################
# file: WebServiceClientService_types.py
#
# schema types generated by "ZSI.generate.wsdl2python.WriteServiceModule"
# /usr/local/bin/wsdl2py ncsc.wsdl
#
##################################################
import ZSI
import ZSI.TCcompound
from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED
##############################
# targetNamespace
# http://webservice.securechannel.netcarity.net/
##############################
class ns0:
targetNamespace = "http://webservice.securechannel.netcarity.net/"
class sendMessage_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "sendMessage")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.sendMessage_Def.schema
TClist = [ZSI.TCnumbers.Iint(pname="arg0", aname="_arg0", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname="arg1", aname="_arg1", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded")), ZSI.TC.String(pname="arg2", aname="_arg2", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._arg0 = None
self._arg1 = None
self._arg2 = None
return
Holder.__name__ = "sendMessage_Holder"
self.pyclass = Holder
class sendMessageResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "sendMessageResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.sendMessageResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "sendMessageResponse_Holder"
self.pyclass = Holder
class isConnected_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "isConnected")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.isConnected_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "isConnected_Holder"
self.pyclass = Holder
class isConnectedResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "isConnectedResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.isConnectedResponse_Def.schema
TClist = [ZSI.TC.Boolean(pname="return", aname="_return", minOccurs=1, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))]
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
self._return = None
return
Holder.__name__ = "isConnectedResponse_Holder"
self.pyclass = Holder
class disconnect_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "disconnect")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.disconnect_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "disconnect_Holder"
self.pyclass = Holder
class disconnectResponse_Def(ZSI.TCcompound.ComplexType, TypeDefinition):
schema = "http://webservice.securechannel.netcarity.net/"
type = (schema, "disconnectResponse")
def __init__(self, pname, ofwhat=(), attributes=None, extend=False, restrict=False, **kw):
ns = ns0.disconnectResponse_Def.schema
TClist = []
self.attribute_typecode_dict = attributes or {}
if extend: TClist += ofwhat
if restrict: TClist = ofwhat
ZSI.TCcompound.ComplexType.__init__(self, None, TClist, pname=pname, inorder=0, **kw)
class Holder:
typecode = self
def __init__(self):
# pyclass
return
Holder.__name__ = "disconnectResponse_Holder"
self.pyclass = Holder
class disconnect_Dec(ElementDeclaration):
literal = "disconnect"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","disconnect")
kw["aname"] = "_disconnect"
if ns0.disconnect_Def not in ns0.disconnect_Dec.__bases__:
bases = list(ns0.disconnect_Dec.__bases__)
bases.insert(0, ns0.disconnect_Def)
ns0.disconnect_Dec.__bases__ = tuple(bases)
ns0.disconnect_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "disconnect_Dec_Holder"
class disconnectResponse_Dec(ElementDeclaration):
literal = "disconnectResponse"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","disconnectResponse")
kw["aname"] = "_disconnectResponse"
if ns0.disconnectResponse_Def not in ns0.disconnectResponse_Dec.__bases__:
bases = list(ns0.disconnectResponse_Dec.__bases__)
bases.insert(0, ns0.disconnectResponse_Def)
ns0.disconnectResponse_Dec.__bases__ = tuple(bases)
ns0.disconnectResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "disconnectResponse_Dec_Holder"
class isConnected_Dec(ElementDeclaration):
literal = "isConnected"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","isConnected")
kw["aname"] = "_isConnected"
if ns0.isConnected_Def not in ns0.isConnected_Dec.__bases__:
bases = list(ns0.isConnected_Dec.__bases__)
bases.insert(0, ns0.isConnected_Def)
ns0.isConnected_Dec.__bases__ = tuple(bases)
ns0.isConnected_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "isConnected_Dec_Holder"
class isConnectedResponse_Dec(ElementDeclaration):
literal = "isConnectedResponse"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","isConnectedResponse")
kw["aname"] = "_isConnectedResponse"
if ns0.isConnectedResponse_Def not in ns0.isConnectedResponse_Dec.__bases__:
bases = list(ns0.isConnectedResponse_Dec.__bases__)
bases.insert(0, ns0.isConnectedResponse_Def)
ns0.isConnectedResponse_Dec.__bases__ = tuple(bases)
ns0.isConnectedResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "isConnectedResponse_Dec_Holder"
class sendMessage_Dec(ElementDeclaration):
literal = "sendMessage"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","sendMessage")
kw["aname"] = "_sendMessage"
if ns0.sendMessage_Def not in ns0.sendMessage_Dec.__bases__:
bases = list(ns0.sendMessage_Dec.__bases__)
bases.insert(0, ns0.sendMessage_Def)
ns0.sendMessage_Dec.__bases__ = tuple(bases)
ns0.sendMessage_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "sendMessage_Dec_Holder"
class sendMessageResponse_Dec(ElementDeclaration):
literal = "sendMessageResponse"
schema = "http://webservice.securechannel.netcarity.net/"
substitutionGroup = None
def __init__(self, **kw):
kw["pname"] = ("http://webservice.securechannel.netcarity.net/","sendMessageResponse")
kw["aname"] = "_sendMessageResponse"
if ns0.sendMessageResponse_Def not in ns0.sendMessageResponse_Dec.__bases__:
bases = list(ns0.sendMessageResponse_Dec.__bases__)
bases.insert(0, ns0.sendMessageResponse_Def)
ns0.sendMessageResponse_Dec.__bases__ = tuple(bases)
ns0.sendMessageResponse_Def.__init__(self, **kw)
if self.pyclass is not None: self.pyclass.__name__ = "sendMessageResponse_Dec_Holder"
# end class ns0 (tns: http://webservice.securechannel.netcarity.net/)
<file_sep>import threading
import xmlrpclib
import socket
import log
from collect import newnodes as nodes
from utils import SimpleThreadedXMLRPCServer
import threading
class RemoteInterface(object):
"""Exposes subscribe(), unsubscribe(), getLastDataFrom() and nodes command interface methods and via XML-RPC."""
def __init__(self):
self.address = ('0.0.0.0', 8081)
self.thread = None
self.adc = None # Async Data Carrier
self.sdc = None # Sync Data Carrier
def initServers(self):
try:
self._startXMLRPCServer()
except socket.error, e:
log.error('RemoteInterface: cannot start server: %s' % str(e))
return False
return True
def _startXMLRPCServer(self):
s = SimpleThreadedXMLRPCServer.SimpleThreadedXMLRPCServer(self.address)
s.register_function(self.subscribe)
s.register_function(self.unsubscribe)
s.register_function(self.isValidSubscription)
s.register_function(self.getLastDataFrom)
### nodes interface
s.register_function(self.command)
s.register_function(self.nodes_list)
self.thread = threading.Thread(target = s.serve_forever)
self.thread.setDaemon(1)
self.thread.start()
### asynchronous interface
###
def isValidSubscription(self, subscriptionUUID, replyAddress):
assert type(subscriptionUUID) is type('')
assert type(replyAddress) is type('')
ret = ['OK', None]
try:
valid = self.adc.isValidSubscription(subscriptionUUID, replyAddress)
ret[1] = valid
except Exception, e:
ret = ['ERR', str(e)]
return ret
def subscribe(self, publisherName, replyAddress):
assert type(publisherName) is type('')
assert type(replyAddress) is type('')
ret = ['OK', None]
try:
subscriptionUUID = self.adc.subscribe(publisherName, replyAddress)
ret[1] = subscriptionUUID
except Exception, e:
ret = ['ERR', str(e)]
log.info("subscribe(): %s - %s - %s" % (publisherName, replyAddress, subscriptionUUID))
return ret
def unsubscribe(self, publisherName, subscriptionUUID):
assert type(publisherName) is type('')
assert type(subscriptionUUID) is type('')
ret = ['OK']
try:
self.adc.unsubscribe(publisherName, subscriptionUUID)
except Exception, e:
ret = ['ERR', str(e)]
log.info("subscribe(): %s %s %s" % (publisherName, replyAddress, subscriptionUUID))
return ret
### synchronous interface
###
def getLastDataFrom(self, publisherName):
assert type(publisherName) is type('')
ret = ['OK', None]
try:
data = self.sdc.getLastDataFrom(publisherName)
ret[1] = data
except Exception, e:
ret = ['ERR', str(e)]
return ret
### nodes interface
### TODO: error handling
def command(self, nodename, cmd):
assert type(nodename) is type('')
assert type(cmd) is type('')
ret = nodes.command(nodename, cmd)
return ['OK', ret]
def nodes_list(self):
ret = nodes.nodes_list()
return ['OK', ret]
<file_sep>import xml.sax
class NCMessage(xml.sax.handler.ContentHandler):
def __init__(self):
xml.sax.handler.ContentHandler.__init__(self)
self._result = {}
# used for <value>
self._currentKey = None
self._valueText = None
def startElement(self, name, attrs):
if name == 'ncmessage':
self._result['ncmessage_attrs'] = {}
self._result['nodes'] = {}
for key in attrs.keys():
self._result['ncmessage_attrs'][key] = attrs[key]
if name == 'node':
self._currentNode = attrs.get('id', None)
self._result['nodes'][self._currentNode] = {}
self._result['nodes'][self._currentNode + '_attrs'] = {}
for key in attrs.keys():
if key == 'id':
continue
self._result['nodes'][self._currentNode + '_attrs'][key] = attrs[key]
if name == 'value':
self._result['nodes'][self._currentNode][attrs.get('key', None)] = ''
self._currentKey = attrs.get('key', None)
def characters(self, content):
if self._valueText is None:
self._valueText = ''
self._valueText = self._valueText + content
def endElement(self, name):
if name == 'node':
self._currentNode = None
if name == 'value':
self._result['nodes'][self._currentNode][self._currentKey] = self._valueText
self._currentKey = None
self._valueText = None
def getResult(self):
return self._result
from xml.sax import make_parser
from xml.sax.handler import feature_namespaces
if __name__ == '__main__':
parser = make_parser()
parser.setFeature(feature_namespaces, 0)
nc = NCMessage()
parser.setContentHandler(nc)
fileName = './msg1.xml'
parser.parse(fileName)
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint( nc.getResult() )
<file_sep>import socket
import time
import GenericInterface
import httplib
RELE1 = 1
RELE2 = 2
OUT1 = 101
OUT2 = 102
OUT3 = 103
OUT4 = 104
IN1 = 201
IN2 = 202
IN3 = 203
IN4 = 204
IN5 = 205
IN6 = 206
IN7 = 207
IN8 = 208
ANALOGIN1 = 501
ANALOGIN2 = 502
ANALOGIN3 = 503
ANALOGIN4 = 504
class BarionetInterface(GenericInterface.GenericInterface):
"""Barionet over tcp/ip interface."""
def init(self, config={}):
# HACK:
self.config = config
self._listen_ip = config['listen_ip']
self._port = config['port']
self._barionet_ip = config['barionet_ip']
self._cgi_request = config['cgi_request']
self._MAXRETRY = 3
self._udpsocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._udpsocket.setblocking(1)
self._udpsocket.settimeout(100)
try:
self._udpsocket.bind((self._listen_ip, self._port))
except socket.error, e:
print "Couldn't be a udp server on port %d : %s" % (self._port, str(e))
#raise e
return False
return True
def runloop(self):
while True:
vid = -1
timestamp = -1
data, addr = self._udpsocket.recvfrom(1024)
# remove '\r' and last ''
data = data.split('\r')
data = data[:-1]
data = data
msg = []
for value in data:
msg.append(value.split(','))
assert type(vid) is type(int())
assert type(timestamp) is type(int())
assert type(msg) is type([])
self.newValue(vid, timestamp, msg)
def open_door(self):
conn = httplib.HTTPConnection(self._barionet_ip)
conn.request('GET', self._cgi_request)
response = conn.getresponse()
return ( response.status, response.reason )
def fakeNewValue(vid, timestamp, msg):
print '%s :: %s :: %s' % (timestamp, vid, msg)
def main():
b = BarionetInterface()
b.init(config={'listen_ip': '10.0.0.2', 'port': 10000, 'barionet_ip': '10.0.0.3', 'cgi_request': '/rc.cgi?o=1,999'})
b.newValue = fakeNewValue
#b.runloop()
b.open_door()
if __name__ == '__main__':
main()
<file_sep>import xmlrpclib
import SimpleXMLRPCServer
import time
import sys
def receiveData(subscriptionUUID, msg):
print 'receiveData(): %s - %s' % (subscriptionUUID, msg)
return ['OK']
def main():
SERVER_ADDRESS = 'http://localhost:8081/'
MY_ADDRESS = ('localhost',10001)
if len(sys.argv) < 2:
print "uso: %s id_del_nodo" % sys.argv[0]
sys.exit(-1)
publisherName = str( sys.argv[-1] )
server = SimpleXMLRPCServer.SimpleXMLRPCServer( MY_ADDRESS )
server.register_function(receiveData)
sp = xmlrpclib.ServerProxy(SERVER_ADDRESS)
myAddr = 'http://localhost:10001'
print 'getting nodes list'
print 'list: ' + str(sp.nodes_list())
print 'checking publisher status'
print 'status: ' + str(sp.command(publisherName, 'status'))
ret, uuid1 = sp.subscribe(publisherName, myAddr)
print "%s %s - isValidSubscription for %s: %s" % (ret, uuid1, publisherName, sp.isValidSubscription(uuid1, myAddr))
try:
print 'waiting for messages from [%s]' % publisherName
server.serve_forever()
except KeyboardInterrupt:
print 'unsubscribe: ' + str(sp.unsubscribe(publisherName, uuid1))
main()
<file_sep>echo "ATTENZIONE: RICHIEDE HGWDemoService.jarda HGWDemoService.zip"
echo ""
echo ""
JAVA_HOME=/opt/java1.6 CLASSPATH="/usr/share/java/axis/axis.jar:/usr/share/java/axis/saaj.jar:/usr/share/java/axis/jaxrpc.jar:/usr/share/java/wsdl4j.jar:/usr/share/java/commons-discovery.jar:/usr/share/java/commons-logging.jar:./HGWDemoService.jar" jython client2.py
<file_sep>import threading,socket
import sys,os,string
class Barionet_controller:
def __init__(self,listenip,listenport):
self._port = listenport
self._listenip = listenip
self._RELE1 = 1
self._RELE2 = 2
self._OUT1 = 101
self._OUT2 = 102
self._OUT3 = 103
self._OUT4 = 104
self._IN1 = 201
self._IN2 = 202
self._IN3 = 203
self._IN4 = 204
self._IN5 = 205
self._IN6 = 206
self._IN7 = 207
self._IN8 = 208
self._ANALOGIN1 = 501
self._ANALOGIN2 = 502
self._ANALOGIN3 = 503
self._ANALOGIN4 = 504
self._udpsocket0 = 0
self._msg = ''
self._rspip= ''
self._MAXRETRY =3
#network
def setup_udpsocket(self):
self._udpsocket0 = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self._udpsocket0.setblocking(1)
self._udpsocket0.settimeout(100)
try:
self._udpsocket0.bind(( self._listenip ,self._port))
except socket.error, err:
print "Couldn't be a udp server on port %d : %s" % (self._port, err)
raise SystemExit
def close_udpsocket(self):
self._udpsocket0.close()
def send_msg(self,msg,host,port):
self._udpsocket0.sendto(msg,(host,port))
def get_rsp(self):
self._msg ,self._rspip = self._udpsocket0.recvfrom(1024)
print "Server %s responded %s " % ( self._rspip[0], self._msg)
def check_rsp(self,exprsp):
if self._msg.find(exprsp) < 0:
return 0
else:
return 1
#commands
def get_iolist(self,host,port):
self.send_msg("iolist", host, port)
def get_version(self,host,port):
self.send_msg("version", host, port)
def set_io(self,io,status,host,port):
self.send_msg("setio,"+ str(io) + "," + status+ "\n", host, port)
def get_io(self,io,host,port):
self.send_msg("getio,"+ str(io) + "\n" , host, port)
def main():
test = Barionet_controller('10.0.0.2',10000)
test.setup_udpsocket()
print "test get version"
for i0 in range(test._MAXRETRY):
print "retry: %d" % i0
test.get_version('10.0.0.3',12345)
test.get_rsp()
if test.check_rsp('version'):
test._msg=''
break
test.close_udpsocket()
test.setup_udpsocket()
print "test get iolist"
for i0 in range(test._MAXRETRY):
print "retry: %d" % i0
test.get_iolist('10.0.0.3',12345)
test.get_rsp()
if test.check_rsp('io'):
test._msg=''
break
test.close_udpsocket()
test.setup_udpsocket()
print "test set rele1"
for i0 in range(test._MAXRETRY):
print "retry: %d" % i0
test.set_io(test._RELE2,'999','10.0.0.3',12345)
test.get_rsp()
if test.check_rsp('change'):
test._msg=''
break
test.close_udpsocket()
test.setup_udpsocket()
print "test get status rele 1"
for i0 in range(test._MAXRETRY):
print "retry: %d" % i0
test.get_io(test._RELE2, '10.0.0.3',12345)
test.get_rsp()
if test.check_rsp('state'):
test._msg=''
break
test.close_udpsocket()
while 1:pass
if __name__ == '__main__':
main()
<file_sep>##################################################
# file: WebServiceClientService_client.py
#
# client stubs generated by "ZSI.generate.wsdl2python.WriteServiceModule"
# /usr/local/bin/wsdl2py ncsc.wsdl
#
##################################################
from WebServiceClientService_types import *
import urlparse, types
from ZSI.TCcompound import ComplexType, Struct
from ZSI import client
from ZSI.schema import GED, GTD
import ZSI
# Locator
class WebServiceClientServiceLocator:
WebServiceClientPort_address = "http://localhost:2001/ncsc/ncsc"
def getWebServiceClientPortAddress(self):
return WebServiceClientServiceLocator.WebServiceClientPort_address
def getWebServiceClientPort(self, url=None, **kw):
return WebServiceClientPortBindingSOAP(url or WebServiceClientServiceLocator.WebServiceClientPort_address, **kw)
# Methods
class WebServiceClientPortBindingSOAP:
def __init__(self, url, **kw):
kw.setdefault("readerclass", None)
kw.setdefault("writerclass", None)
# no resource properties
self.binding = client.Binding(url=url, **kw)
# no ws-addressing
# op: disconnect
def disconnect(self, request, **kw):
if isinstance(request, disconnect) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(disconnectResponse.typecode)
return response
# op: isConnected
def isConnected(self, request, **kw):
if isinstance(request, isConnected) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(isConnectedResponse.typecode)
return response
# op: sendMessage
def sendMessage(self, request, **kw):
if isinstance(request, sendMessage) is False:
raise TypeError, "%s incorrect request type" % (request.__class__)
# no input wsaction
self.binding.Send(None, None, request, soapaction="", **kw)
# no output wsaction
response = self.binding.Receive(sendMessageResponse.typecode)
return response
disconnect = GED("http://webservice.securechannel.netcarity.net/", "disconnect").pyclass
disconnectResponse = GED("http://webservice.securechannel.netcarity.net/", "disconnectResponse").pyclass
isConnected = GED("http://webservice.securechannel.netcarity.net/", "isConnected").pyclass
isConnectedResponse = GED("http://webservice.securechannel.netcarity.net/", "isConnectedResponse").pyclass
sendMessage = GED("http://webservice.securechannel.netcarity.net/", "sendMessage").pyclass
sendMessageResponse = GED("http://webservice.securechannel.netcarity.net/", "sendMessageResponse").pyclass
<file_sep>import GenericInterface
import time
import datetime
import random
class SerialExample(GenericInterface.GenericInterface):
"""Example/fake serial interface for testing."""
def init(self, config={'device': '/dev/ttyS0'}):
self.config = config
return True
def runloop(self):
while True:
time.sleep(3)
vid = 1
timestamp = -1
valori = ['111.0', '222.0', '333.0', '444.0']
self.newValue(vid, timestamp, valori[random.randint(0, 3)])
def command(self, vid, cmd):
if cmd == 'status':
return 'STATUS_OK'
return 'NOT_SUPPORTED'
<file_sep>import sys
import time
import net.netcarity.hgw.DemoHGWService
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import javax.xml.ws.Endpoint
import net.netcarity.ncscclient.jaxws.WebServiceClient;
import net.netcarity.ncscclient.jaxws.WebServiceClientService;
from net.netcarity.ncscclient.jaxws import *
class HGWTest(object):
def run(self):
log("publishing myself")
demoHGW = net.netcarity.hgw.DemoHGWService()
endpoint = javax.xml.ws.Endpoint.publish("http://localhost:2000/ncsc/hgwnodedemo", demoHGW)
connected = 0
while not connected:
print("connecting to NCSC WS")
service = net.netcarity.ncscclient.jaxws.WebServiceClientService()
ncsc = service.getWebServiceClientPort()
connected = ncsc.isConnected()
print connected
log("sleeping for 10s")
time.sleep(10)
def messageReceived(self, msg):
print 'received: ' + str(msg)
def disconnected(self, msg):
print 'disconnected: ' + str(msg)
def messageSent(self, id):
pass
"""
public void messageReceived(String msg) {
synchronized(this) {
notifyAll();
}
}
public void disconnected(String msg) {
// break all waitings due to disconnected channel
synchronized(this) {
notifyAll();
}
}
public void messageSent(String id) {
//notifyAll();
}
"""
global msgId
msgId = 0
def getMsgId():
global msgId
msgId += 1
return str(msgId)
def getCurrTime():
sdf = java.text.SimpleDateFormat("yyyyMMddHHmmssS")
return str(sdf.format(java.util.Date()))
def log(msg):
print("%s - %s" % (time.ctime(), msg))
def main():
h = HGWTest()
h.run()
main()
<file_sep>import log
class SynchronousDataCarrier(object):
"""Synchronous data request interface for RemoteInterface."""
def __init__(self):
self.cabinet = None
def getLastDataFrom(self, publisherName):
ret = self.cabinet.pull_last(publisherName)
if not ret:
ret = ""
return ret
<file_sep>/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2004-2008 <NAME> <<EMAIL>>
*
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#define VERSION "3.7"
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <getopt.h>
#include <string.h>
#include <dbus/dbus.h>
#define INTERFACE "org.bluez.Security"
static char *passkey = NULL;
static char *address = NULL;
static volatile sig_atomic_t __io_canceled = 0;
static volatile sig_atomic_t __io_terminated = 0;
static void sig_term(int sig)
{
__io_canceled = 1;
}
static DBusHandlerResult agent_filter(DBusConnection *conn,
DBusMessage *msg, void *data)
{
const char *name, *old, *new;
if (!dbus_message_is_signal(msg, DBUS_INTERFACE_DBUS, "NameOwnerChanged"))
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &old,
DBUS_TYPE_STRING, &new, DBUS_TYPE_INVALID)) {
fprintf(stderr, "Invalid arguments for NameOwnerChanged signal");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if (!strcmp(name, "org.bluez") && *new == '\0') {
fprintf(stderr, "Passkey service has been terminated\n");
__io_terminated = 1;
}
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static DBusHandlerResult request_message(DBusConnection *conn,
DBusMessage *msg, void *data)
{
DBusMessage *reply;
const char *path, *address;
dbus_bool_t numeric;
if (!passkey)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_STRING, &path, DBUS_TYPE_STRING, &address,
DBUS_TYPE_BOOLEAN, &numeric, DBUS_TYPE_INVALID)) {
fprintf(stderr, "Invalid arguments for passkey Request method");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
reply = dbus_message_new_method_return(msg);
if (!reply) {
fprintf(stderr, "Can't create reply message\n");
return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
printf("Passkey request for device %s\n", address);
dbus_message_append_args(reply, DBUS_TYPE_STRING, &passkey,
DBUS_TYPE_INVALID);
dbus_connection_send(conn, reply, NULL);
dbus_connection_flush(conn);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
static DBusHandlerResult confirm_message(DBusConnection *conn,
DBusMessage *msg, void *data)
{
DBusMessage *reply;
const char *path, *address, *value;
if (!passkey)
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_STRING, &path, DBUS_TYPE_STRING, &address,
DBUS_TYPE_STRING, &value, DBUS_TYPE_INVALID)) {
fprintf(stderr, "Invalid arguments for passkey Confirm method");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
printf("Confirm request for device %s\n", address);
reply = dbus_message_new_method_return(msg);
if (!reply) {
fprintf(stderr, "Can't create reply message\n");
return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
dbus_connection_send(conn, reply, NULL);
dbus_connection_flush(conn);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
static DBusHandlerResult cancel_message(DBusConnection *conn,
DBusMessage *msg, void *data)
{
DBusMessage *reply;
const char *path, *address;
if (!dbus_message_get_args(msg, NULL,
DBUS_TYPE_STRING, &path, DBUS_TYPE_STRING, &address,
DBUS_TYPE_INVALID)) {
fprintf(stderr, "Invalid arguments for passkey Confirm method");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
printf("Request canceled for device %s\n", address);
reply = dbus_message_new_method_return(msg);
if (!reply) {
fprintf(stderr, "Can't create reply message\n");
return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
dbus_connection_send(conn, reply, NULL);
dbus_connection_flush(conn);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
static DBusHandlerResult release_message(DBusConnection *conn,
DBusMessage *msg, void *data)
{
DBusMessage *reply;
if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_INVALID)) {
fprintf(stderr, "Invalid arguments for passkey Release method");
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
if (!__io_canceled)
fprintf(stderr, "Passkey service has been released\n");
__io_terminated = 1;
reply = dbus_message_new_method_return(msg);
if (!reply) {
fprintf(stderr, "Can't create reply message\n");
return DBUS_HANDLER_RESULT_NEED_MEMORY;
}
dbus_connection_send(conn, reply, NULL);
dbus_connection_flush(conn);
dbus_message_unref(reply);
return DBUS_HANDLER_RESULT_HANDLED;
}
static DBusHandlerResult agent_message(DBusConnection *conn,
DBusMessage *msg, void *data)
{
if (dbus_message_is_method_call(msg, "org.bluez.PasskeyAgent", "Request"))
return request_message(conn, msg, data);
if (dbus_message_is_method_call(msg, "org.bluez.PasskeyAgent", "Confirm"))
return confirm_message(conn, msg, data);
if (dbus_message_is_method_call(msg, "org.bluez.PasskeyAgent", "Cancel"))
return cancel_message(conn, msg, data);
if (dbus_message_is_method_call(msg, "org.bluez.PasskeyAgent", "Release"))
return release_message(conn, msg, data);
return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}
static const DBusObjectPathVTable agent_table = {
.message_function = agent_message,
};
static int register_agent(DBusConnection *conn, const char *agent_path,
const char *remote_address, int use_default)
{
DBusMessage *msg, *reply;
DBusError err;
const char *path, *method, *address = remote_address;
if (!dbus_connection_register_object_path(conn, agent_path,
&agent_table, NULL)) {
fprintf(stderr, "Can't register object path for agent\n");
return -1;
}
if (use_default) {
path = "/org/bluez";
method = "RegisterDefaultPasskeyAgent";
} else {
path = "/org/bluez/hci0";
method = "RegisterPasskeyAgent";
}
msg = dbus_message_new_method_call("org.bluez", path, INTERFACE, method);
if (!msg) {
fprintf(stderr, "Can't allocate new method call\n");
return -1;
}
if (use_default)
dbus_message_append_args(msg, DBUS_TYPE_STRING, &agent_path,
DBUS_TYPE_INVALID);
else
dbus_message_append_args(msg, DBUS_TYPE_STRING, &agent_path,
DBUS_TYPE_STRING, &address, DBUS_TYPE_INVALID);
dbus_error_init(&err);
reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
dbus_message_unref(msg);
if (!reply) {
fprintf(stderr, "Can't register passkey agent\n");
if (dbus_error_is_set(&err)) {
fprintf(stderr, "%s\n", err.message);
dbus_error_free(&err);
}
return -1;
}
dbus_message_unref(reply);
dbus_connection_flush(conn);
return 0;
}
static int unregister_agent(DBusConnection *conn, const char *agent_path,
const char *remote_address, int use_default)
{
DBusMessage *msg, *reply;
DBusError err;
const char *path, *method, *address = remote_address;
if (use_default) {
path = "/org/bluez";
method = "UnregisterDefaultPasskeyAgent";
} else {
path = "/org/bluez/hci0";
method = "UnregisterPasskeyAgent";
}
msg = dbus_message_new_method_call("org.bluez", path, INTERFACE, method);
if (!msg) {
fprintf(stderr, "Can't allocate new method call\n");
dbus_connection_unref(conn);
exit(1);
}
if (use_default)
dbus_message_append_args(msg, DBUS_TYPE_STRING, &agent_path,
DBUS_TYPE_INVALID);
else
dbus_message_append_args(msg, DBUS_TYPE_STRING, &agent_path,
DBUS_TYPE_STRING, &address, DBUS_TYPE_INVALID);
dbus_error_init(&err);
reply = dbus_connection_send_with_reply_and_block(conn, msg, -1, &err);
dbus_message_unref(msg);
if (!reply) {
fprintf(stderr, "Can't unregister passkey agent\n");
if (dbus_error_is_set(&err)) {
fprintf(stderr, "%s\n", err.message);
dbus_error_free(&err);
}
return -1;
}
dbus_message_unref(reply);
dbus_connection_flush(conn);
dbus_connection_unregister_object_path(conn, agent_path);
return 0;
}
static void usage(void)
{
printf("Bluetooth passkey agent ver %s\n\n", VERSION);
printf("Usage:\n"
"\tpasskey-agent [--default] [--path agent-path] <passkey> [address]\n"
"\n");
}
static struct option main_options[] = {
{ "default", 0, 0, 'd' },
{ "path", 1, 0, 'p' },
{ "help", 0, 0, 'h' },
{ 0, 0, 0, 0 }
};
int main(int argc, char *argv[])
{
struct sigaction sa;
DBusConnection *conn;
char match_string[128], default_path[128], *agent_path = NULL;
int opt, use_default = 0;
snprintf(default_path, sizeof(default_path),
"/org/bluez/passkey_agent_%d", getpid());
while ((opt = getopt_long(argc, argv, "+dp:h", main_options, NULL)) != EOF) {
switch(opt) {
case 'd':
use_default = 1;
break;
case 'p':
if (optarg[0] != '/') {
fprintf(stderr, "Invalid path\n");
exit(1);
}
agent_path = strdup(optarg);
break;
case 'h':
usage();
exit(0);
default:
exit(1);
}
}
argc -= optind;
argv += optind;
optind = 0;
if (argc < 1) {
usage();
exit(1);
}
passkey = strdup(argv[0]);
address = (argc > 1) ? strdup(argv[1]) : NULL;
if (!use_default && !address) {
usage();
exit(1);
}
if (!agent_path)
agent_path = strdup(default_path);
conn = dbus_bus_get(DBUS_BUS_SYSTEM, NULL);
if (!conn) {
fprintf(stderr, "Can't get on system bus");
exit(1);
}
if (register_agent(conn, agent_path, address, use_default) < 0) {
dbus_connection_unref(conn);
exit(1);
}
if (!dbus_connection_add_filter(conn, agent_filter, NULL, NULL))
fprintf(stderr, "Can't add signal filter");
snprintf(match_string, sizeof(match_string),
"interface=%s,member=NameOwnerChanged,arg0=%s",
DBUS_INTERFACE_DBUS, "org.bluez");
dbus_bus_add_match(conn, match_string, NULL);
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_NOCLDSTOP;
sa.sa_handler = sig_term;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
while (!__io_canceled && !__io_terminated) {
if (dbus_connection_read_write_dispatch(conn, 500) != TRUE)
break;
}
if (!__io_terminated)
unregister_agent(conn, agent_path, address, use_default);
if (passkey)
free(passkey);
dbus_connection_unref(conn);
return 0;
}
<file_sep>import sys
import time
import threading
import xmlrpclib
import SimpleXMLRPCServer
from WebServiceClientService_client import *
ENDPOINT = "http://0.0.0.0:2000/ncsc/hgwnodedemo"
def initClient():
logfile = file('zsiclient.log', 'w+')
loc = WebServiceClientServiceLocator()
kw = { 'tracefile' : logfile }
port = loc.getWebServiceClientPort(**kw)
return port
import wserver
def initServer():
t1 = threading.Thread(target=wserver.initServer)
t1.setDaemon(0)
t1.start()
def log(msg):
print("%s - %s" % (time.ctime(), msg))
global msg_id
msg_id = 0
def temp_sendMessage(temp, timestamp, priority=30):
global msg_id, ncsc
msg_id += 1
msg = '<?xml version="1.0" encoding="UTF-8"?>' + \
'<ncmessage priority="%s" msgid="temperature_%s" source="temperature#1" ' + \
'timestamp="%s" type="node_data" version="1.0">' + \
'<node id="temperature#1" type="temperature_sensor">' + \
'<value key="temperature">%s</value>' + \
'<value key="location">kitchen</value>' + \
'<value key="text">testext</value>' + \
'<value key="coordinates">13,17,69</value>' + \
'</node>' + \
'</ncmessage>'
msg = msg % (priority, msg_id, timestamp, temp)
log("sending message: " + msg)
sm = sendMessage()
sm._arg0 = priority
sm._arg1 = msg
sm._arg2 = ENDPOINT
result = ncsc.sendMessage(sm)
#log("sendMessage result: " + str(dir(result)))
return result
def receiveData(subscriptionUUID, msg):
print 'RDAF: %s - %s' % (subscriptionUUID, msg)
temp_sendMessage(msg['temperature'], msg['timestamp'])
return ['OK']
def async_receiving_endpoint():
server = SimpleXMLRPCServer.SimpleXMLRPCServer( ('localhost',10001) )
server.register_function(receiveData)
t2 = threading.Thread( target=server.serve_forever )
t2.start()
def async_interface(nodeName):
sp = xmlrpclib.ServerProxy('http://localhost:8081/')
myAddr = 'xmlrpc://localhost:10001'
ret, uuid1 = sp.subscribe(nodeName, myAddr)
print "asyncInterface::%s %s - isValidSubscription: %s" % (ret, uuid1, sp.isValidSubscription(uuid1, myAddr))
return sp, uuid1
global ncsc
ncsc = None
def main():
global ncsc
initServer()
ncsc = initClient()
ret_isConnected = False
while ret_isConnected is False:
log("calling isConnected()")
iscon = isConnected()
ret = ncsc.isConnected(iscon)
ret_isConnected = ret._return
log("connected to NCSC")
async_receiving_endpoint()
sp, uuid = async_interface('temperature')
log("async interface up")
# NOTA: crasha il demone
# a cosa serve se non c'e' connect() ?
#time.sleep(5)
#log("disconnecting...")
#disc = disconnect()
#ret = ncsc.disconnect(disc)
#log("disconnected: " + str(ret))
#time.sleep(5)
#log("exiting")
#sys.exit()
main()
<file_sep>import xmlrpclib
import SimpleXMLRPCServer
import time
import threading
def receiveData(subscriptionUUID, msg):
print 'asyncInterface::receiveData(): %s - %s' % (subscriptionUUID, msg)
return ['OK']
def async_receiving_endpoint():
server = SimpleXMLRPCServer.SimpleXMLRPCServer( ('localhost',10001) )
server.register_function(receiveData)
server.serve_forever()
def async_interface(nodeName):
sp = xmlrpclib.ServerProxy('http://localhost:8081/')
myAddr = 'xmlrpc://localhost:10001'
ret, uuid1 = sp.subscribe(nodeName, myAddr)
print "asyncInterface::%s %s - isValidSubscription: %s" % (ret, uuid1, sp.isValidSubscription(uuid1, myAddr))
return sp, uuid1
def sync_interface(nodeName):
sp = xmlrpclib.ServerProxy('http://localhost:8081/')
data = sp.getLastDataFrom(nodeName)
print 'syncInterface::sync_interface(): data from %s -> %s' % (nodeName, data)
print 'syncInterface::sync_interface(): sleeping for 10s'
time.sleep(10)
data = sp.getLastDataFrom(nodeName)
print 'syncInterface::sync_interface(): data from %s -> %s' % (nodeName, data)
def main():
sp1 = xmlrpclib.ServerProxy('http://localhost:8081/')
ret = sp1.list_nodes()
print 'main(): list_nodes(): ' + str(ret[1])
# prende il primo per il test
for node in ret[1]:
nodeName = node
break
t = threading.Thread(target=async_receiving_endpoint)
t.setDaemon(1)
t.start()
sp, uuid = async_interface(nodeName)
sync_interface(nodeName)
sp.unsubscribe(nodeName, uuid)
main()
<file_sep>import xmlrpclib
import SimpleXMLRPCServer
import time
import sys
RINGBELL_NODENAME = 'ringbell'
global sp
sp = None
# callback XML-RPC chiamata da hgw2 quando sono disponibili messaggi
#
def receiveData(subscriptionUUID, msg):
global sp
print 'receiveData(): %s - %s' % (subscriptionUUID, msg)
if msg['ringbell_status'] == 'pressed':
sp.command(RINGBELL_NODENAME, 'open_port')
# se non ci sono errori deve ritornare:
return ['OK']
def main():
global sp
SERVER_ADDRESS = 'http://localhost:8081/'
MY_ADDRESS = ('localhost',10001)
publisherName = RINGBELL_NODENAME
server = SimpleXMLRPCServer.SimpleXMLRPCServer( MY_ADDRESS )
server.register_function(receiveData)
sp = xmlrpclib.ServerProxy(SERVER_ADDRESS)
myAddr = 'http://localhost:10001'
print 'checking publisher status'
ret = sp.command(publisherName, 'status')
print 'status: ' + str(ret)
if ret[1] == 'NODE_NOT_FOUND':
print "[%s] nodo non trovato!" % publisherName
sys.exit(-1)
ret, uuid = sp.subscribe(publisherName, myAddr)
print "%s %s - isValidSubscription for %s: %s" % (ret, uuid, publisherName, sp.isValidSubscription(uuid, myAddr))
try:
print 'waiting for messages from [%s]' % publisherName
server.serve_forever()
except KeyboardInterrupt:
print 'unsubscribe: ' + str(sp.unsubscribe(publisherName, uuid))
main()
<file_sep>import sys
import signal
import time
from hgw_init import hgw_init
from delivery import RemoteInterface
from collect import newnodes as nodes
import log
def cleanexit(exitcode, *args):
log.info('exiting')
log.stop()
sys.exit(exitcode)
def main():
signal.signal(signal.SIGINT, cleanexit)
log.init()
collector, cabinet, broker, adc, sdc = hgw_init()
if not nodes.init(collector) or not nodes.start():
cleanexit(-1)
ri = RemoteInterface()
ri.adc = adc
ri.sdc = sdc
if not ri.initServers():
cleanexit(-1)
# TODO: cleanup here
while True:
time.sleep(3600)
if __name__ == '__main__':
main()
<file_sep>application = {
'dbpath': './hgw2db.sqlite3',
}
interfaces = {
'serial': {
'device': '/dev/ttyS0'
},
'tcp': {
'host': '0.0.0.0',
'port': 50007,
},
'barionet': {
'listen_ip': '0.0.0.0',
'port': 10000,
'barionet_ip': '10.0.0.3',
'cgi_request': '/rc.cgi?o=2,999',
## HACK:
'barionet_ringbell_ionum': '205',
},
}
nodes = {
#'temperature':
# {
# 'id': '1',
# 'position': 'B',
# 'coordinates': '3,7,99',
# },
#'tcpexample':
# {
# 'id': '2',
# 'position': 'A',
# 'coordinates': '3,7,9',
# },
'ringbell':
{
'id': '3',
'position': 'C',
'coordinates': '6,6,6',
},
#'tempexample':
# {
# 'id': '4',
# 'position': 'D',
# 'coordinates': '1,3,99',
# }
}
<file_sep>import GenericNode
from interfaces import serialInterface
import binascii
def hex2dec(s):
return int(s, 16)
class Temperature(GenericNode.GenericNode):
"""Translates the ziqbee-enable temperature sensor data into celsius degrees."""
interface = serialInterface.SerialInterface()
interfacename = 'serial'
def newValue(self, nodename, values):
values = values.strip('#')
values = values.strip('@')
fields = values.split(',')
if len(fields) == 4 and fields[2] == '1' and fields[3] != '':
x = float(fields[3])
a = 1.6e-05
b = -0.10328
c = 73.62593
temp = pow(a * x, 2) + (b * x) + c
return {'temperature': str(temp)}
| 82475f727472b51696eb2e802d0a76208409db9e | [
"Markdown",
"Java",
"Python",
"Text",
"C",
"Shell"
]
| 60 | Python | origliante/hgw | 17f40fc62f69e32be7119cac027fbc88af7e54e1 | c9f5c53bc360bae48b1ec417b0930bc02c7f81da |
refs/heads/master | <file_sep>var inputTemp = 0;//input中的内容
var first = 0;//第一操作数
var second = 0;//第二操作数
var operator;//储存运算符
var one;//一步运算操作
var pointer=1;//对一或二操作数操作的标志
var afterCaculation=false;//是否运算的标志
function clearAll()//清空所有
{
inputTemp.value = 0;
first = 0;
second = 0;
pointer = 1;
operator = false;
afterCaculation = false;
}
function clearSecond()//清空上一串数
{
if(inputTemp.value == "Error" )
{
clearAll();
}//Error时的CE操作与C操作相同
if(afterCaculation == true)
{
first =0;
second = second;
inputTemp.value = first;
}//如果已经进行过计算,清除结果后点等于仍使用第二操作数运算
else
{
if(pointer == 2)
{
pointer = 2;
inputTemp.value = 0;
second = inputTemp.value;
}//清除第二操作数
if(pointer == 1)
{
pointer = 1;
inputTemp.value = 0;
first = inputTemp.value;
}//清除第一操作数
}
}
function clearOne()//退格
{
if(inputTemp.value != "Error" && afterCaculation == false && !one)
{//Error不能退格且运算结果不能退格且一步运算结果不能退格
if(pointer == 1)
{
inputTemp.value = inputTemp.value.substring(0,inputTemp.value.length - 1);
first = inputTemp.value;
if(inputTemp.value.length == 0)
{
inputTemp.value = "0";
first = inputTemp.value;
}//退到最后变为0
if(first[0]=="-" && inputTemp.value.length == 1)
{
inputTemp.value = "0";
first = inputTemp.value;
}//“-”变为0
if(inputTemp.value == "-0")
{
inputTemp.value = "0";
first = inputTemp.value;
}//“-0”变为0
}
if(pointer == 2 && second != 0)
{//按运算符后不能退格
inputTemp.value = inputTemp.value.substring(0,inputTemp.value.length - 1);
second = inputTemp.value;
if(inputTemp.value.length == 0)
{
inputTemp.value = "0";
second = inputTemp.value;
}//退到最后变为0
if(second[0]=="-" && inputTemp.value.length == 1)
{
inputTemp.value = "0";
second = inputTemp.value;
}//“-”变为0
if(inputTemp.value == "-0")
{
inputTemp.value = "0";
first = inputTemp.value;
}//“-0”变为0
}
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
}
function sign()//正负号
{
inputTemp = document.getElementById("textbox");
if((inputTemp.value - 0) > 0)
{//正数变负
inputTemp.value = "-" + inputTemp.value;
if(pointer == 1)
{
first = inputTemp.value;
}
if(pointer == 2)
{
second = inputTemp.value;
}
}
else if((inputTemp.value - 0) < 0)
{//负数变正
inputTemp.value = inputTemp.value.substring(1,inputTemp.value.length);
if(pointer == 1)
{
first = inputTemp.value;
}
if(pointer == 2)
{
second = inputTemp.value;
}
}
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
function numIn(obj)//输入一串数字
{
if(inputTemp.value != "Error")
{//不出现Error时才允许操作
if(afterCaculation == false && operator && first &&(!second))
{//转而对第二操作数操作的判定
pointer = 2;
document.getElementById("textbox").value = 0;
}
if(afterCaculation == true && pointer == 1)
{//转而对第一操作数操作的判定
document.getElementById("textbox").value = 0;
afterCaculation = false;
}
inputTemp = document.getElementById("textbox");
if(inputTemp.value == "0" && obj.innerHTML == ".")
{//显示内容为0且点击“.”时显示“0.”
inputTemp.value = "0" + obj.innerHTML;
}
else if(inputTemp.value == "0")//显示为0时直接改变显示值
inputTemp.value = obj.innerHTML;
else
{
if(inputTemp.value.indexOf(".") > -1 && obj.innerHTML == ".")
{//只准输入一次小数点
inputTemp.value = inputTemp.value;
}
else//输入一串数字
inputTemp.value = inputTemp.value + obj.innerHTML;
}
//对变量赋值
if(pointer == 1)
{
first = inputTemp.value;
}
else if(pointer == 2)
{
second = inputTemp.value;
}
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
}
function operatorIn(obj)//运算符
{
if(inputTemp.value != "Error")
{//不出现Error时才允许操作
if(pointer == 1)
{//储存运算符并转而对第二操作数操作
pointer = 2;
second = 0;
afterCaculation = false;
operator = obj.innerHTML;
}
if(afterCaculation == false && second!= 0 && pointer == 2)
{//不点等于的连续运算
orderIn();
second = false;
afterCaculation = false;
operator = obj.innerHTML;
}
else
operator = obj.innerHTML;//以最后一个运算符为准
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
}
function others(obj)//直接运算的……
{
if(inputTemp.value != "Error")
{//不出现Error时才允许操作
one = obj.innerHTML;
if(one == "√")//平方根
{
if(first < 0)
{//不能为负
inputTemp = document.getElementById("textbox");
inputTemp.value = "Error";
pointer = 1;
}
else
{//分别对一二操作数运算
if(pointer == 1)
{
first = Math.sqrt(first);
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
afterCaculation = true;//相当于运算完毕了!
}
if(pointer == 2)
{
second = Math.sqrt(second);
inputTemp = document.getElementById("textbox");
inputTemp.value = second;
afterCaculation = false;//不能相当于运算完毕
}
}
}
if(one == "x²")//平方
{//分别对一二操作数运算
if(pointer == 1)
{
first = (first - 0) * (first - 0);
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
afterCaculation = true;//相当于运算完毕了!
}
else if(pointer == 2)
{
second = (second - 0) * (second - 0);
inputTemp = document.getElementById("textbox");
inputTemp.value = second;
afterCaculation = false;//不能相当于运算完毕
}
}
if(one == "1/x")//倒数
{
if(first == 0)
{//不能为0
inputTemp = document.getElementById("textbox");
inputTemp.value = "Error";
pointer = 1;
}
else
{//分别对一二操作数运算
if(pointer == 1)
{
first = 1/(first - 0);
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
afterCaculation = true;//相当于运算完毕了!
}
else if(pointer == 2)
{
second = 1/(second - 0);
inputTemp = document.getElementById("textbox");
inputTemp.value = second;
afterCaculation = false;//不能相当于运算完毕
}
}
}
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
}
function orderIn(obj)//运算啦运算啦
{
if(inputTemp.value != "Error")
{//不出现Error时才允许操作
if(operator == "+")//加
{
if(!second)//不点第二操作数进行的连续运算
{
second = first;
}
var r1,r2,m;
try{r1=first.toString().split(".")[1].length}catch(e){r1=0}
try{r2=second.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
first = (first*m+second*m)/m;
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
}
if(operator == "-")//减
{
if(!second)
{
second = first;
}
var r1,r2,m,n;
try{r1=first.toString().split(".")[1].length}catch(e){r1=0}
try{r2=second.toString().split(".")[1].length}catch(e){r2=0}
m=Math.pow(10,Math.max(r1,r2));
n=(r1>=r2)?r1:r2;
first =((first*m-second*m)/m).toFixed(n);
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
}
if(operator == "×")//乘
{
if(!second)
{
second = first;
}
var m=0,s1=first.toString(),s2=second.toString();
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
first= Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
}
if(operator == "÷")//除
{
if(!second)
{
second = first;
}
if(second == 0)
{//除数不能为0
inputTemp = document.getElementById("textbox");
inputTemp.value = "Error";
pointer = 1;
}
else
{
var t1=0,t2=0,r1,r2;
try{t1=first.toString().split(".")[1].length}catch(e){}
try{t2=second.toString().split(".")[1].length}catch(e){}
with(Math)
{
r1=Number(first.toString().replace(".",""));
r2=Number(second.toString().replace(".",""));
first =(r1/r2)*pow(10,t2-t1);
}
inputTemp = document.getElementById("textbox");
inputTemp.value = first;
pointer = 1;
}
}
if(!operator)//没点运算符字符串变为数
{
inputTemp.value = (inputTemp.value - 0);
}
afterCaculation = true;
if(inputTemp.value=="NaN"||inputTemp.value=="Infinity"||inputTemp.value=="null"||inputTemp.value=="undefined")
{
inputTemp.value="Error";
}
}
}
| 358e22c1fa407fc5926528274dc21f7f5718e742 | [
"JavaScript"
]
| 1 | JavaScript | lizlizlizlizliz/ITstudio | ebed734f7284f3413b01df11e05fe189e4e7686b | 0166f5ee73f147e83ae694042701922a2d1ade41 |
refs/heads/master | <repo_name>fR33Q/kolokwiumPUM<file_sep>/app/src/main/java/com/example/damian/myapplication/LekiAdapter.java
package com.example.damian.myapplication;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by Damian on 15.01.2018.
*/
public class LekiAdapter extends RecyclerView.Adapter<LekiAdapter.ViewHolder> {
private ArrayList<Leki> listaLekow = new ArrayList<>();
LekiAdapter(ArrayList<Leki> listaLekow)
{
this.listaLekow = listaLekow;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_item, null);
return new ViewHolder(itemLayoutView);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setDawka_leku(listaLekow.get(position).getDawka());
holder.setNazwa_leku(listaLekow.get(position).getNazwa());
}
@Override
public int getItemCount() {
return listaLekow.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
@BindView(R.id.lek_nazwa)
TextView nazwa_leku;
@BindView(R.id.dawka_lek)
TextView dawka_leku;
@BindView(R.id.button_wybierz)
Button wybierz;
@OnClick(R.id.button_wybierz)
void onNameClick() {
if (wybierz.getText() == "WYBRANO") {
wybierz.setText("WYBIERZ");
} else
{
wybierz.setText("WYBRANO");
}
}
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
private void setNazwa_leku(String nazwa) {nazwa_leku.setText(nazwa);}
private void setDawka_leku(String dawka) {dawka_leku.setText(dawka);}
}
}
<file_sep>/app/src/main/java/com/example/damian/myapplication/Main2Activity.java
package com.example.damian.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Main2Activity extends AppCompatActivity {
@BindView(R.id.recyclerView)
RecyclerView recView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ButterKnife.bind(this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recView.setLayoutManager(layoutManager);
ArrayList<Leki> listaLekow = new ArrayList<>();
listaLekow.add(new Leki("Aspiryna","100mg"));
listaLekow.add(new Leki("Ibuprom","150mg"));
listaLekow.add(new Leki("Apap","450mg"));
listaLekow.add(new Leki("Mucosolvan","300mg"));
listaLekow.add(new Leki("Aspot","200mg"));
LekiAdapter lekiAdapter = new LekiAdapter(listaLekow);
recView.setAdapter(lekiAdapter);
}
}
| ce55d67cee2afdf72ad945b586bb0bfdff148c07 | [
"Java"
]
| 2 | Java | fR33Q/kolokwiumPUM | b945214b830654da1ccdca0e0d93d6246d63daff | 7f5db199eb3b6697d514523eeff8ae9c480a906e |
refs/heads/master | <file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 28 12:56:49 2017
@author: jojo
"""
import string
import porter2_jojo
import re
#processing email.
#start by counting characters.
SU = string.ascii_uppercase
SL = string.ascii_lowercase
No = string.digits
def get_char_counts(string):
"""
counts the type of characters in each string,
perhaps this could encode some useful features.
perhaps not!
"""
char_count = [0, 0, 0, 0]
for char in string:
if char in SU:
char_count[0] = char_count[0]+1
elif char in SL:
char_count[1] = char_count[1] +1
elif char in No:
char_count[2] = char_count[2]+1
else:
#assumes all other characters are special :-)
char_count[3] = char_count[3] +1
return char_count
#print (get_char_counts('string'))
def get_word_counts(line, minimalStemming=False, stopWordsRemoved=True, ):
"""
constructs bag of words as dictionary
"""
word_count = {}
line = re.sub('[^a-zA-Z]+', ' ', line)
words = line.split()
for word in words:
word = porter2_jojo.stem(word, minimalStemming, stopWordsRemoved)
if word:
try:
word_count[word] = word_count[word] + 1
except:
word_count[word] =1
return word_count
#print (get_char_counts('You are receiving this letter because you have expressed an interest in '))
#print(get_word_counts('You are receiving this letter because you have expressed an interest in '))
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 10:41:03 2018
@author: jojo
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import numpy.linalg as la
import matplotlib.cm as cm
def make_mask(x,y, labels):
plot_point=[]
for i in range(len(x)):
if (np.isnan(x[i]) or np.isnan(y[i])):
continue
else:
plot_point.append(labels[i])
return plot_point
def abline(slope, intercept):
"""Plot a line from slope and intercept"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = intercept + slope * x_vals
plt.plot(x_vals, y_vals, '--')
def pearson(x, y):
x_bar = np.mean(x)
y_bar = np.mean(y)
top = np.dot( (x-x_bar), (y-y_bar) )
bottom = np.sqrt( sum((x - x_bar)**2) * sum((y - y_bar)**2) )
return top/bottom
def euclid_dist(x, y):
tot = 0
for i in range(len(x)):
diff = (x[i] - y[i])**2
tot +=diff
return np.sqrt(tot)
def man_dist(x,y):
return sum(x-y)
def cos_sim(x,y):
return np.dot(x,y) / (np.sqrt(np.sum(x**2)) * np.sqrt(np.sum(y**2)))
def euclid_sim(x,y):
dist = euclid_dist(x,y)
return 1/(1+dist)
def calc_centroid(cluster):
"""
calculates centroid based on data in cluster
cluster is list of feature vectors
"""
return np.mean(cluster, axis=0)
def calc_dist_all(p_dict, dist_metric):
"""
p_dict is list of all points key = label, value is fv
calcualtes all the distances between all the feature vectors
returns these distances as a dict of tuples of fvs as key, and dist as val
"""
distances={}
for id1,fv1 in p_dict.items():
for id2,fv2 in p_dict.items():
if id1==id2:
continue
d = dist_metric(fv1, fv2)
# print(euclid_dist(fv1, fv2))
# print(d)
distances[(id1,id2)] = d
return distances
def find_closest_pair(distances, points1, points2):
"""
takes in dict of sample ids pairs as keys, and distances as values
points1 list of keys in each group
returns closest distance between points in groups
"""
d = np.inf
for p1 in points1:
for p2 in points2:
if p1 == p2:
continue
if distances[(p1, p2)]<d:
d = distances[(p1, p2)]
# print(d, p1, p2)
return d
def find_furthest_pair(distances, points1, points2):
"""
takes in dict of sample ids pairs as keys, and distances as values
"""
d=0
for p1 in points1:
for p2 in points2:
if p1 == p2:
continue
if distances[(p1, p2)]>d:
d = distances[(p1,p2)]
return d
def find_next_merge(distances, centroid_dict, c_dict, p_dict, linkage):
"""
takes in dict of point distances, dict of point positions, and linkage
"""
d_tup=(np.inf, 0,0)
for cid1 in centroid_dict.keys():
for cid2 in centroid_dict.keys():
if cid1==cid2:
continue
points1 = c_dict[cid1]
points2 = c_dict[cid2]
if linkage=='min':
d = find_closest_pair(distances, points1, points2)
else:
d = find_furthest_pair(distances, points1, points2)
if d<d_tup[0]:
d_tup = d, cid1, cid2
return d_tup
def link_WPGMC(c1, c2):
"""
takes in two clusters, calcuates new merged cluster centroid
based on mean of two previous centroids
returns coords of new centroid
"""
c1_centroid = calc_centroid(c1)
c2_centroid = calc_centroid(c2)
return np.mean([c1_centroid, c2_centroid], axis=0)
def link_UPGMC(c1, c2):
"""
takes in two clusters, calculates new merged cluster centroid
based on members of both clusters
"""
c1.append(c2)
return calc_centroid(c1)
def plot_grouping(centroid_dict, p_dict,ax_lims, d=0):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.axis=ax_lims
plt.grid()
colors = cm.rainbow(np.linspace(0, 1, len(centroid_dict.keys())))
for cent, lab in zip(p_dict.values(), p_dict.keys()):
plt.plot(cent[0], cent[1], 'k.')
ax.annotate(lab, xy = cent)
for cent, c in zip(centroid_dict.values(), colors):
plt.scatter(cent[0], cent[1], color=c, alpha=0.3, s=((d+1)*5)**4)
plt.show()
def hac(X, labels, dist_metric, min_or_max, centroid_calc):
p_dict = {}
c_dict = {}
centroid_dict={}
for i in range(len(X)):
centroid_dict[i] = X[i] # sets each point as centroid
p_dict[labels[i]] = X[i] #sets name for each data point
c_dict[i] = [labels[i]] #stores which points are associated with which centroid
distances=calc_dist_all(p_dict, dist_metric) #works out all the distances between points
merge_order=[]
next_cid = len(centroid_dict.keys())
plot_grouping(centroid_dict, p_dict, [-2.25, 2.25, -1,2])
while len(centroid_dict.keys())>1:
d, c1, c2 = find_next_merge(distances, centroid_dict, c_dict, p_dict, min_or_max)
pid_list1 = c_dict[c1]
pid_list2 = c_dict[c2]
clust1 = [p_dict[p_id] for p_id in pid_list1]
clust2 = [p_dict[p_id] for p_id in pid_list2]
new_centroid = centroid_calc(clust1, clust2)
centroid_dict[next_cid] = new_centroid
c_dict[next_cid] = pid_list1 + pid_list2
del centroid_dict[c1]
del centroid_dict[c2]
plot_grouping(centroid_dict, p_dict, [-2.25, 2.25, -1,2], d)
next_cid +=1
merge_order.append((d, pid_list1, pid_list2))
return merge_order, p_dict
def plot_dentrogram(merge_order, p_dict):
"""
somehow plots a dendrogram for the merge order given
"""
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlabel("distance")
plt.ylabel("data points")
y = [x for x in range(len(p_dict))]
x = np.zeros(len(y))
labels = p_dict.keys()
for point, lab in zip(y,labels):
plt.plot(0, point, 'k.')
ax.annotate(lab, xy=(0,point))
for d, pid_list1, pid_list2 in merge_order:
for point, lab in zip(y,labels):
plt.plot(d, point, 'k.')
X = np.array([[1.5,1.5], [2,1],[-2.01,0.5], [-1,0.5], [-1,-0.5], [-1.5,-0.5]])
#print(metrics.calc_dist_all(X, metrics.euclid_dist))
labels=['A', 'B', 'C', 'D', 'E', 'F']
mo, p_dict = hac(X, labels, euclid_dist, 'max', link_WPGMC)
plot_dentrogram(mo, p_dict)
#
#hac(X, labels, euclid_dist, 'max', link_WPGMC) | 2efe86e7117110a95e5aa1c87d2ef72e84ca756c | [
"Python"
]
| 2 | Python | JoHoughton/Data-Mining-Demo-Code-18-19 | 9ac5bd7143f454a39e5f56884c97b019c13bab2c | d8b6751ddb9ae6b66108921b67674731b3cf9ee8 |
refs/heads/master | <repo_name>league1991/WRayEngine<file_sep>/WRayEngine/WRayEngine/main.cpp
#include "Application.h"
#include "Mesh.h"
//#include <util_init.hpp>
int main(int argc, char* argv[]) {
//const char *filename = "E:\\Code\\WRayEngine\\WRayEngine\\WRayEngine\\cornell_box.obj";
//ObjLoader loader;
//loader.Load(filename);
//std::vector<float> buffer;
//int numVertex, sizeOfPerVertex;
//loader.GetVertexBuffer(0,ObjLoader::VERTEX_ATTRIBUTE_POSITION | ObjLoader::VERTEX_ATTRIBUTE_COLOR,
// buffer, numVertex, sizeOfPerVertex);
Application* app = Application::instance();
app->initialize();
while (!app->shouldExit())
{
app->update();
}
app->destroy();
return 0;
}
<file_sep>/WRayEngine/WRayEngine/Mesh.h
#pragma once
#include "tiny_obj_loader.h"
#include <vulkan/vulkan.h>
#include "Buffer.h"
class ObjLoader
{
public:
enum VertexAttributeType
{
VERTEX_ATTRIBUTE_POSITION = 0x1,
VERTEX_ATTRIBUTE_NORMAL = 0x2,
VERTEX_ATTRIBUTE_TEXCOORD = 0x4,
VERTEX_ATTRIBUTE_COLOR = 0x8,
};
void Load(const char* fileName);
bool GetVertexBuffer(int shapeIndex, unsigned type, std::vector<float>& buffer, int& numberVertices, int& sizeOfPerVertex);
tinyobj::attrib_t m_attrib;
std::vector<tinyobj::shape_t> m_shapes;
std::vector<tinyobj::material_t> m_materials;
std::string m_warn;
std::string m_err;
};
class Mesh
{
public:
Mesh();
~Mesh();
void load(const char* fileName, VkDevice device, VkPhysicalDeviceMemoryProperties& memory_properties);
void draw(VkCommandBuffer cmd);
std::vector<Buffer> m_vertexBuffers;
};
<file_sep>/WRayEngine/WRayEngine/Shader.cpp
#include <vulkan/vulkan.h>
#include "Application.h"
#include "Shader.h"
Shader::Shader()
{
}
Shader::~Shader()
{
}
void Shader::init(VkDevice device, Type type, const std::string & fileName, const std::string& entryName)
{
std::ifstream file(fileName);
if (!file)
{
return;
}
m_fileName = fileName;
m_entryName = entryName;
//std::string code;
//file >> code;
std::string code((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
//void init_shaders(struct sample_info &info, const char *vertShaderText, const char *fragShaderText) {
VkResult res;
bool retVal;
//init_glslang();
glslang::InitializeProcess();
VkShaderModuleCreateInfo moduleCreateInfo;
VkShaderStageFlagBits stage;
switch (type)
{
case Shader::Type::SHADER_VERTEX:
stage = VK_SHADER_STAGE_VERTEX_BIT;
break;
case Shader::Type::SHADER_FRAGMENT:
stage = VK_SHADER_STAGE_FRAGMENT_BIT;
break;
default:
break;
}
//if (vertShaderText) {
std::vector<unsigned int> vtx_spv;
shaderStage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
shaderStage.pNext = NULL;
shaderStage.pSpecializationInfo = NULL;
shaderStage.flags = 0;
shaderStage.stage = stage;
shaderStage.pName = m_entryName.data();
retVal = GLSLtoSPV(stage, code.data(), vtx_spv);
assert(retVal);
moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
moduleCreateInfo.pNext = NULL;
moduleCreateInfo.flags = 0;
moduleCreateInfo.codeSize = vtx_spv.size() * sizeof(unsigned int);
moduleCreateInfo.pCode = vtx_spv.data();
res = vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderStage.module);
assert(res == VK_SUCCESS);
//}
//if (fragShaderText) {
// std::vector<unsigned int> frag_spv;
// info.shaderStages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
// info.shaderStages[1].pNext = NULL;
// info.shaderStages[1].pSpecializationInfo = NULL;
// info.shaderStages[1].flags = 0;
// info.shaderStages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
// info.shaderStages[1].pName = "main";
// retVal = GLSLtoSPV(VK_SHADER_STAGE_FRAGMENT_BIT, fragShaderText, frag_spv);
// assert(retVal);
// moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
// moduleCreateInfo.pNext = NULL;
// moduleCreateInfo.flags = 0;
// moduleCreateInfo.codeSize = frag_spv.size() * sizeof(unsigned int);
// moduleCreateInfo.pCode = frag_spv.data();
// res = vkCreateShaderModule(info.device, &moduleCreateInfo, NULL, &info.shaderStages[1].module);
// assert(res == VK_SUCCESS);
//}
glslang::FinalizeProcess();
//}
}
<file_sep>/WRayEngine/WRayEngine/Shader.h
#pragma once
#include <string>
#include <fstream>
class Shader
{
public:
enum class Type
{
SHADER_VERTEX,
SHADER_FRAGMENT
};
Shader();
~Shader();
void init(VkDevice device, Type type, const std::string & fileName, const std::string& entryName);
void destroy(VkDevice device)
{
vkDestroyShaderModule(device, shaderStage.module, NULL);
}
std::string m_fileName;
std::string m_entryName;
VkPipelineShaderStageCreateInfo shaderStage;
};
<file_sep>/WRayEngine/WRayEngine/Buffer.h
#pragma once
#include <vulkan/vulkan.h>
#include <vector>
class Buffer
{
public:
enum class Type
{
BUFFER_VERTEX,
BUFFER_INDEX,
};
Buffer() {}
~Buffer();
void init(VkDevice device, Type type, const void* data, int vertexCount, int dataStride, VkPhysicalDeviceMemoryProperties& memory_properties, bool useUV);
void destroy(VkDevice device)
{
vkDestroyBuffer(device, buf, NULL);
vkFreeMemory(device, mem, NULL);
}
//private:
int m_numVertex;
VkBuffer buf;
VkDeviceMemory mem;
VkDescriptorBufferInfo buffer_info;
VkVertexInputBindingDescription vi_binding;
VkVertexInputAttributeDescription vi_attribs[2];
};
<file_sep>/WRayEngine/WRayEngine/Application.h
#pragma once
#include <iostream>
#include <cstdlib>
#include <vulkan/vulkan.h>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <assert.h>
#include <WinUser.h>
#include <wingdi.h>
#include <windowsx.h>
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glslang/SPIRV/GlslangToSpv.h"
#include "Buffer.h"
#include "Shader.h"
#include "Mesh.h"
/* Number of descriptor sets needs to be the same at alloc, */
/* pipeline layout creation, and descriptor set layout creation */
#define NUM_DESCRIPTOR_SETS 1
/* Number of samples needs to be the same at image creation, */
/* renderpass creation and pipeline creation. */
#define NUM_SAMPLES VK_SAMPLE_COUNT_1_BIT
/* Number of viewports and number of scissors have to be the same */
/* at pipeline creation and in any call to set them dynamically */
/* They also have to be the same as each other */
#define NUM_VIEWPORTS 1
#define NUM_SCISSORS NUM_VIEWPORTS
#define APP_SHORT_NAME "WRayEngine"
#define U_ASSERT_ONLY
/* Amount of time, in nanoseconds, to wait for a command buffer to complete */
#define FENCE_TIMEOUT 100000000*100
#define VK_CHECK(x) \
do \
{ \
VkResult err = x; \
if (err) \
{ \
printf("Detected Vulkan error: {%d}", (err)); \
abort(); \
} \
} while (0)
/*
* structure to track all objects related to a texture.
*/
struct texture_object {
VkSampler sampler;
VkImage image;
VkImageLayout imageLayout;
bool needs_staging;
VkBuffer buffer;
VkDeviceSize buffer_size;
VkDeviceMemory image_memory;
VkDeviceMemory buffer_memory;
VkImageView view;
int32_t tex_width, tex_height;
};
/*
* Keep each of our swap chain buffers' image, command buffer and view in one
* spot
*/
typedef struct _swap_chain_buffers {
VkImage image;
VkImageView view;
} swap_chain_buffer;
/*
* A layer can expose extensions, keep track of those
* extensions here.
*/
typedef struct {
VkLayerProperties properties;
std::vector<VkExtensionProperties> instance_extensions;
std::vector<VkExtensionProperties> device_extensions;
} layer_properties;
struct PerFrame
{
VkFence queue_submit_fence = VK_NULL_HANDLE;
VkCommandPool primary_command_pool = VK_NULL_HANDLE;
VkCommandBuffer primary_command_buffer = VK_NULL_HANDLE;
VkSemaphore swapchain_acquire_semaphore = VK_NULL_HANDLE;
VkSemaphore swapchain_release_semaphore = VK_NULL_HANDLE;
};
/*
* Structure for tracking information used / created / modified
* by utility functions.
*/
struct sample_info {
#ifdef _WIN32
#define APP_NAME_STR_LEN 80
HINSTANCE connection; // hInstance - Windows Instance
TCHAR name[APP_NAME_STR_LEN]; // Name to put on the window/icon
HWND window; // hWnd - window handle
#elif defined(VK_USE_PLATFORM_METAL_EXT)
void* caMetalLayer;
#elif defined(__ANDROID__)
PFN_vkCreateAndroidSurfaceKHR fpCreateAndroidSurfaceKHR;
#elif defined(VK_USE_PLATFORM_WAYLAND_KHR)
wl_display* display;
wl_registry* registry;
wl_compositor* compositor;
wl_surface* window;
wl_shell* shell;
wl_shell_surface* shell_surface;
#else
xcb_connection_t* connection;
xcb_screen_t* screen;
xcb_window_t window;
xcb_intern_atom_reply_t* atom_wm_delete_window;
#endif // _WIN32
VkSurfaceKHR surface;
bool prepared;
bool use_staging_buffer;
bool save_images;
std::vector<const char*> instance_layer_names;
std::vector<const char*> instance_extension_names;
std::vector<layer_properties> instance_layer_properties;
std::vector<VkExtensionProperties> instance_extension_properties;
VkInstance inst;
std::vector<const char*> device_extension_names;
std::vector<VkExtensionProperties> device_extension_properties;
std::vector<VkPhysicalDevice> gpus;
VkDevice device;
VkQueue graphics_queue;
VkQueue present_queue;
uint32_t graphics_queue_family_index;
uint32_t present_queue_family_index;
VkPhysicalDeviceProperties gpu_props;
std::vector<VkQueueFamilyProperties> queue_props;
VkPhysicalDeviceMemoryProperties memory_properties;
VkFramebuffer* framebuffers;
int width, height;
VkFormat format;
uint32_t swapchainImageCount;
VkSwapchainKHR swap_chain;
std::vector<swap_chain_buffer> buffers;
VkSemaphore imageAcquiredSemaphore;
//VkCommandPool cmd_pool;
struct {
VkFormat format;
VkImage image;
VkDeviceMemory mem;
VkImageView view;
} depth;
std::vector<struct texture_object> textures;
struct {
VkBuffer buf;
VkDeviceMemory mem;
VkDescriptorBufferInfo buffer_info;
} uniform_data;
struct {
VkDescriptorImageInfo image_info;
} texture_data;
//struct {
// VkBuffer buf;
// VkDeviceMemory mem;
// VkDescriptorBufferInfo buffer_info;
//} vertex_buffer;
VkVertexInputBindingDescription vi_binding;
VkVertexInputAttributeDescription vi_attribs[2];
glm::mat4 Projection;
glm::mat4 View;
glm::mat4 Model;
glm::mat4 Clip;
glm::mat4 MVP;
//VkCommandBuffer cmd; // Buffer for initialization commands
VkPipelineLayout pipeline_layout;
std::vector<VkDescriptorSetLayout> desc_layout;
VkPipelineCache pipelineCache;
VkRenderPass render_pass;
VkPipeline pipeline;
VkPipelineShaderStageCreateInfo shaderStages[2];
VkDescriptorPool desc_pool;
std::vector<VkDescriptorSet> desc_set;
PFN_vkCreateDebugReportCallbackEXT dbgCreateDebugReportCallback;
PFN_vkDestroyDebugReportCallbackEXT dbgDestroyDebugReportCallback;
PFN_vkDebugReportMessageEXT dbgBreakCallback;
std::vector<VkDebugReportCallbackEXT> debug_report_callbacks;
std::vector<PerFrame> per_frame;
uint32_t current_buffer;
uint32_t queue_family_count;
VkViewport viewport;
VkRect2D scissor;
};
VkResult init_global_extension_properties(layer_properties& layer_props);
VkResult init_global_layer_properties(sample_info& info);
VkResult init_device_extension_properties(struct sample_info& info,
layer_properties& layer_props);
void init_instance_extension_names(struct sample_info& info);
VkResult init_instance(struct sample_info& info,
char const* const app_short_name);
void init_device_extension_names(struct sample_info& info);
VkResult init_device(struct sample_info& info);
VkResult init_enumerate_device(struct sample_info& info,
uint32_t gpu_count = 1);
VkBool32 demo_check_layers(const std::vector<layer_properties>& layer_props,
const std::vector<const char*>& layer_names);
void init_connection(struct sample_info& info);
void init_window(struct sample_info& info, WNDPROC WndProc);
void init_queue_family_index(struct sample_info& info);
void init_presentable_image(struct sample_info& info);
void execute_queue_cmdbuf(struct sample_info& info,
const VkCommandBuffer* cmd_bufs, VkFence& fence);
void execute_pre_present_barrier(struct sample_info& info);
void execute_present_image(struct sample_info& info);
void init_swapchain_extension(struct sample_info& info);
void init_command_pool(struct sample_info& info);
void init_command_buffer(struct sample_info& info);
void execute_begin_command_buffer(struct sample_info& info);
void execute_end_command_buffer(struct sample_info& info);
void execute_queue_command_buffer(struct sample_info& info);
void init_device_queue(struct sample_info& info);
void init_swap_chain(
struct sample_info& info,
VkImageUsageFlags usageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
void init_depth_buffer(struct sample_info& info);
void init_uniform_buffer(struct sample_info& info);
void init_descriptor_and_pipeline_layouts(struct sample_info& info, bool use_texture,
VkDescriptorSetLayoutCreateFlags descSetLayoutCreateFlags = 0);
void init_renderpass(struct sample_info& info, bool include_depth, bool clear = true,
VkImageLayout finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
VkImageLayout initialLayout = VK_IMAGE_LAYOUT_UNDEFINED);
void init_vertex_buffer(struct sample_info& info, const void* vertexData,
uint32_t dataSize, uint32_t dataStride,
bool use_texture);
void init_framebuffers(struct sample_info& info, bool include_depth);
void init_descriptor_pool(struct sample_info& info, bool use_texture);
void init_descriptor_set(struct sample_info& info, bool use_texture);
void init_shaders(struct sample_info& info, const VkShaderModuleCreateInfo* vertShaderCI,
const VkShaderModuleCreateInfo* fragShaderCI);
void init_shaders(struct sample_info &info, const char *vertShaderText, const char *fragShaderText);
void init_pipeline_cache(struct sample_info& info);
void init_pipeline(struct sample_info& info, VkBool32 include_depth,
VkBool32 include_vi = true);
void init_sampler(struct sample_info& info, VkSampler& sampler);
void init_image(struct sample_info& info, texture_object& texObj,
const char* textureName, VkImageUsageFlags extraUsages = 0,
VkFormatFeatureFlags extraFeatures = 0);
void init_texture(struct sample_info& info, const char* textureName = nullptr,
VkImageUsageFlags extraUsages = 0,
VkFormatFeatureFlags extraFeatures = 0);
void init_viewports(struct sample_info& info);
void init_scissors(struct sample_info& info);
void init_fence(struct sample_info& info, VkFence& fence);
void init_submit_info(struct sample_info& info, VkSubmitInfo& submit_info,
VkPipelineStageFlags& pipe_stage_flags);
void init_present_info(struct sample_info& info, VkPresentInfoKHR& present);
void init_clear_color_and_depth(struct sample_info& info,
VkClearValue* clear_values);
void init_render_pass_begin_info(struct sample_info& info,
VkRenderPassBeginInfo& rp_begin);
void init_window_size(struct sample_info& info, int32_t default_width,
int32_t default_height);
VkResult init_debug_report_callback(struct sample_info& info,
PFN_vkDebugReportCallbackEXT dbgFunc);
void init_per_frame(struct sample_info& info, PerFrame& per_frame);
void destroy_debug_report_callback(struct sample_info& info);
void destroy_pipeline(struct sample_info& info);
void destroy_pipeline_cache(struct sample_info& info);
void destroy_descriptor_pool(struct sample_info& info);
void destroy_vertex_buffer(struct sample_info& info);
void destroy_textures(struct sample_info& info);
void destroy_framebuffers(struct sample_info& info);
void destroy_shaders(struct sample_info& info);
void destroy_renderpass(struct sample_info& info);
void destroy_descriptor_and_pipeline_layouts(struct sample_info& info);
void destroy_uniform_buffer(struct sample_info& info);
void destroy_depth_buffer(struct sample_info& info);
void destroy_swap_chain(struct sample_info& info);
void destroy_command_buffer(struct sample_info& info);
void destroy_command_pool(struct sample_info& info);
void destroy_device(struct sample_info& info);
void destroy_instance(struct sample_info& info);
void destroy_window(struct sample_info& info);
bool memory_type_from_properties(struct VkPhysicalDeviceMemoryProperties& memory_properties, uint32_t typeBits, VkFlags requirements_mask, uint32_t* typeIndex);
bool GLSLtoSPV(const VkShaderStageFlagBits shader_type, const char *pshader, std::vector<unsigned int> &spirv);
class Application
{
public:
void initialize();
bool shouldExit() { return false; }
void update();
void destroy();
static Application* instance();
void onMouseMove(int x, int y);
void onMouseWheel(float delta)
{
m_cameraDist += delta * 0.1f;
}
void onMouseButton(UINT button);
void onKeyDown(UINT wParam, UINT lParam) {}
void onKeyUp(UINT wParam, UINT lParam) {}
private:
Application() {}
~Application();
void acquireSemaphore();
void render();
void present();
void updateCPUData();
void updateTexture();
static Application* s_instance;
glm::ivec2 m_lastMousePos{ 0,0 };
bool m_isLeftButton = false;
bool m_isMiddleButton = false;
bool m_isRightButton = false;
glm::vec2 m_cameraAngle;
float m_cameraDist = 10.f;
glm::mat4x4 m_modelMatrix;
Buffer vertexBuffer;
Mesh m_mesh;
Shader vertexShader, fragmentShader;
std::vector<VkSemaphore> recycled_semaphores;
VkFence drawFence = {};
sample_info info;
};
<file_sep>/WRayEngine/WRayEngine/Mesh.cpp
#define TINYOBJLOADER_IMPLEMENTATION
#include "Mesh.h"
Mesh::Mesh()
{
}
Mesh::~Mesh()
{
}
void Mesh::load(const char * fileName, VkDevice device, VkPhysicalDeviceMemoryProperties & memory_properties)
{
ObjLoader loader;
loader.Load(fileName);
int numBuffers = loader.m_shapes.size();
m_vertexBuffers.resize(numBuffers);
for (int i = 0; i < numBuffers; i++)
{
std::vector<float> buffer;
int numVertices, sizeOfVertex;
loader.GetVertexBuffer(i, ObjLoader::VERTEX_ATTRIBUTE_POSITION | ObjLoader::VERTEX_ATTRIBUTE_TEXCOORD, buffer, numVertices, sizeOfVertex);
m_vertexBuffers[i].init(device, Buffer::Type::BUFFER_VERTEX, &buffer[0], numVertices, sizeOfVertex, memory_properties, true);
}
}
void Mesh::draw(VkCommandBuffer cmd)
{
const VkDeviceSize offsets[1] = { 0 };
for (int i = 0; i < m_vertexBuffers.size(); i++)
{
vkCmdBindVertexBuffers(cmd, 0, 1, &m_vertexBuffers[i].buf, offsets);
vkCmdDraw(cmd, m_vertexBuffers[i].m_numVertex, 1, 0, 0);
}
}
void ObjLoader::Load(const char * fileName)
{
tinyobj::LoadObj(&m_attrib, &m_shapes, &m_materials, &m_warn, &m_err, fileName);
}
bool ObjLoader::GetVertexBuffer(int shapeIndex, unsigned type, std::vector<float>& buffer, int & numberVertices, int & sizeOfPerVertex)
{
if (shapeIndex >= m_shapes.size())
{
return false;
}
if (m_attrib.vertices.size() == 0)
{
return false;
}
int numberOfFloats = 0;
if ((type & VERTEX_ATTRIBUTE_POSITION) != 0)
{
numberOfFloats += 3;
}
if ((type & VERTEX_ATTRIBUTE_NORMAL) != 0)
{
numberOfFloats += 3;
}
if ((type & VERTEX_ATTRIBUTE_TEXCOORD) != 0)
{
numberOfFloats += 2;
}
if ((type & VERTEX_ATTRIBUTE_COLOR) != 0)
{
numberOfFloats += 3;
}
sizeOfPerVertex = numberOfFloats * sizeof(float);
auto& shape = m_shapes[shapeIndex];
numberVertices = shape.mesh.indices.size();
buffer.resize(numberVertices * numberOfFloats);
for (int i = 0; i < numberVertices; i++)
{
auto& idx = shape.mesh.indices[i];
float* p = &buffer[i * numberOfFloats];
if ((type & VERTEX_ATTRIBUTE_POSITION) != 0)
{
if (idx.vertex_index >= 0)
{
p[0] = m_attrib.vertices[idx.vertex_index * 3];
p[1] = m_attrib.vertices[idx.vertex_index * 3 + 1];
p[2] = m_attrib.vertices[idx.vertex_index * 3 + 2];
}
else
{
p[0] = p[1] = p[2] = 0;
}
p += 3;
}
if ((type & VERTEX_ATTRIBUTE_NORMAL) != 0)
{
if (idx.normal_index >= 0)
{
p[0] = m_attrib.normals[idx.normal_index * 3];
p[1] = m_attrib.normals[idx.normal_index * 3 + 1];
p[2] = m_attrib.normals[idx.normal_index * 3 + 2];
}
else
{
p[0] = p[1] = p[2] = 0;
}
p += 3;
}
if ((type & VERTEX_ATTRIBUTE_TEXCOORD) != 0)
{
if (idx.texcoord_index >= 0)
{
p[0] = m_attrib.texcoords[idx.texcoord_index * 2];
p[1] = m_attrib.texcoords[idx.texcoord_index * 2 + 1];
}
else
{
p[0] = p[1] = 0;
}
p += 2;
}
if ((type & VERTEX_ATTRIBUTE_COLOR) != 0)
{
if (idx.vertex_index >= 0)
{
p[0] = m_attrib.colors[idx.vertex_index * 3];
p[1] = m_attrib.colors[idx.vertex_index * 3 + 1];
p[2] = m_attrib.colors[idx.vertex_index * 3 + 2];
}
else
{
p[0] = p[1] = p[2] = 0;
}
}
}
return true;
}
<file_sep>/WRayEngine/WRayEngine/Buffer.cpp
#include <assert.h>
#include "Application.h"
#include "Buffer.h"
void Buffer::init(VkDevice device, Type type, const void* data, int numVertex, int dataStride, VkPhysicalDeviceMemoryProperties& memory_properties, bool useUV)
{
int dataSize = numVertex * dataStride;
m_numVertex = numVertex;
VkBufferUsageFlags usage;
switch (type)
{
case Buffer::Type::BUFFER_VERTEX:
usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
break;
case Buffer::Type::BUFFER_INDEX:
usage = VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
break;
default:
break;
}
VkResult U_ASSERT_ONLY res;
bool U_ASSERT_ONLY pass;
VkBufferCreateInfo buf_info = {};
buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
buf_info.pNext = NULL;
buf_info.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
buf_info.size = dataSize;
buf_info.queueFamilyIndexCount = 0;
buf_info.pQueueFamilyIndices = NULL;
buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
buf_info.flags = 0;
res = vkCreateBuffer(device, &buf_info, NULL, &buf);
assert(res == VK_SUCCESS);
VkMemoryRequirements mem_reqs;
vkGetBufferMemoryRequirements(device, buf, &mem_reqs);
VkMemoryAllocateInfo alloc_info = {};
alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
alloc_info.pNext = NULL;
alloc_info.memoryTypeIndex = 0;
alloc_info.allocationSize = mem_reqs.size;
pass = memory_type_from_properties(memory_properties, mem_reqs.memoryTypeBits,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&alloc_info.memoryTypeIndex);
assert(pass && "No mappable, coherent memory");
res = vkAllocateMemory(device, &alloc_info, NULL, &(mem));
assert(res == VK_SUCCESS);
buffer_info.range = mem_reqs.size;
buffer_info.offset = 0;
uint8_t* pData;
res = vkMapMemory(device, mem, 0, mem_reqs.size, 0, (void**)&pData);
assert(res == VK_SUCCESS);
memcpy(pData, data, dataSize);
vkUnmapMemory(device, mem);
res = vkBindBufferMemory(device, buf, mem, 0);
assert(res == VK_SUCCESS);
vi_binding.binding = 0;
vi_binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
vi_binding.stride = dataStride;
vi_attribs[0].binding = 0;
vi_attribs[0].location = 0;
vi_attribs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
vi_attribs[0].offset = 0;
vi_attribs[1].binding = 0;
vi_attribs[1].location = 1;
vi_attribs[1].format = useUV ? VK_FORMAT_R32G32_SFLOAT : VK_FORMAT_R32G32B32A32_SFLOAT;
vi_attribs[1].offset = 12;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//VkResult res;
//VkBufferCreateInfo buf_info = {};
//buf_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
//buf_info.pNext = NULL;
//buf_info.usage = usage;
//buf_info.size = size;
//buf_info.queueFamilyIndexCount = 0;
//buf_info.pQueueFamilyIndices = NULL;
//buf_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
//buf_info.flags = 0;
//res = vkCreateBuffer(device, &buf_info, NULL, &buf);
//assert(res == VK_SUCCESS);
//VkMemoryRequirements mem_reqs;
//vkGetBufferMemoryRequirements(device, buf, &mem_reqs);
//VkMemoryAllocateInfo alloc_info = {};
//alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
//alloc_info.pNext = NULL;
//alloc_info.memoryTypeIndex = 0;
//alloc_info.allocationSize = mem_reqs.size;
//bool pass = memory_type_from_properties(memory_properties, mem_reqs.memoryTypeBits,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// &alloc_info.memoryTypeIndex);
//assert(pass && "No mappable, coherent memory");
//res = vkAllocateMemory(device, &alloc_info, NULL, &(mem));
//assert(res == VK_SUCCESS);
//uint8_t *pData;
//res = vkMapMemory(device, mem, 0, mem_reqs.size, 0, (void **)&pData);
//assert(res == VK_SUCCESS);
//memcpy(pData, data, size);
//vkUnmapMemory(device, mem);
//res = vkBindBufferMemory(device, buf, mem, 0);
//assert(res == VK_SUCCESS);
}
Buffer::~Buffer()
{
}
<file_sep>/WRayEngine/WRayEngine/Application.cpp
#include "Application.h"
#include "Mesh.h"
Application* Application::s_instance = nullptr;
void Application::onMouseMove(int x, int y)
{
glm::ivec2 thisMousePos(x, y);
glm::vec2 deltaPos = thisMousePos - m_lastMousePos;
if (m_isLeftButton)
{
//m_modelMatrix = glm::rotate(m_modelMatrix, deltaPos.x * 0.01f, glm::vec3(1, 0, 0));
//m_modelMatrix = glm::rotate(m_modelMatrix, deltaPos.y * 0.01f, glm::vec3(0, 0, 1));
m_cameraAngle += deltaPos * 0.01f;
}
m_lastMousePos = thisMousePos;
}
void Application::onMouseButton(UINT button)
{
switch (button)
{
case WM_LBUTTONDOWN:
m_isLeftButton = true; break;
case WM_LBUTTONUP:
m_isLeftButton = false; break;
case WM_MBUTTONDOWN:
m_isMiddleButton = true; break;
case WM_MBUTTONUP:
m_isMiddleButton = false; break;
case WM_RBUTTONDOWN:
m_isRightButton = true; break;
case WM_RBUTTONUP:
m_isRightButton = false; break;
default:
break;
}
}
Application::~Application() { }
static const uint32_t __draw_cube_vert[287] = {
0x07230203, 0x00010000, 0x00080008, 0x00000020,
0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e,
0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0009000f, 0x00000000, 0x00000004, 0x6e69616d,
0x00000000, 0x00000009, 0x0000000b, 0x00000012,
0x0000001c, 0x00030003, 0x00000002, 0x00000190,
0x00090004, 0x415f4c47, 0x735f4252, 0x72617065,
0x5f657461, 0x64616873, 0x6f5f7265, 0x63656a62,
0x00007374, 0x00090004, 0x415f4c47, 0x735f4252,
0x69646168, 0x6c5f676e, 0x75676e61, 0x5f656761,
0x70303234, 0x006b6361, 0x00040005, 0x00000004,
0x6e69616d, 0x00000000, 0x00050005, 0x00000009,
0x4374756f, 0x726f6c6f, 0x00000000, 0x00040005,
0x0000000b, 0x6f436e69, 0x00726f6c, 0x00060005,
0x00000010, 0x505f6c67, 0x65567265, 0x78657472,
0x00000000, 0x00060006, 0x00000010, 0x00000000,
0x505f6c67, 0x7469736f, 0x006e6f69, 0x00070006,
0x00000010, 0x00000001, 0x505f6c67, 0x746e696f,
0x657a6953, 0x00000000, 0x00070006, 0x00000010,
0x00000002, 0x435f6c67, 0x4470696c, 0x61747369,
0x0065636e, 0x00030005, 0x00000012, 0x00000000,
0x00050005, 0x00000016, 0x66667562, 0x61567265,
0x0000736c, 0x00040006, 0x00000016, 0x00000000,
0x0070766d, 0x00060005, 0x00000018, 0x7542796d,
0x72656666, 0x736c6156, 0x00000000, 0x00030005,
0x0000001c, 0x00736f70, 0x00040047, 0x00000009,
0x0000001e, 0x00000000, 0x00040047, 0x0000000b,
0x0000001e, 0x00000001, 0x00050048, 0x00000010,
0x00000000, 0x0000000b, 0x00000000, 0x00050048,
0x00000010, 0x00000001, 0x0000000b, 0x00000001,
0x00050048, 0x00000010, 0x00000002, 0x0000000b,
0x00000003, 0x00030047, 0x00000010, 0x00000002,
0x00040048, 0x00000016, 0x00000000, 0x00000005,
0x00050048, 0x00000016, 0x00000000, 0x00000023,
0x00000000, 0x00050048, 0x00000016, 0x00000000,
0x00000007, 0x00000010, 0x00030047, 0x00000016,
0x00000002, 0x00040047, 0x00000018, 0x00000022,
0x00000000, 0x00040047, 0x00000018, 0x00000021,
0x00000000, 0x00040047, 0x0000001c, 0x0000001e,
0x00000000, 0x00020013, 0x00000002, 0x00030021,
0x00000003, 0x00000002, 0x00030016, 0x00000006,
0x00000020, 0x00040017, 0x00000007, 0x00000006,
0x00000004, 0x00040020, 0x00000008, 0x00000003,
0x00000007, 0x0004003b, 0x00000008, 0x00000009,
0x00000003, 0x00040020, 0x0000000a, 0x00000001,
0x00000007, 0x0004003b, 0x0000000a, 0x0000000b,
0x00000001, 0x00040015, 0x0000000d, 0x00000020,
0x00000000, 0x0004002b, 0x0000000d, 0x0000000e,
0x00000001, 0x0004001c, 0x0000000f, 0x00000006,
0x0000000e, 0x0005001e, 0x00000010, 0x00000007,
0x00000006, 0x0000000f, 0x00040020, 0x00000011,
0x00000003, 0x00000010, 0x0004003b, 0x00000011,
0x00000012, 0x00000003, 0x00040015, 0x00000013,
0x00000020, 0x00000001, 0x0004002b, 0x00000013,
0x00000014, 0x00000000, 0x00040018, 0x00000015,
0x00000007, 0x00000004, 0x0003001e, 0x00000016,
0x00000015, 0x00040020, 0x00000017, 0x00000002,
0x00000016, 0x0004003b, 0x00000017, 0x00000018,
0x00000002, 0x00040020, 0x00000019, 0x00000002,
0x00000015, 0x0004003b, 0x0000000a, 0x0000001c,
0x00000001, 0x00050036, 0x00000002, 0x00000004,
0x00000000, 0x00000003, 0x000200f8, 0x00000005,
0x0004003d, 0x00000007, 0x0000000c, 0x0000000b,
0x0003003e, 0x00000009, 0x0000000c, 0x00050041,
0x00000019, 0x0000001a, 0x00000018, 0x00000014,
0x0004003d, 0x00000015, 0x0000001b, 0x0000001a,
0x0004003d, 0x00000007, 0x0000001d, 0x0000001c,
0x00050091, 0x00000007, 0x0000001e, 0x0000001b,
0x0000001d, 0x00050041, 0x00000008, 0x0000001f,
0x00000012, 0x00000014, 0x0003003e, 0x0000001f,
0x0000001e, 0x000100fd, 0x00010038,
};
static const uint32_t __draw_cube_frag[112] = {
0x07230203, 0x00010000, 0x00080008, 0x0000000d,
0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e,
0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d,
0x00000000, 0x00000009, 0x0000000b, 0x00030010,
0x00000004, 0x00000007, 0x00030003, 0x00000002,
0x00000190, 0x00090004, 0x415f4c47, 0x735f4252,
0x72617065, 0x5f657461, 0x64616873, 0x6f5f7265,
0x63656a62, 0x00007374, 0x00090004, 0x415f4c47,
0x735f4252, 0x69646168, 0x6c5f676e, 0x75676e61,
0x5f656761, 0x70303234, 0x006b6361, 0x00040005,
0x00000004, 0x6e69616d, 0x00000000, 0x00050005,
0x00000009, 0x4374756f, 0x726f6c6f, 0x00000000,
0x00040005, 0x0000000b, 0x6f6c6f63, 0x00000072,
0x00040047, 0x00000009, 0x0000001e, 0x00000000,
0x00040047, 0x0000000b, 0x0000001e, 0x00000000,
0x00020013, 0x00000002, 0x00030021, 0x00000003,
0x00000002, 0x00030016, 0x00000006, 0x00000020,
0x00040017, 0x00000007, 0x00000006, 0x00000004,
0x00040020, 0x00000008, 0x00000003, 0x00000007,
0x0004003b, 0x00000008, 0x00000009, 0x00000003,
0x00040020, 0x0000000a, 0x00000001, 0x00000007,
0x0004003b, 0x0000000a, 0x0000000b, 0x00000001,
0x00050036, 0x00000002, 0x00000004, 0x00000000,
0x00000003, 0x000200f8, 0x00000005, 0x0004003d,
0x00000007, 0x0000000c, 0x0000000b, 0x0003003e,
0x00000009, 0x0000000c, 0x000100fd, 0x00010038,
};
static const uint32_t template_vert[296] = {
0x07230203, 0x00010000, 0x00080008, 0x00000023,
0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e,
0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0009000f, 0x00000000, 0x00000004, 0x6e69616d,
0x00000000, 0x00000009, 0x0000000b, 0x00000013,
0x0000001e, 0x00030003, 0x00000002, 0x00000190,
0x00090004, 0x415f4c47, 0x735f4252, 0x72617065,
0x5f657461, 0x64616873, 0x6f5f7265, 0x63656a62,
0x00007374, 0x00090004, 0x415f4c47, 0x735f4252,
0x69646168, 0x6c5f676e, 0x75676e61, 0x5f656761,
0x70303234, 0x006b6361, 0x00040005, 0x00000004,
0x6e69616d, 0x00000000, 0x00050005, 0x00000009,
0x63786574, 0x64726f6f, 0x00000000, 0x00050005,
0x0000000b, 0x65546e69, 0x6f6f4378, 0x00736472,
0x00060005, 0x00000011, 0x505f6c67, 0x65567265,
0x78657472, 0x00000000, 0x00060006, 0x00000011,
0x00000000, 0x505f6c67, 0x7469736f, 0x006e6f69,
0x00070006, 0x00000011, 0x00000001, 0x505f6c67,
0x746e696f, 0x657a6953, 0x00000000, 0x00070006,
0x00000011, 0x00000002, 0x435f6c67, 0x4470696c,
0x61747369, 0x0065636e, 0x00030005, 0x00000013,
0x00000000, 0x00030005, 0x00000017, 0x00667562,
0x00040006, 0x00000017, 0x00000000, 0x0070766d,
0x00040005, 0x00000019, 0x66756275, 0x00000000,
0x00030005, 0x0000001e, 0x00736f70, 0x00040047,
0x00000009, 0x0000001e, 0x00000000, 0x00040047,
0x0000000b, 0x0000001e, 0x00000001, 0x00050048,
0x00000011, 0x00000000, 0x0000000b, 0x00000000,
0x00050048, 0x00000011, 0x00000001, 0x0000000b,
0x00000001, 0x00050048, 0x00000011, 0x00000002,
0x0000000b, 0x00000003, 0x00030047, 0x00000011,
0x00000002, 0x00040048, 0x00000017, 0x00000000,
0x00000005, 0x00050048, 0x00000017, 0x00000000,
0x00000023, 0x00000000, 0x00050048, 0x00000017,
0x00000000, 0x00000007, 0x00000010, 0x00030047,
0x00000017, 0x00000002, 0x00040047, 0x00000019,
0x00000022, 0x00000000, 0x00040047, 0x00000019,
0x00000021, 0x00000000, 0x00040047, 0x0000001e,
0x0000001e, 0x00000000, 0x00020013, 0x00000002,
0x00030021, 0x00000003, 0x00000002, 0x00030016,
0x00000006, 0x00000020, 0x00040017, 0x00000007,
0x00000006, 0x00000002, 0x00040020, 0x00000008,
0x00000003, 0x00000007, 0x0004003b, 0x00000008,
0x00000009, 0x00000003, 0x00040020, 0x0000000a,
0x00000001, 0x00000007, 0x0004003b, 0x0000000a,
0x0000000b, 0x00000001, 0x00040017, 0x0000000d,
0x00000006, 0x00000004, 0x00040015, 0x0000000e,
0x00000020, 0x00000000, 0x0004002b, 0x0000000e,
0x0000000f, 0x00000001, 0x0004001c, 0x00000010,
0x00000006, 0x0000000f, 0x0005001e, 0x00000011,
0x0000000d, 0x00000006, 0x00000010, 0x00040020,
0x00000012, 0x00000003, 0x00000011, 0x0004003b,
0x00000012, 0x00000013, 0x00000003, 0x00040015,
0x00000014, 0x00000020, 0x00000001, 0x0004002b,
0x00000014, 0x00000015, 0x00000000, 0x00040018,
0x00000016, 0x0000000d, 0x00000004, 0x0003001e,
0x00000017, 0x00000016, 0x00040020, 0x00000018,
0x00000002, 0x00000017, 0x0004003b, 0x00000018,
0x00000019, 0x00000002, 0x00040020, 0x0000001a,
0x00000002, 0x00000016, 0x00040020, 0x0000001d,
0x00000001, 0x0000000d, 0x0004003b, 0x0000001d,
0x0000001e, 0x00000001, 0x00040020, 0x00000021,
0x00000003, 0x0000000d, 0x00050036, 0x00000002,
0x00000004, 0x00000000, 0x00000003, 0x000200f8,
0x00000005, 0x0004003d, 0x00000007, 0x0000000c,
0x0000000b, 0x0003003e, 0x00000009, 0x0000000c,
0x00050041, 0x0000001a, 0x0000001b, 0x00000019,
0x00000015, 0x0004003d, 0x00000016, 0x0000001c,
0x0000001b, 0x0004003d, 0x0000000d, 0x0000001f,
0x0000001e, 0x00050091, 0x0000000d, 0x00000020,
0x0000001c, 0x0000001f, 0x00050041, 0x00000021,
0x00000022, 0x00000013, 0x00000015, 0x0003003e,
0x00000022, 0x00000020, 0x000100fd, 0x00010038,
};
static const uint32_t template_frag[163] = {
0x07230203, 0x00010000, 0x00080008, 0x00000015,
0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e,
0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x0007000f, 0x00000004, 0x00000004, 0x6e69616d,
0x00000000, 0x00000009, 0x00000011, 0x00030010,
0x00000004, 0x00000007, 0x00030003, 0x00000002,
0x00000190, 0x00090004, 0x415f4c47, 0x735f4252,
0x72617065, 0x5f657461, 0x64616873, 0x6f5f7265,
0x63656a62, 0x00007374, 0x00090004, 0x415f4c47,
0x735f4252, 0x69646168, 0x6c5f676e, 0x75676e61,
0x5f656761, 0x70303234, 0x006b6361, 0x00040005,
0x00000004, 0x6e69616d, 0x00000000, 0x00050005,
0x00000009, 0x4374756f, 0x726f6c6f, 0x00000000,
0x00030005, 0x0000000d, 0x00786574, 0x00050005,
0x00000011, 0x63786574, 0x64726f6f, 0x00000000,
0x00040047, 0x00000009, 0x0000001e, 0x00000000,
0x00040047, 0x0000000d, 0x00000022, 0x00000000,
0x00040047, 0x0000000d, 0x00000021, 0x00000001,
0x00040047, 0x00000011, 0x0000001e, 0x00000000,
0x00020013, 0x00000002, 0x00030021, 0x00000003,
0x00000002, 0x00030016, 0x00000006, 0x00000020,
0x00040017, 0x00000007, 0x00000006, 0x00000004,
0x00040020, 0x00000008, 0x00000003, 0x00000007,
0x0004003b, 0x00000008, 0x00000009, 0x00000003,
0x00090019, 0x0000000a, 0x00000006, 0x00000001,
0x00000000, 0x00000000, 0x00000000, 0x00000001,
0x00000000, 0x0003001b, 0x0000000b, 0x0000000a,
0x00040020, 0x0000000c, 0x00000000, 0x0000000b,
0x0004003b, 0x0000000c, 0x0000000d, 0x00000000,
0x00040017, 0x0000000f, 0x00000006, 0x00000002,
0x00040020, 0x00000010, 0x00000001, 0x0000000f,
0x0004003b, 0x00000010, 0x00000011, 0x00000001,
0x0004002b, 0x00000006, 0x00000013, 0x00000000,
0x00050036, 0x00000002, 0x00000004, 0x00000000,
0x00000003, 0x000200f8, 0x00000005, 0x0004003d,
0x0000000b, 0x0000000e, 0x0000000d, 0x0004003d,
0x0000000f, 0x00000012, 0x00000011, 0x00070058,
0x00000007, 0x00000014, 0x0000000e, 0x00000012,
0x00000002, 0x00000013, 0x0003003e, 0x00000009,
0x00000014, 0x000100fd, 0x00010038,
};
struct Vertex {
float posX, posY, posZ, posW; // Position data
float r, g, b, a; // Color
};
struct VertexUV {
float posX, posY, posZ, posW; // Position data
float u, v; // texture u,v
};
#define XYZ1(_x_, _y_, _z_) (_x_), (_y_), (_z_), 1.f
#define UV(_u_, _v_) (_u_), (_v_)
static const Vertex g_vbData[] = {
{XYZ1(-1, -1, -1), XYZ1(0.f, 0.f, 0.f)}, {XYZ1(1, -1, -1), XYZ1(1.f, 0.f, 0.f)}, {XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)}, {XYZ1(1, -1, -1), XYZ1(1.f, 0.f, 0.f)}, {XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)}, {XYZ1(-1, 1, 1), XYZ1(0.f, 1.f, 1.f)}, {XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 1.f)}, {XYZ1(-1, 1, 1), XYZ1(0.f, 1.f, 1.f)}, {XYZ1(1, 1, 1), XYZ1(1.f, 1.f, 1.f)},
{XYZ1(1, 1, 1), XYZ1(1.f, 1.f, 1.f)}, {XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)}, {XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 1.f)}, {XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)}, {XYZ1(1, -1, -1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(-1, 1, 1), XYZ1(0.f, 1.f, 1.f)}, {XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)}, {XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)}, {XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)}, {XYZ1(-1, -1, -1), XYZ1(0.f, 0.f, 0.f)},
{XYZ1(1, 1, 1), XYZ1(1.f, 1.f, 1.f)}, {XYZ1(-1, 1, 1), XYZ1(0.f, 1.f, 1.f)}, {XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)}, {XYZ1(-1, 1, 1), XYZ1(0.f, 1.f, 1.f)}, {XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 1.f)}, {XYZ1(1, -1, -1), XYZ1(1.f, 0.f, 0.f)}, {XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)}, {XYZ1(1, -1, -1), XYZ1(1.f, 0.f, 0.f)}, {XYZ1(-1, -1, -1), XYZ1(0.f, 0.f, 0.f)},
};
static const Vertex g_vb_solid_face_colors_Data[] = {
// red face
{XYZ1(-1, -1, 1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(-1, 1, 1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(-1, 1, 1), XYZ1(1.f, 0.f, 0.f)},
{XYZ1(1, 1, 1), XYZ1(1.f, 0.f, 0.f)},
// green face
{XYZ1(-1, -1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(1, -1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(1, -1, -1), XYZ1(0.f, 1.f, 0.f)},
{XYZ1(1, 1, -1), XYZ1(0.f, 1.f, 0.f)},
// blue face
{XYZ1(-1, 1, 1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, 1, -1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 0.f, 1.f)},
{XYZ1(-1, -1, -1), XYZ1(0.f, 0.f, 1.f)},
// yellow face
{XYZ1(1, 1, 1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, -1, 1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, 1, -1), XYZ1(1.f, 1.f, 0.f)},
{XYZ1(1, -1, -1), XYZ1(1.f, 1.f, 0.f)},
// magenta face
{XYZ1(1, 1, 1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(-1, 1, 1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(1, 1, -1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(1, 1, -1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(-1, 1, 1), XYZ1(1.f, 0.f, 1.f)},
{XYZ1(-1, 1, -1), XYZ1(1.f, 0.f, 1.f)},
// cyan face
{XYZ1(1, -1, 1), XYZ1(0.f, 1.f, 1.f)},
{XYZ1(1, -1, -1), XYZ1(0.f, 1.f, 1.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 1.f, 1.f)},
{XYZ1(-1, -1, 1), XYZ1(0.f, 1.f, 1.f)},
{XYZ1(1, -1, -1), XYZ1(0.f, 1.f, 1.f)},
{XYZ1(-1, -1, -1), XYZ1(0.f, 1.f, 1.f)},
};
static const VertexUV g_vb_texture_Data[] = {
// left face
{XYZ1(-1, -1, -1), UV(1.f, 0.f)}, // lft-top-front
{XYZ1(-1, 1, 1), UV(0.f, 1.f)}, // lft-btm-back
{XYZ1(-1, -1, 1), UV(0.f, 0.f)}, // lft-top-back
{XYZ1(-1, 1, 1), UV(0.f, 1.f)}, // lft-btm-back
{XYZ1(-1, -1, -1), UV(1.f, 0.f)}, // lft-top-front
{XYZ1(-1, 1, -1), UV(1.f, 1.f)}, // lft-btm-front
// front face
{XYZ1(-1, -1, -1), UV(0.f, 0.f)}, // lft-top-front
{XYZ1(1, -1, -1), UV(1.f, 0.f)}, // rgt-top-front
{XYZ1(1, 1, -1), UV(1.f, 1.f)}, // rgt-btm-front
{XYZ1(-1, -1, -1), UV(0.f, 0.f)}, // lft-top-front
{XYZ1(1, 1, -1), UV(1.f, 1.f)}, // rgt-btm-front
{XYZ1(-1, 1, -1), UV(0.f, 1.f)}, // lft-btm-front
// top face
{XYZ1(-1, -1, -1), UV(0.f, 1.f)}, // lft-top-front
{XYZ1(1, -1, 1), UV(1.f, 0.f)}, // rgt-top-back
{XYZ1(1, -1, -1), UV(1.f, 1.f)}, // rgt-top-front
{XYZ1(-1, -1, -1), UV(0.f, 1.f)}, // lft-top-front
{XYZ1(-1, -1, 1), UV(0.f, 0.f)}, // lft-top-back
{XYZ1(1, -1, 1), UV(1.f, 0.f)}, // rgt-top-back
// bottom face
{XYZ1(-1, 1, -1), UV(0.f, 0.f)}, // lft-btm-front
{XYZ1(1, 1, 1), UV(1.f, 1.f)}, // rgt-btm-back
{XYZ1(-1, 1, 1), UV(0.f, 1.f)}, // lft-btm-back
{XYZ1(-1, 1, -1), UV(0.f, 0.f)}, // lft-btm-front
{XYZ1(1, 1, -1), UV(1.f, 0.f)}, // rgt-btm-front
{XYZ1(1, 1, 1), UV(1.f, 1.f)}, // rgt-btm-back
// right face
{XYZ1(1, 1, -1), UV(0.f, 1.f)}, // rgt-btm-front
{XYZ1(1, -1, 1), UV(1.f, 0.f)}, // rgt-top-back
{XYZ1(1, 1, 1), UV(1.f, 1.f)}, // rgt-btm-back
{XYZ1(1, -1, 1), UV(1.f, 0.f)}, // rgt-top-back
{XYZ1(1, 1, -1), UV(0.f, 1.f)}, // rgt-btm-front
{XYZ1(1, -1, -1), UV(0.f, 0.f)}, // rgt-top-front
// back face
{XYZ1(-1, 1, 1), UV(1.f, 1.f)}, // lft-btm-back
{XYZ1(1, 1, 1), UV(0.f, 1.f)}, // rgt-btm-back
{XYZ1(-1, -1, 1), UV(1.f, 0.f)}, // lft-top-back
{XYZ1(-1, -1, 1), UV(1.f, 0.f)}, // lft-top-back
{XYZ1(1, 1, 1), UV(0.f, 1.f)}, // rgt-btm-back
{XYZ1(1, -1, 1), UV(0.f, 0.f)}, // rgt-top-back
};
static const char *vertShaderText =
"#version 400\n"
"#extension GL_ARB_separate_shader_objects : enable\n"
"#extension GL_ARB_shading_language_420pack : enable\n"
"layout (std140, binding = 0) uniform buf {"
" mat4 mvp;"
"} ubuf;"
"layout (location = 0) in vec4 pos;"
"layout (location = 1) in vec2 inTexCoords;"
"layout (location = 0) out vec2 texcoord;"
"void main() {"
" texcoord = inTexCoords;"
" gl_Position = ubuf.mvp * pos;"
"}"
//
//"#version 400\n"
//"#extension GL_ARB_separate_shader_objects : enable\n"
//"#extension GL_ARB_shading_language_420pack : enable\n"
//"layout (std140, binding = 0) uniform bufferVals {\n"
//" mat4 mvp;\n"
//"} myBufferVals;\n"
//"layout (location = 0) in vec4 pos;\n"
//"layout (location = 1) in vec4 inColor;\n"
//"layout (location = 0) out vec4 outColor;\n"
//"void main() {\n"
//" outColor = inColor;\n"
//" gl_Position = myBufferVals.mvp * pos;\n"
//"}\n"
;
static const char *fragShaderText =
"#version 400\n"
"#extension GL_ARB_separate_shader_objects : enable\n"
"#extension GL_ARB_shading_language_420pack : enable\n"
"layout (binding = 1) uniform sampler2D tex;"
"layout (location = 0) in vec2 texcoord;"
"layout (location = 0) out vec4 outColor;"
"void main() {"
" outColor = textureLod(tex, texcoord, 0.0);"
"}"
//"#version 400\n"
//"#extension GL_ARB_separate_shader_objects : enable\n"
//"#extension GL_ARB_shading_language_420pack : enable\n"
//"layout (location = 0) in vec4 color;\n"
//"layout (location = 0) out vec4 outColor;\n"
//"void main() {\n"
//" outColor = color;\n"
//"}\n"
;
// MS-Windows event handling function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
struct sample_info* info = reinterpret_cast<struct sample_info*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
Application* app = Application::instance();
switch (uMsg) {
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_PAINT:
//run(info);
break;// return 0;
case WM_MOUSEMOVE:
{
const int x = GET_X_LPARAM(lParam);
const int y = GET_Y_LPARAM(lParam);
app->onMouseMove(x, y);
break;
}
case WM_MOUSEWHEEL:
{
app->onMouseWheel((SHORT)HIWORD(wParam) / (float)WHEEL_DELTA);
break;
}
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
app->onKeyDown(wParam, lParam);
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
app->onKeyUp(wParam, lParam);
break;
}
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_XBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
case WM_XBUTTONUP:
{
app->onMouseButton(uMsg);
break;
}
default:
break;
}
return (DefWindowProc(hWnd, uMsg, wParam, lParam));
}
void Application::initialize()
{
VkResult U_ASSERT_ONLY res;
char sample_title[] = "Draw Cube";
const bool depthPresent = true;
//process_command_line_args(info, argc, argv);
init_global_layer_properties(info);
init_instance_extension_names(info);
init_device_extension_names(info);
init_instance(info, sample_title);
init_enumerate_device(info);
init_window_size(info, 500, 500);
init_connection(info);
init_window(info, WndProc);
init_swapchain_extension(info);
init_device(info);
//init_command_pool(info);
//init_command_buffer(info);
//execute_begin_command_buffer(info);
init_device_queue(info);
init_swap_chain(info);
info.per_frame.resize(info.swapchainImageCount);
for (int i = 0; i < info.swapchainImageCount; i++)
{
init_per_frame(info, info.per_frame[i]);
}
init_depth_buffer(info);
init_texture(info);
init_uniform_buffer(info);
init_descriptor_and_pipeline_layouts(info, true);
init_renderpass(info, depthPresent);
VkShaderModuleCreateInfo vert_info = {};
VkShaderModuleCreateInfo frag_info = {};
vert_info.sType = frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
vert_info.codeSize = sizeof(template_vert);
vert_info.pCode = template_vert;
frag_info.codeSize = sizeof(template_frag);
frag_info.pCode = template_frag;
//init_shaders(info, &vert_info, &frag_info);
//init_shaders(info, vertShaderText, fragShaderText);
vertexShader.init(info.device, Shader::Type::SHADER_VERTEX, "E:/Code/WRayEngine/WRayEngine/WRayEngine/test.vert", "main");
fragmentShader.init(info.device, Shader::Type::SHADER_FRAGMENT, "E:/Code/WRayEngine/WRayEngine/WRayEngine/test.frag", "main");
info.shaderStages[0] = vertexShader.shaderStage;
info.shaderStages[1] = fragmentShader.shaderStage;
init_framebuffers(info, depthPresent);
//init_vertex_buffer(info, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), true);
const char *filename = "E:\\Code\\WRayEngine\\WRayEngine\\WRayEngine\\ball_cube.obj";
ObjLoader loader;
loader.Load(filename);
std::vector<float> buffer;
int numVertex, sizeOfPerVertex;
loader.GetVertexBuffer(0, ObjLoader::VERTEX_ATTRIBUTE_POSITION | ObjLoader::VERTEX_ATTRIBUTE_TEXCOORD,
buffer, numVertex, sizeOfPerVertex);
//vertexBuffer.init(info.device, Buffer::Type::BUFFER_VERTEX, g_vb_texture_Data, sizeof(g_vb_texture_Data), sizeof(g_vb_texture_Data[0]), info.memory_properties, true);
vertexBuffer.init(info.device, Buffer::Type::BUFFER_VERTEX, &buffer[0], numVertex, sizeOfPerVertex, info.memory_properties, true);
m_mesh.load(filename, info.device, info.memory_properties);
info.vi_attribs[0] = m_mesh.m_vertexBuffers[0].vi_attribs[0];
info.vi_attribs[1] = m_mesh.m_vertexBuffers[0].vi_attribs[1];
info.vi_binding = m_mesh.m_vertexBuffers[0].vi_binding;
init_descriptor_pool(info, true);
init_descriptor_set(info, true);
init_pipeline_cache(info);
init_pipeline(info, depthPresent);
//init_presentable_image(info);
VkClearValue clear_values[2];
init_clear_color_and_depth(info, clear_values);
VkRenderPassBeginInfo rp_begin;
init_render_pass_begin_info(info, rp_begin);
rp_begin.clearValueCount = 2;
rp_begin.pClearValues = clear_values;
/*
vkCmdBeginRenderPass(info.cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline);
vkCmdBindDescriptorSets(info.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS,
info.desc_set.data(), 0, NULL);
const VkDeviceSize offsets[1] = { 0 };
vkCmdBindVertexBuffers(info.cmd, 0, 1, &info.vertex_buffer.buf, offsets);
init_viewports(info);
init_scissors(info);
vkCmdDraw(info.cmd, 12 * 3, 1, 0, 0);
vkCmdEndRenderPass(info.cmd);
res = vkEndCommandBuffer(info.cmd);
assert(res == VK_SUCCESS);*/
//VkFence drawFence = {};
//init_fence(info, drawFence);
//VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
//VkSubmitInfo submit_info = {};
//init_submit_info(info, submit_info, pipe_stage_flags);
///* Queue the command buffer for execution */
//res = vkQueueSubmit(info.graphics_queue, 1, &submit_info, drawFence);
//assert(res == VK_SUCCESS);
///* Now present the image in the window */
//VkPresentInfoKHR present = {};
//init_present_info(info, present);
///* Make sure command buffer is finished before presenting */
//do {
// res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT);
//} while (res == VK_TIMEOUT);
//assert(res == VK_SUCCESS);
//res = vkQueuePresentKHR(info.present_queue, &present);
//assert(res == VK_SUCCESS);
//wait_seconds(1);
//if (info.save_images) write_ppm(info, "template");
}
void Application::update()
{
acquireSemaphore();
render();
present();
MSG msg;
HWND handle;
while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
{
}
else
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
handle = GetActiveWindow();
}
void Application::destroy()
{
vkDestroyFence(info.device, drawFence, NULL);
vkDestroySemaphore(info.device, info.imageAcquiredSemaphore, NULL);
destroy_pipeline(info);
destroy_pipeline_cache(info);
destroy_textures(info);
destroy_descriptor_pool(info);
//destroy_vertex_buffer(info);
//vertexBuffer.destroy(info.device);
destroy_framebuffers(info);
//destroy_shaders(info);
vertexShader.destroy(info.device);
fragmentShader.destroy(info.device);
destroy_renderpass(info);
destroy_descriptor_and_pipeline_layouts(info);
destroy_uniform_buffer(info);
destroy_depth_buffer(info);
destroy_swap_chain(info);
//destroy_command_buffer(info);
//destroy_command_pool(info);
destroy_device(info);
destroy_window(info);
destroy_instance(info);
}
Application * Application::instance()
{
if (s_instance == nullptr)
{
s_instance = new Application();
}
return s_instance;
}
void Application::acquireSemaphore()
{
// acquire semaphore
VkSemaphore acquire_semaphore;
if (recycled_semaphores.empty())
{
VkSemaphoreCreateInfo infos = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
vkCreateSemaphore(info.device, &infos, nullptr, &acquire_semaphore);
}
else
{
acquire_semaphore = recycled_semaphores.back();
recycled_semaphores.pop_back();
}
VkResult res = vkAcquireNextImageKHR(info.device, info.swap_chain, UINT64_MAX, acquire_semaphore, VK_NULL_HANDLE, &info.current_buffer);
if (res != VK_SUCCESS)
{
recycled_semaphores.push_back(acquire_semaphore);
return;
}
// If we have outstanding fences for this swapchain image, wait for them to complete first.
// After begin frame returns, it is safe to reuse or delete resources which
// were used previously.
//
// We wait for fences which completes N frames earlier, so we do not stall,
// waiting for all GPU work to complete before this returns.
// Normally, this doesn't really block at all,
// since we're waiting for old frames to have been completed, but just in case.
if (info.per_frame[info.current_buffer].queue_submit_fence != VK_NULL_HANDLE)
{
vkWaitForFences(info.device, 1, &info.per_frame[info.current_buffer].queue_submit_fence, true, UINT64_MAX);
vkResetFences(info.device, 1, &info.per_frame[info.current_buffer].queue_submit_fence);
}
if (info.per_frame[info.current_buffer].primary_command_pool != VK_NULL_HANDLE)
{
vkResetCommandPool(info.device, info.per_frame[info.current_buffer].primary_command_pool, 0);
}
// Recycle the old semaphore back into the semaphore manager.
VkSemaphore old_semaphore = info.per_frame[info.current_buffer].swapchain_acquire_semaphore;
if (old_semaphore != VK_NULL_HANDLE)
{
recycled_semaphores.push_back(old_semaphore);
}
info.per_frame[info.current_buffer].swapchain_acquire_semaphore = acquire_semaphore;
//return VK_SUCCESS;
}
void Application::updateCPUData()
{
float fov = glm::radians(45.0f);
info.Projection = glm::perspective(fov, static_cast<float>(info.width) / static_cast<float>(info.height), 0.1f, 100.0f);
static float offset = 0.f;
glm::vec3 camPos(
cos(m_cameraAngle.x)* sin(m_cameraAngle.y),
sin(m_cameraAngle.x)* sin(m_cameraAngle.y),
cos(m_cameraAngle.y));
glm::vec3 camUp(
cos(m_cameraAngle.x)* cos(m_cameraAngle.y),
sin(m_cameraAngle.x)* cos(m_cameraAngle.y),
-sin(m_cameraAngle.y));
camPos *= m_cameraDist;
info.View = glm::lookAt(camPos, // Camera is at (-5,3,-10), in World Space
glm::vec3(0, 0, 0), // and looks at the origin
camUp // Head is up (set to 0,-1,0 to look upside-down)
);
//offset += 0.01f;
info.Model = m_modelMatrix;// glm::mat4(1.0f);
// Vulkan clip space has inverted Y and half Z.
info.Clip = glm::mat4(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 1.0f);
info.MVP = info.Clip * info.Projection * info.View * info.Model;
}
void Application::updateTexture()
{
static bool initialized = false;
if (initialized)
{
return;
}
//init_texture(info);
initialized = true;
}
void Application::render()
{
updateTexture();
updateCPUData();
// update uniform buffer
{
uint8_t* pData;
VkResult res = vkMapMemory(info.device, info.uniform_data.mem, 0, info.uniform_data.buffer_info.range, 0, (void**)&pData);
assert(res == VK_SUCCESS);
memcpy(pData, &info.MVP, sizeof(info.MVP));
//vkUnmapMemory(info.device, info.uniform_data.mem);
VkMappedMemoryRange range;
range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
range.offset = 0;
range.pNext = NULL;
range.size = info.uniform_data.buffer_info.range;
range.memory = info.uniform_data.mem;
vkInvalidateMappedMemoryRanges(info.device, 1, &range);
vkFlushMappedMemoryRanges(info.device, 1, &range);
}
// Render to this framebuffer.
VkFramebuffer framebuffer = info.framebuffers[info.current_buffer];
// Allocate or re-use a primary command buffer.
VkCommandBuffer cmd = info.per_frame[info.current_buffer].primary_command_buffer;
// We will only submit this once before it's recycled.
VkCommandBufferBeginInfo begin_info{ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
// Begin command recording
vkBeginCommandBuffer(cmd, &begin_info);
// Set clear color values.
VkClearValue clear_value[2];
static float c = 0;
clear_value[0].color = { {0.1f, 0.2f, c+0.2f, 1.0f} };
clear_value[1].depthStencil.depth = 1;
clear_value[1].depthStencil.stencil = 0;
c += 0.01f;
// Begin the render pass.
VkRenderPassBeginInfo rp_begin{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
rp_begin.renderPass = info.render_pass;
rp_begin.framebuffer = framebuffer;
rp_begin.renderArea.extent.width = info.width;
rp_begin.renderArea.extent.height = info.height;
rp_begin.clearValueCount = 2;
rp_begin.pClearValues = clear_value;
// We will add draw commands in the same command buffer.
vkCmdBeginRenderPass(cmd, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
// Bind the graphics pipeline.
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline);
VkViewport vp{};
vp.width = static_cast<float>(info.width);
vp.height = static_cast<float>(info.height);
vp.minDepth = 0.0f;
vp.maxDepth = 1.0f;
// Set viewport dynamically
vkCmdSetViewport(cmd, 0, 1, &vp);
VkRect2D scissor{};
scissor.extent.width = info.width;
scissor.extent.height = info.height;
// Set scissor dynamically
vkCmdSetScissor(cmd, 0, 1, &scissor);
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, info.pipeline_layout, 0, NUM_DESCRIPTOR_SETS,
info.desc_set.data(), 0, NULL);
//const VkDeviceSize offsets[1] = { 0 };
//vkCmdBindVertexBuffers(cmd, 0, 1, &info.vertex_buffer.buf, offsets);
//vkCmdBindVertexBuffers(cmd, 0, 1, &vertexBuffer.buf, offsets);
// Draw three vertices with one instance.
//vkCmdDraw(cmd, vertexBuffer.m_numVertex, 1, 0, 0);
//vkCmdDraw(cmd, 3, 1, 0, 0);
m_mesh.draw(cmd);
// Complete render pass.
vkCmdEndRenderPass(cmd);
// Complete the command buffer.
VK_CHECK(vkEndCommandBuffer(cmd));
}
void Application::present()
{
VkCommandBuffer cmd = info.per_frame[info.current_buffer].primary_command_buffer;
// Submit it to the queue with a release semaphore.
if (info.per_frame[info.current_buffer].swapchain_release_semaphore == VK_NULL_HANDLE)
{
VkSemaphoreCreateInfo semaphore_info{ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
VK_CHECK(vkCreateSemaphore(info.device, &semaphore_info, nullptr,
&info.per_frame[info.current_buffer].swapchain_release_semaphore));
}
VkPipelineStageFlags wait_stage{ VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
VkSubmitInfo infoS{ VK_STRUCTURE_TYPE_SUBMIT_INFO };
infoS.commandBufferCount = 1;
infoS.pCommandBuffers = &cmd;
infoS.waitSemaphoreCount = 1;
infoS.pWaitSemaphores = &info.per_frame[info.current_buffer].swapchain_acquire_semaphore;
infoS.pWaitDstStageMask = &wait_stage;
infoS.signalSemaphoreCount = 1;
infoS.pSignalSemaphores = &info.per_frame[info.current_buffer].swapchain_release_semaphore;
// Submit command buffer to graphics queue
VK_CHECK(vkQueueSubmit(info.present_queue, 1, &infoS, info.per_frame[info.current_buffer].queue_submit_fence));
VkPresentInfoKHR present{ VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
present.swapchainCount = 1;
present.pSwapchains = &info.swap_chain;
present.pImageIndices = &info.current_buffer;
present.waitSemaphoreCount = 1;
present.pWaitSemaphores = &info.per_frame[info.current_buffer].swapchain_release_semaphore;
// Present swapchain image
vkQueuePresentKHR(info.present_queue, &present);
}
| 90a483ec6a29be34c3d3ca64371619aedec38662 | [
"C++"
]
| 9 | C++ | league1991/WRayEngine | 8afd117e8a1cf10c51f6826795d691527dadbb79 | 44f860af52b8d5ecc22359a6e52227d57e2af43e |
refs/heads/master | <repo_name>yunieju/leetcode<file_sep>/two_sum.py
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
seen = {}
for i, num in enumerate(nums):
temp = target - num
if temp in seen:
return [seen[temp], i]
else:
seen[num] = i
return []
<file_sep>/plus_one.py
# start with 1's digit and check the carry flag (digit == 9)
# we need to check case like 9, 99, 999
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
for i in range(len(digits)):
index = len(digits) - 1 - i
if digits[index] == 9:
digits[index] = 0
else:
digits[index] += 1
return digits
return [1] + digits
<file_sep>/contains_duplicate.py
class Solution:
# Time Complexity: O(N), Space Complexity: O(N)
def containsDuplicate(self, nums: List[int]) -> bool:
seen = set([])
for num in nums:
if num in seen:
return True
else:
seen.add(num)
return False
# Time Complexity: O(NlogN), Space Complexity: O(1)
def containsDuplicate(self, nums: List[int]) -> bool:
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
<file_sep>/decode_string.py
class Solution:
def decodeString(self, s: str) -> str:
stack = []
cur_num = ""
cur_string = ""
ans = ""
for c in s:
if c == "]":
while stack[-1] != "[":
cur_string = stack.pop() + cur_string
stack.pop() #pop "["
# cur_num = stack.pop()
while stack and stack[-1].isdigit():
cur_num = stack.pop() + cur_num
stack.append(cur_string * int(cur_num))
cur_string = ""
cur_num = ""
else:
stack.append(c)
return "".join(stack)
<file_sep>/is_subsequence.py
class Solution:
def isSubsequence1(self, s: str, t: str) -> bool:
for c in s:
if len(t) == 0:
return False
for i in range(len(t)):
if c not in t[i:]:
return False
if c == t[i]:
t = t[i+1:]
break
return True
# Greedy + Divide and conquer
def isSubsequence2(self,s: str, t:str) -> bool:
L_BOUND , R_BOUND = len(s), len(t)
def check(left_index, right_index):
if left_index == L_BOUND:
return True
if right_index == R_BOUND:
return False
if s[left_index] == t[right_index]:
left_index += 1
right_index += 1
return check(left_index, right_index)
return check(0,0)
<file_sep>/open_the_lock.py
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
q = [("0000", 0)]
visited = set()
count = 0
while len(q) > 0:
cur, count = q.pop(0)
if cur == target:
return count
if cur in deadends:
continue
visited.add(cur)
for n in self.neighbors(cur):
if n not in visited:
visited.add(n)
q.append((n, count + 1))
return -1
def neighbors(self, num: str):
for i in range(4):
x = int(num[i])
for d in (-1, 1):
y = (x + d) % 10
yield num[:i] + str(y) + num[i+1:]
<file_sep>/merge_sorted_array.py
class Solution:
#start with left
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
p1 , p2 = m-1, n-1
i = m+n-1
while p1 >= 0 and p2 >= 0:
if nums1[p1] >= nums2[p2]:
nums1[i] = nums1[p1]
p1 -= 1
else:
nums1[i] = nums2[p2]
p2 -= 1
i -= 1
nums1[:p2+1] = nums2[:p2+1]
#start with right
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
nums1_copy = nums1[:m]
nums1[:] = []
p1, p2 = 0, 0
while p1 < m and p2 < n:
if nums1_copy[p1] <= nums2[p2]:
nums1.append(nums1_copy[p1])
p1 += 1
else:
nums1.append(nums2[p2])
p2 += 1
if p1 < m:
nums1[p1+p2:] = nums1_copy[p1:]
if p2 < n:
nums1[p1+p2:] = nums2[p2:]
<file_sep>/design_linked_list.py
class MyLinkedList:
def __init__(self):
self.size = 0
self.head = ListNode(0)
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.head
for _ in range(index+1):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
"""
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
if index > self.size:
return
if index < 0:
index = 0
self.size += 1
new = ListNode(val)
prev, temp = None, self.head
for _ in range(index+1):
prev = temp
temp = temp.next
prev.next = new
new.next = temp
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
self.size -= 1
temp = self.head
for _ in range(index):
temp = temp.next
temp.next = temp.next.next
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
<file_sep>/README.md
# Leetcode Solutions in Python
| # | Title | Difficulty | Related Topic / idea |
| ----|-------|------------|------------------- |
| 66 | [Plus One](https://leetcode.com/problems/plus-one) | Easy | Array & mathematics|
|485|[Max Consecutive Ones](https://leetcode.com/problems/max-consecutive-ones/) | Easy | Array|
|628|[Maximum Product of Three Numbers](https://leetcode.com/problems/maximum-product-of-three-numbers)| Easy | Array |
|1518| [Water Bottles](https://leetcode.com/problems/water-bottles/) | Easy | Math | Stack & Two Pointers |
|168| [Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) | Easy | String |
|844| [Backspace String Compare](https://leetcode.com/problems/backspace-string-compare/) |Easy| String|
|189| [Rotate Array](https://leetcode.com/problems/rotate-array/) |Easy| Array|
|217| [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |Easy | Hashtable |
|155| [Minstack](https://leetcode.com/problems/min-stack/)|Easy|Stack|
|392| [Is Subsequence](https://leetcode.com/problems/is-subsequence/) |Easy| Greedy, Divide and Conquer |
|108| [Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) | Easy | BST |
|278| [First Bad Version](https://leetcode.com/problems/first-bad-version/) | Easy | Binary Search|
|53| [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | Easy | DP |
|203| [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) | Easy | Linked List|
|234| [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) |Easy | Linked List|
|88| [Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |Easy| Array|
|26| [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)|Easy|Array|
|346| [Moving Average from Data stream](https://leetcode.com/problems/moving-average-from-data-stream/)|Easy| Queue|
|359| [Logger Rate Limiter](https://leetcode.com/problems/logger-rate-limiter/) |Easy | Hash, Queue|
|144| [Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) | Medium| Tree|
|94| [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) | Medium| Tree|
|145| [Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) | Medium| Tree|
|19| [Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list)| Medium | Linked List|
|2| [Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) | Medium | Linked List |
|34| [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) | Medium| Binary Search|
|1513| [Number of Substrings with Only 1's](https://leetcode.com/problems/number-of-substrings-with-only-1s/) |Medium| Math |
|39| [Combination Sum](https://leetcode.com/problems/combination-sum/)|Medium| backtracking & dfs |
| 48| [Rotate Image](https://leetcode.com/problems/rotate-image/) |Medium| array, pythonic code|
|62 | [Unique Paths](https://leetcode.com/problems/unique-paths/) |Medium| Dynamic Programming & Math|
|75| [Sort Colors](https://leetcode.com/problems/sort-colors/) | Medium | Counting Sort|
|79| [Word Search](https://leetcode.com/problems/word-search/) |Medium| Backtracking |
|739| [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) | Medium | Array, Stack |
|394| [Decode String](https://leetcode.com/problems/decode-string/) |Medium| Stack & DFS |
|96| [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) | Medium | DP |
|107| [Binary Tree Level Order Traversal II](https://leetcode.com/problems/binary-tree-level-order-traversal-ii/)|Medium|DFS/BFS, Tree|
|5| [Longest Palindrome Substring](https://leetcode.com/problems/longest-palindromic-substring/)|Medium| DP|
|221| [Maximal Square](https://leetcode.com/problems/maximal-square/)|Medium| DP|
|622| [Design Circular Queue](https://leetcode.com/problems/design-circular-queue/) |Medium| Queue |
|286| [Walls and Gates](https://leetcode.com/problems/walls-and-gates/) | Medium | BFS |
|707| [Design Linked List](https://leetcode.com/problems/design-linked-list/) | Medium | Linked List|
|752| [Open the Lock](https://leetcode.com/problems/open-the-lock)|Medium| BFS|
|142| [Linked List Cycle 2](https://leetcode.com/problems/linked-list-cycle-ii/)|Medium| Linked List|
|702| [Search in a Sorted Array of Unknown Size](https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/) | Medium | Binary Search|
|162| [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | Medium | Binary Search |
<file_sep>/palindrome_linked_list.py
def isListPalindrome(l):
temp = l
count = 0
while temp:
count += 1
temp = temp.next
left, right= [], []
temp = l
for i in range(count //2):
left.append(temp.value)
temp = temp.next
if count % 2 == 1:
temp = temp.next
for i in range(count //2):
right.append(temp.value)
temp = temp.next
return left == right[::-1]
<file_sep>/binary_tree_level_order_traversal.py
class Solution:
# BFS + queue
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
q = [(root,0)]
while q:
curr,depth = q.pop()
if curr:
q.append((curr.right, depth + 1))
q.append((curr.left, depth + 1))
if len(res) <= depth:
res.append([curr.val])
else:
res[depth].append(curr.val)
return res
# DFS recursively
def levelOrderBottom2(self, root: TreeNode) -> List[List[int]]:
res = []
self.dfs(0, root, res)
return res
def dfs(self, level: int, root: TreeNode, res)-> List[List[int]]:
if root:
if len(res) < level + 1:
res.insert(0, [])
res[-(level+1)].append(root.val)
self.dfs(level +1, root.left, res)
self.dfs(level +1, root.right, res)
<file_sep>/longest_palindromic_substring.py
class Solution:
def longestPalindrome(self, s:str)-> str:
if len(s)< 0:
return 0
start, end = 0,0
for i in range(len(s)):
len1 = self.expandFromMiddle(s,i,i)
len2 = self.expandFromMiddle(s,i,i+1)
length = max(len1, len2)
if length > (end - start):
start = i - (length -1)//2
end = i + length //2
return s[start:end +1]
def expandFromMiddle(self, s:str, left: int, right: int):
if left > right:
return 0
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return right - left - 1
#Brute Force: Time Complexity: O(n^3) -> TLE
# def longestPalindrome(self, s: str) -> str:
# res = ""
# for i in range(len(s)): # substring starts from index i
# substring = ""
# for j in range(i, len(s)):
# substring += s[j]
# if self.checkPalindrome(substring):
# if len(substring) > len(res):
# res = substring
# return res
# def checkPalindrome(self, sub: str)-> bool:
# return sub[::-1] == sub
<file_sep>/walls_and_gates.py
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
if not rooms:
return
rows, cols = len(rooms), len(rooms[0])
q = []
for i in range(rows):
for j in range(cols):
if rooms[i][j] == 0:
q.append((i,j))
for row, col in q:
d = rooms[row][col] + 1
for dx, dy in (-1, 0), (1, 0), (0, -1), (0, 1):
r = row + dx
c = col + dy
if 0 <= r < rows and 0 <= c < cols and rooms[r][c] == 2147483647:
rooms[r][c] = d
q.append((r,c))
<file_sep>/number_of_substrings_with_only_1s.py
class Solution:
# def numSub(self, s: str) -> int:
# count = 0
# for i in range(len(s)):
# while i < len(s) and s[i] == "1":
# count += 1
# i += 1
# return count
# using arithmatic sum
def numSub(self, s:str) -> int:
count = 0
counts = []
total = 0
for i in range(len(s)):
if s[i] == "1":
count += 1
else:
counts.append(count)
count = 0
counts.append(count)
for count in counts:
subs = count * (count + 1) // 2
total += subs
# Since the answer may be too large, return it modulo 10^9 + 7.
total = total % (10**9 + 7)
return total
<file_sep>/word_search.py
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
self.ROWS = len(board)
self.COLS = len(board[0])
self.board = board
for row in range(self.ROWS):
for col in range(self.COLS):
if self.checkNeighbor(row, col, word):
return True
return False
def checkNeighbor(self, row, col, word):
if len(word) == 0:
return True
if row < 0 or row == self.ROWS or col < 0 or col == self.COLS or self.board[row][col] != word[0]:
return False
res = False
self.board[row][col] = '*'
for r_offset, col_offset in [(0,1), (0,-1), (1,0), (-1,0)]:
res = self.checkNeighbor(row+r_offset, col+col_offset, word[1:])
if res:
break
self.board[row][col] = word[0]
return res
<file_sep>/maximal_square.py
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if matrix is None or len(matrix) < 1:
return 0
rows, cols = len(matrix), len(matrix[0])
dp = [[0]*(cols+1) for _ in range(rows+1)]
maxlen = 0
for i in range(1,rows+1):
for j in range(1,cols+1):
if matrix[i-1][j-1] == '1':
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
maxlen = max(maxlen, dp[i][j])
return maxlen* maxlen
<file_sep>/binary_tree_inorder.py
class Solution:
# recursive
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.dfs(root,res)
return res
def dfs(self, root, res):
if not root:
return
self.dfs(root.left, res)
res.append(root.val)
self.dfs(root.right, res)
# iterative
def inorderTraversal(self, root: TreeNode) -> List[int]:
res, stack = [], []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
res.append(node.val)
root = node.right
return res
<file_sep>/sort_colors.py
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
l = cur = 0
r = len(nums) -1
while cur <= r:
if nums[cur] == 0:
nums[l], nums[cur] = nums[cur], nums[l]
l += 1
cur += 1
elif nums[cur] == 2:
nums[cur], nums[r] = nums[r], nums[cur]
r -=1
else:
cur += 1
# two pass algorithm
def sortColors(self, nums: List[int]) -> None:
color = [0] *3
for num in nums:
color[num] += 1
idx = 0
for i in range(3):
for _ in range(color[i]):
nums[idx] = i
idx += 1
<file_sep>/unique_binary_search_trees.py
class Solution:
# Time Complexity: O(n^2), Space Complexity: O(N)
def numTrees(self, n: int) -> int:
res = [0] * (n+1)
res[0] = 1
for i in range(n+1):
for j in range(i):
res[i] += res[j] * res[i-1-j]
return res[n]
<file_sep>/excel_sheet_column_title.py
class Solution:
def convertToTitle(self, n: int) -> str:
arr = [chr(x) for x in range(ord('A'), ord('Z')+1)]
res = []
while n > 0:
n, r = divmod(n-1, 26)
res.append(arr[r])
return "".join(res[::-1])
<file_sep>/backspace_string_compare.py
class Solution:
# time: O(M+N)
# space: O(1)
def backspaceCompare(self, S: str, T: str) -> bool:
p1, p2 = len(S) - 1, len(T) - 1
count = 0
while p1 >= 0 or p2 >= 0:
while p1 >= 0:
if S[p1] == "#":
count += 1
p1 -= 1
elif S[p1] != "#" and count > 0:
count -= 1
p1 -= 1
else:
break
while p2 >= 0:
if T[p2] == "#":
count += 1
p2 -= 1
elif T[p2] != "#" and count > 0:
count -= 1
p2 -= 1
else:
break
if (p1 < 0 and p2 >= 0) or (p1 >= 0 and p2 < 0):
return False
if (p1 >= 0 and p2 >= 0) and S[p1] != T[p2]:
return False
p1 -= 1
p2 -= 1
return True
# using two stacks
# time : O(M+N)
# space : O(M+N)
def backspaceCompare(self, S: str, T: str) -> bool:
stack1= []
for char in S:
if char != "#":
stack1.append(char)
elif char == "#" and len(stack1) >= 1:
stack1.pop()
stack2 = []
for char in T:
if char != "#":
stack2.append(char)
elif char == "#" and len(stack2) >= 1:
stack2.pop()
return stack1 == stack2
<file_sep>/maximum_product_of_three_numbers.py
'''
We need to check the negative numbers
two cases are available
negative * negative * positive = positive
positive * positive * positive = positive
'''
# Time complexity: O(nlogn)
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
sorted_nums = sorted(nums)
length = len(nums)
nnp = sorted_nums[0] * sorted_nums[1] * sorted_nums[length - 1]
ppp = sorted_nums[length -1] * sorted_nums[length -2] * sorted_nums[length -3]
return max(nnp, ppp)
'''
We need to check the negative numbers
two cases are available
negative * negative * positive = positive
positive * positive * positive = positive
We only need to track five values.
min1, min2, max1, max2, max3
return max(min1 * min2 * max1, max1*max2*max3)
'''
# Time Complexity : O(n), Space Complexity: O(1)
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
min1, min2 = float("inf"), float("inf")
max1, max2, max3 = float("-inf"), float("-inf"), float("-inf")
for num in nums:
if num <= min1:
min2 = min1
min1 = num
elif num <= min2: # min1 < num < min2
min2 = num
if num > max1:
max3 = max2
max2 = max1
max1 = num
elif num >= max2:
max3 = max2
max2 = num
elif num >= max3:
max3 = num
return max(min1*min2*max1, max1*max2*max3)
<file_sep>/minimum_moves_to_equal_array_elements.py
class Solution:
# # incrementing n - 1 elements by 1 means decrementing maximum value by 1
# # Eventually, the number of move we need is the sum of difference between the minimum and number
# # Time Complexity: O(N)
def minMoves(self, nums: List[int]) -> int:
moves = 0
minimum = min(nums)
for i in range(0, len(nums)):
moves += (nums[i] - minimum)
return moves
# # And we can make it more efficient without min fuction iterating one time
def minMoves(self, nums: List[int]) -> int:
moves = 0
minimum = float('inf')
for i in range(len(nums)):
moves += nums[i]
minimum = min(minimum, nums[i])
return moves - minimum * len(nums)
# DP solution
def minMoves(self, nums:List[int]) -> int:
nums.sort()
dp = [0] * len(nums)
res = 0
for i in range(1, len(nums)):
dp[i] = dp[i-1] + (nums[i] - nums[i-1])
res += dp[i]
return res
# DP without extra space
def minMoves(self, nums:List[int]) -> int:
nums.sort()
moves = 0
for i in range(1, len(nums)):
diff = moves + (nums[i] - nums[i-1])
nums[i] += moves
moves += diff
return moves
<file_sep>/cousins_in_binary_tree.py
class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
x_info = [0,0] #depth, parent
y_info = [0,0]
def dfs(root, key, key_info, depth):
if not root:
return
if root.right and root.right.val == key:
key_info[0], key_info[1] = depth+ 1, root.val
return
if root.left and root.left.val == key:
key_info[0], key_info[1] = depth + 1, root.val
return
dfs(root.right, key, key_info, depth + 1)
dfs(root.left, key, key_info, depth + 1)
return
dfs(root, x, x_info, 0)
dfs(root, y, y_info, 0)
return (x_info[0] == y_info[0]) and (x_info[1] != y_info[1])
<file_sep>/find_first_and_last_position_of_element_in_sorted_array.py
class Solution:
def findStartingIndex(self,nums, target):
idx = -1
l = 0
r = len(nums)-1
while l <= r:
m = l + (r-l)//2
if nums[m] >= target:
r = m - 1
else:
l += 1
if nums[m] == target:
idx = m
return idx
def findEndingIndex(self,nums, target):
idx = -1
l = 0
r = len(nums) - 1
while l <= r:
m = l + (r-l)//2
if nums[m] <= target:
l = m+1
else:
r -= 1
if nums[m] == target:
idx = m
return idx
def searchRange(self, nums: List[int], target: int) -> List[int]:
res = [-1, -1]
res[0] = self.findStartingIndex(nums, target)
res[1] = self.findEndingIndex(nums, target)
return res
<file_sep>/isomorphic_string.py
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
d1, d2 = dict(), dict()
for i,val in enumerate(s):
d1[val] = d1.get(val, [])+ [i]
for i,val in enumerate(s):
d2[val] = d2.get(val, [])+ [i]
for i in range(len(s_dict.values())):
s_val = list(s_dict.values())[i]
t_val = list(t_dict.values())[i]
if s_val != t_val:
return False
return True
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return len(set(s)) == len(set(zip(s, t))) == len(set(t))
<file_sep>/remove_nth_node_from_end_of_list.py
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
fast = dummy
slow = dummy
for i in range(n+1):
fast = fast.next
while fast:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
#Brute force
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# step 1. calculate the length of the linked list
temp = head
# make a dummy node to handle edge cases
dummy = ListNode(0)
dummy.next = head
length = 0
while temp:
length += 1
temp = temp.next
# step 2. find the node need to be deleted
temp = dummy # reset temp to the head
for i in range(1, length-n):
temp = temp.next
temp.next = (temp.next.next if temp.next.next else None)
return dummy.next
<file_sep>/REFERENCES.md
# Useful resources
for my reference
- [General backtracking solutions](https://leetcode.com/problems/combination-sum/discuss/429538/General-Backtracking-questions-solutions-in-Python-for-reference-%3A)
- [Python Binary Search Templates](https://leetcode.com/discuss/general-discussion/786126/python-powerful-ultimate-binary-search-template-solved-many-problems)
- [Tech Interview Handbook](https://yangshun.github.io/tech-interview-handbook/algorithms/array) by Yangshun
| 78a9d14d05967beb5433a00bd5920dd87a901d4f | [
"Markdown",
"Python"
]
| 28 | Python | yunieju/leetcode | d4c2cf38fb3547c4e1701ba6d87889fecfb1ded1 | 56044395fb9844fe47e331344725bd9f35ee3af9 |
refs/heads/master | <file_sep>
getRandom=()=>{
const quotes = [
"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.",
"Don't watch the clock; do what it does. Keep going.",
"The secret of getting ahead is getting started.",
"Well done is better than well said.",
"You miss 100% of the shots you don’t take.",
"A goal is a dream with a deadline.",
"Outstanding people have one thing in common: An absolute sense of mission.",
"Trying is winning in the moment.",
"Fall down seven times and stand up eight.",
"You just can't beat the person who never gives up.",
"There is little success where there is little laughter.",
"We cannot solve our problems with the same thinking we used when we created them."
];
let min = Math.ceil(0);
let max = Math.floor(quotes.length-1);
let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
//let randomNumber =Math.floor( Math.random(0, quotes.length-1))
return quotes[randomNumber]
}
function getRandomIntInclusive(min, max) {
//The maximum is inclusive and the minimum is inclusive
}
callbackRandom = (event) => {
let quote = getRandom()
console.log(quote)
document.querySelector('#quote').textContent= quote
// console.dir(event.target)
}
init = () => {
document.querySelector('button').addEventListener("click", callbackRandom)
callbackRandom()
}
window.addEventListener("load", init)
<file_sep># Quote of the Day WebApp
Create a webapp to display a random quote using HTML, CSS and Javascript
## Rules
- Setup a consistent project structure
- Use vanilla javascript (no JQuery but Bootstrap css is ok)
- Only use [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/) as resource
- You will work on your own: it's an individual assignment
***Bonus point if you user Git properly!***
Commit & push your working code. Then create a new branch, implement a new feature and merge it when you finished. Use the commit message to document your work. Then start again with the next feature (if any).
[Review the process here, if you need](https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging)
## Technical requirements
Create a function that returns a random quote from the array of quotes that's given (check below "Sample Data"). Remember that there's a nice function for random numbers in the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math) for *Math.rand()*.
Sometimes it's a good idea to create multiple functions, that do one specific thing only, to make the code more readable and easier to maintain / extend.
If you think they can be useful put some comments to document your code, but remember don't tell-stories (review [Don't be a Ninja](https://codepen.io/leandro_berlin/pen/GzKWwv?editors=0010)). Add the needed JavaScript to load a new random quote, when the button below the quote is used.
## Demo
You're very welcome to customize the UI of your webapp. Here a demo with the minimum requirments.
<img alt="mockup" src="demo.gif">
## Sample Data:
Here a list of random quotes you can use for your app
```javascript
const quotes = [
"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.",
"Don't watch the clock; do what it does. Keep going.",
"The secret of getting ahead is getting started.",
"Well done is better than well said.",
"You miss 100% of the shots you don’t take.",
"A goal is a dream with a deadline.",
"Outstanding people have one thing in common: An absolute sense of mission.",
"Trying is winning in the moment.",
"Fall down seven times and stand up eight.",
"You just can't beat the person who never gives up.",
"There is little success where there is little laughter.",
"We cannot solve our problems with the same thinking we used when we created them."
];
```
| dfe8dcb2f1731e2ec1e6a661891e31fe5ed441c5 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | 123aadina/QoD | 39958465be5837a1c9616c65fe9475b6a90f6073 | 3dd981eb778f62844d4b370b29bed92ffda75ea3 |
refs/heads/master | <file_sep>var nombre = prompt("Digite su nombre por favor");
document.write("<p>"+nombre+"</p>");
| 92de5846d91b4a48c603aea4bf5ac5f954d658cd | [
"JavaScript"
]
| 1 | JavaScript | ozkrmora/pSimple | c49109568ad27eb2c81d1e82faa18932b4221d5f | f57dda0c5c5aa43bb3259144566535370a87f845 |
refs/heads/master | <repo_name>damonsong/node-spotify-playlist-export<file_sep>/main.js
require('dotenv').config();
const fs = require('fs');
const SpotifyWebApi = require('spotify-web-api-node');
const Promise = require('bluebird');
const moment = require('moment');
const _ = require('underscore');
/**
* INPUT PLAYLIST ID HERE
*/
var playlistId = "5r9BATxFQONQs6EUdXncAX";
var spotifyApi = new SpotifyWebApi({
clientId: process.env.clientId,
clientSecret: process.env.clientSecret
});
var promiseArray = [];
var tracksArray = [];
var tracksArrayRaw = [];
var totalTracks = 0;
var username = "kluskey";
// Retrieve an access token
spotifyApi.clientCredentialsGrant().then(
function(data) {
// console.log('The access token expires in ' + data.body['expires_in']);
// console.log('The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
runBackup();
},
function(err) {
console.log('Something went wrong when retrieving an access token', err.message);
}
);
function runBackup() {
getTotalTracks()
.then(function(totalTracks) {
console.log('Total tracks to pull:', totalTracks);
// we can only pull 100 at a time
for (let index = 0; index < totalTracks; index += 100) {
console.log('Pulling batch:', index)
promiseArray.push(pullBatch(index))
}
//uncomment for single batch test
// promiseArray.push(pullBatch(0))
return Promise.all(promiseArray)
})
.then(function(result) {
processRawTrackArray();
})
.then(function(result) {
writeExportsToFile();
})
.catch(function(error) {
console.error(error);
})
}
function pullBatch(startIndex) {
return new Promise(function(resolve, reject) {
spotifyApi.getPlaylistTracks(username, playlistId, {
offset: startIndex,
limit: 100
})
.then(function(returnData) {
// console.log('Some information about this playlist', data.body);
let data = returnData.body;
// console.log(JSON.stringify(data, null, 2));
data.items.forEach(item => {
tracksArrayRaw.push(item);
});
resolve();
}, function(err) {
console.log('Something went wrong!', err);
reject(err);
});
});
}
function getTotalTracks() {
return new Promise(function(resolve, reject) {
spotifyApi.getPlaylistTracks(username, playlistId)
.then(function(returnData) {
let data = returnData.body;
//update the total of all tracks
totalTracks = data.total;
resolve(totalTracks);
}, function(err) {
console.log('Something went wrong!', err);
reject(err);
});
});
}
function processRawTrackArray() {
return new Promise(function(resolve, reject) {
tracksArrayRaw.forEach(rawItem => {
// console.log(item.track.artists);
let artistNames = [];
rawItem.track.artists.forEach(artist => {
// console.log(element.name);
artistNames.push(artist.name)
});
addTrackToExport(rawItem.track.name, artistNames.join(", "), rawItem.track.album.name, rawItem.added_at, rawItem.track.external_urls.spotify);
});
resolve();
});
}
function addTrackToExport(trackName, artistName, albumName, date, url) {
let trackString = trackName + " | " + artistName + " | " + albumName + " | " + date + " | " + url + "\n";
tracksArray.push(trackString);
}
function writeExportsToFile() {
console.log("Writing tracks to file... Please wait.");
fs.writeFile('backup.txt', tracksArray.join(""), (err) => {
if (err) throw err;
console.log(tracksArray.length + ' tracks have been saved!');
});
}<file_sep>/readme.md
# node-spotify-playlist-export
#### A simple NodeJS tool to export all song names & artists from a Spotify playlist.
### Setup
0. (Make sure `node` and `npm` are installed).
1. Run `npm install`
2. [Create a new Spotify app of your own here and grab the Client ID and Client Secret.](http://developer.spotify.com/)
2. Create a `.env` file and add:
```
clientId=YOUR_SPOTIFY_CLIENT_ID
clientSecret=YOUR_SPOTIFY_CLIENT_SECRET
```
4. Paste the Playlist ID of your desired playlist into the `playlistId` at the top of the file.
5. Run `npm start` and your tracks will be saved with the title, artist, album, date added, and URL! All will be saved to a backup.txt file with information separated by pipe (`|`) characters.
In the existing implementation, the code saves all tracks [from this playlist](https://open.spotify.com/user/kluskey/playlist/5r9BATxFQONQs6EUdXncAX?si=Oq9M6K_eR8Oi7h2Juv-vTA).
Thanks! Let me know if you have any questions. | ee8b7eb6d909c73e9384b1f85da348522b086427 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | damonsong/node-spotify-playlist-export | f634b3630c27f114485f420855cdaf15fffe8dfc | a44e33dba61e3200b832706a56afd945b513765a |
refs/heads/master | <file_sep>import speech_recognition as sr
def ListenToVoice():
mic = sr.Recognizer()
with sr.Microphone() as source:
mic.adjust_for_ambient_noise(source)
print("Please say something")
audio = mic.listen(source)
print("Recognizing Now .... ")
try:
phrase = mic.recognize_google(audio)
if(phrase.lower() is "listen here new speaker"):
with open("microphone-results.wav", "wb") as f:
f.write(audio.get_wav_data())
return (phrase)
except Exception as e:
return("Error : " + str(e))<file_sep># **Contact Information** #
Name: <NAME>
Phone: 440-829-2808
Email: <EMAIL>
# **Co-op Work** #
## **National Interstate Insurance** ##
* **Position**: Developer
* **Dates**: Summer 2015 to present
* **Responsibilities**
* Worked on the front and back ends of web based applications for insurance premium rating and document generation
* During my experience at National Interstate, I worked on the operations team working on restructing systems to reduce day to day issues
* Worked with and developed data bases for insurance and customer data
* Built a web application to allow regular business employees to manage insurance forms internally
* **Technical Skills Used**:
* **Languages**:
* C#, JavaScript, SQL, XML
* **Tools**:
* Visual studio
* SQL Server
* **Non-Technical Skills**:
* Worked on a team with other developers
* Learned how to communicate with non-technical employees
# **Projects Sought** #
## **Type** ##
* Machine Learning or AI
* tensor flow python library
* build predictive models based on high level algorithms
* deep learning
* Augmented Reality
* Microsoft Hololense
* Potentially commercial application<file_sep># <NAME> - Individual Capstone Assessment
Our project is all about real-world impact. The idea of anabling people to connect better and easier is something that deffinitely appeals to me. From an academic perspective, this project will expose me to new, cutting-edge technologies in Augmented Reality and allow me to showcase my software design capabilities. This will force me to work with both hardware and software, ensuring that the actual software components interface well with the hardware components, like a headset or camera. Working in a team will also provide me with valuable experience which will be applicable throughout my career. This will involve a lot of research across the board, which is further helped by my academic experience.
The college curriculum at UC has given me many opportunities which have furthered my skills as a developer and software engineer. The most applicable course has certainly been Software Engineering, which has already given me experience in providing design documents, UML diagrams, and a functioning prototype of a product of my own creation with a team. This project is going to be rather large. Having experience in creating class and sequence diagrams will be very useful in communicating designs and ensuring understanding. Python Programming will also be applicable. That course exposed me to using third party libraries in my own project, so that experience is directly useful in this case as well. Additionally, Intro to Public Speech will also be useful, as we will have to present this project at the Senior Expo.
My co-op experiences have been even more valuable. Working at Honeywell Intelligrated as a Software Project Engineer allowed me to gain experience in working in a team for the first time. This will be useful as this project also involves teamwork. Working as a Developer at Siemens PLM Software has been even more useful. While there, I gained experience in software design, presenting designs, working with source control via Git, and implementing new designs. All of these things will be applicable to my senior design project. Source control via Git is already being used for our project repository. Design diagrams will be incredibly important, as we are expected to create UML and user stories which will showcase our project at various levels of abstraction.
I am extremely motivated and excited to participate in this project. I am interested in the idea of language processing via machine learning. Augmented/virtual reality are incredibly popular now, so working with these technologies will be exciting for me. Helping people experience other cultures is also appealing on a more personal level. Ideally, this project will be scalable and perhaps distributed into real-world use. That's much more exciting that just working on an assignment.
Preliminary design considerations brings up a lot to think about. First we should determing how we will handle the three main modules: speech-to-text, translation, and hardware integration. After that, it's more about treating each as a black box and making sure each works individually. Our expected results is creating a working prototype, ideally something that will be scalable and extended in the future. We will evaluate contributions by keeping track of participation by monitoring commits to our Git repository. We will know when we are done when the initial prototype works with little to no bugs.<file_sep>package com.example.testapp;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import com.chaquo.python.Python;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCamera2View;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import com.chaquo.python.Python;
import com.chaquo.python.PyObject;
import com.chaquo.python.android.AndroidPlatform;
public class MainActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {
JavaCamera2View javaCamera2View;
File casFile;
private Mat mRgba,mGrey;
private Handler mainHandler = new Handler();
private volatile boolean stopThread = false;
private volatile String text1 = "hello";
CascadeClassifier faceDetected;
private static final int SPEECH_REQUEST_CODE = 1000;
SpeechThread speechThread = new SpeechThread();
private boolean isRunning;
PyObject stt = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
javaCamera2View = (JavaCamera2View)findViewById(R.id.javaCamera);
javaCamera2View.setCvCameraViewListener(this);
//speechThread.run();
if (! Python.isStarted()) {
Python.start(new AndroidPlatform(this));
}
Python py = Python.getInstance();
stt = py.getModule("SpeechToText");
startService(new Intent(this, SpeechService.class));
}
public String getText()
{
return text1;
}
public void setText(String text)
{
text1 = text;
}
@Override
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat();
mGrey = new Mat();
}
@Override
public void onCameraViewStopped() {
mRgba.release();
mGrey.release();
}
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGrey = inputFrame.gray();
Mat mRgbaT = mRgba.t();
Core.flip(mRgba.t(), mRgbaT, 1);
Imgproc.resize(mRgbaT, mRgbaT, mRgba.size());
//detect face
MatOfRect faceDetections = new MatOfRect();
faceDetected.detectMultiScale(mRgbaT,faceDetections);
//startService(new Intent(this, SpeechService.class));
if(!isRunning) {
speechThread.start();
}
for(Rect rect: faceDetections.toArray())
{
//face detected yee haw lets capture it
//Imgproc.rectangle(mRgbaT,new Point(rect.x,rect.y), new Point(rect.x + rect.width, rect.y + rect.height),
//new Scalar(255,0,0));
Imgproc.putText(mRgbaT,getText(),new Point(rect.x,rect.y),0,2,new Scalar(0,255,0));
}
return mRgbaT;
}
@Override
protected void onResume() {
super.onResume();
if(!OpenCVLoader.initDebug()){
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION,this,baseCallback);
}
else
{
try {
baseCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
javaCamera2View.disableView();
}
private void speak()
{
PyObject speech = stt.callAttr("ListenToVoice");
setText(speech.toString());
isRunning = false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case SPEECH_REQUEST_CODE:{
if(resultCode == RESULT_OK && data !=null){
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
text1 = result.get(0);
isRunning = false;
}
break;
}
}
}
private BaseLoaderCallback baseCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) throws IOException {
switch (status)
{
case LoaderCallbackInterface.SUCCESS:
{
InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
File cascade = getDir("cascade", Context.MODE_PRIVATE);
casFile = new File(cascade,"haarcascade_frontalface_alt2.xml");
FileOutputStream fos = new FileOutputStream(casFile);
byte[] buffer = new byte[4096];
int byteRead;
while((byteRead = is.read(buffer)) != -1){
fos.write(buffer,0,byteRead);
}
is.close();
fos.close();
faceDetected = new CascadeClassifier(casFile.getAbsolutePath());
if(faceDetected.empty()){
faceDetected = null;
}
else{
cascade.delete();
}
javaCamera2View.enableView();
}
break;
default:
{
super.onManagerConnected(status);
}
break;
}
}
};
class BroadcastReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
try
{
System.out.println("revieved text");
String data = intent.getStringExtra("speech"); // data is a key specified to intent while sending broadcast
setText(data);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
class SpeechThread extends Thread {
@Override
public void run() {
isRunning = true;
speak();
}
}
}
<file_sep># **Contact Information** #
Name: <NAME>
Phone: (937) 941-7859
Email: <EMAIL>
# **Co-op Work Experience** #
## **Honeywell Intelligrated** ##
* **Position**: Software Project Engineer
* **Department**: Software Controls Engineering
* **Dates**: Fall 2016 and Summer 2017
* **Responsibilities**
* Configure graphics application to monitor devices in real time
* Configure machine operation code in C++ to control flow through various assembly lines within a large-scale distribution center
* Configure simulation software to simulate flow and processes within a distribution center
* **Technical Skills Used**:
* **Languages**:
* C++, C#, Java, SQL, XML
* **Tools**:
* Tortoise SVN version control
* SQL Server
* Windows Server
* **Non-Technical Skills**:
* Experienced code review process
* Bi-weekly status meetings
* Waterfall process
## **Siemens PLM Software** ##
* **Position**: Software Developer
* **Department**: Product Engineering Software
* **Dates**: Spring 2018 to current
* **Responsibilities**:
* Design and implement a debugging tool to aid in the development/testing process
* Ensure two large-scale applications communicate and integrate with each other
* Utilize cloud programming paradigms to develop a new product to modernize legacy software
* **Technical Skills Used**:
* **Languages**:
* C#, Python, C++, SQL, Java
* **Tools**:
* GitLab source control and continous integration
* Postman for API testing
* Visual Studio debugger
* CMake
* In-house source control for large-scale applications
* WPF for C# and .NET
* **Non-Technical Skills Used**:
* Agile Scrum
* Pressentations and code demos
* Documentation via SharePoint and in-house wikis
* Continuous Integration and DevOps processes
* Project management experience
* Software design patterns
* **Expertise**
* Software design patterns
* Threaded programming in C#
* UI programming in C#
* WPF and Windows Forms
* Interprocess communication in C# and in C++ via named pipes
* .NET concepts
* Managed code and CLR profiling
# **Projects Sought** #
## **Type** ##
* Machine Learning and AI based
* Deep learning and neural networks
* Natural language processing
* Ideally tensorflow
* Augmented or Virtual Reality
* GUI-based
* Something real time and tangible?
* Possibly Cybersecurity
* Pen-testing or cyber defense related
## **Tools** ##
* Modern, high level language
* Python ideally
* Some sort of integration with hardware
<file_sep># **Contact Information** #
Name: <NAME>
Phone: (330) 840-0104
Email: <EMAIL>
# **Co-op Work Experience** #
## **National Interstate** ##
* **Position**: Programmer COOP
* **Dates**: Fall 2016, Summer 2017, and Spring 2018
* **Responsibilities**
* Maintain database and fix bugs as they arise
* Develop web app with MVC arcitecture
* **Technical Skills Used**:
* **Languages**:
* C#.NET, SQL, XML
* **Tools**:
* Visual studio
* SQL Server
## **KLH Engineers** ##
* **Position**: Software Developer COOP
* **Dates**: Fall 2018, Summer 2019
* **Responsibilities**:
* Created tools to make engineer processes more efficient
* Designed application that acted as a Sql Server user management system
* **Technical Skills Used**:
* **Languages**:
* C#.NET, VB.NET, python
* **Tools**:
* Visual Studio, TFS
* Revit
* **Non-Technical Skills Used**:
* Worked in Agile environment
* Used code reviews
* Software demos
* Software design patterns, processes
# **Projects Sought** #
## **Type** ##
* Augmented or Virtual Reality
* GUI-based
* Something real time and tangible?
* using Microsoft Hololense
<file_sep># **Contact Information** #
Name: <NAME>
Phone: (513) 550-1086
Email: <EMAIL>(school) or <EMAIL>(personal)
# **Co-op Work Experience** #
## **Honeywell Intelligrated** ##
* **Position**: Software Engineer
* **Dates**: Fall 2016, Summer 2017, and Spring 2018
* **Responsibilities**
* Developed a Rest API for posting HTTP requests to a message bus and transmitting response messages back to a specific server. This project was developed in Java and used apache software for
* At Honeywell, I learned and worked in a Agile/Scrum environment participating through each step of the project project.
* Created and maintained a database with schemas, stored procedures, and triggers in SQLServer.
* Developed a python script to read timings within log files for internal use in the company. This python script was mostly used for testing purposes to see how long a specific process in a program took.
* Developed a communication system between PLCs, a message bus, and other servers through a socket connection. The communication system handled all inbound and outbound messages and provided a way for different types of machines/servers to communicate with each other. The project was developed in Java.
* **Technical Skills Used**:
* **Languages**:
* C++, C#, Java, SQL, XML, python, erlang
* **Tools**:
* IntelliJ
* Visual studio
* Hyper Sql
* Linux
* SQL Server
* **Non-Technical Skills**:
* Experienced code review process
* Worked in Agile/scrum environment
## **Projetech** ##
* **Position**: Software Developer
* **Dates**: Fall 2018, Summer 2018
* **Responsibilities**:
* Designed a web application that allowed users to sync remote databases to a local database
* Designed application that acted as a Sql Server user management system
* **Technical Skills Used**:
* **Languages**:
* C#, Vue.js, javascript
* **Tools**:
* Git source control and continous integration
* Postman for API testing
* Visual code
* **Non-Technical Skills Used**:
* Worked in Agile/scrum environment
* Presentation and code demos
* Project management experience
* Software design patterns
# **Projects Sought** #
## **Type** ##
* Machine Learning and AI based
* Deep learning and neural networks
* using tensor flow library
* Augmented or Virtual Reality
* GUI-based
* Something real time and tangible?
* using Microsoft Hololense
<file_sep># Project: Sight of Sound #
## Team Members ##
* <NAME> - <EMAIL>
* <NAME> - <EMAIL>
* <NAME> - <EMAIL>
* <NAME> - <EMAIL>
## Faculty Advisor ##
TBA
## Project Background ##
Deafness is an ailment which affects many people. Estimates are around one in every ten people has some form of hearing loss. Beyond that, there exist countries with multiple national languages. Tourists visiting these countries must either learn those dialects or only visit countries which are friendly towards their mother tongue. This causes an undue hardship.
## Problem Statement ##
Make it easier for people to understand languages with which they are not fluent, or can't even hear at all.
## Inadequacy of Current Solutions ##
Current implementations which solve this problem are not robust. Google translate is of course a ubiquitous approach to this situation. However, it's real time capabilities are lacking. It involves a user staring at their phone and hoping Google picks up the phrase and waits for the translation. It lacks a human element.
## Background Skills/Interests ##
We all enjoy travel and experiencing other cultures, and we want to make an impact with our work.
Each of us are interested in the fields of augmented reality and virtual reality. This project will allow us to utilize these technologies while also solving a real-world problem in a way that is impactful. We all have experience with software and working with third party APIs, so we are all prepared to learn new technologies as necessary through documentation.
## Our Approach ##
Implement a real-time subtitle system in Augmented Reality. As phrases are detected by our AR interface, it is then translated to the user-selected language. For those who are entirely deaf, this will allow them to understand conversations. For those who are speaking to someone else who speaks a foreign language, they will be better able to comprehend and convey ideas while maintaining the human element of conversation, being able to view body language and actually see their partner speak.
As far as a demo, we would ideally be able to show this project in action. Using some kind of AR device (a headset or phone, preferably), we can allow a user to wear/operate the device and see subtitles in relatively real-time. Our ultimate goal is to get this thing in a working state, maybe even marketing it eventually.
<file_sep>rootProject.name='testApp'
include ':app'
include ':opencv'
include ':java'
include ':openCVLibrary349'
<file_sep># Sight of Sound #
## Senior Design Project for UC ##
This is our Senior Design project at the University of Cincinnati. We've decided to call it Sight of Sound.
Please visit our [wiki](https://github.com/smith-gj/SeniorDesign/wiki/Homepage-and-Table-of-Contents) for more detailed project information.
<file_sep># User Stories #
1) When I wear the AR Headset, I want to be able to see speech bubbles appear when people in my field of view speak. The speech bubbles should be to one side of the speaker's head.
2) As a deaf user, I want a visual que to know how loud or soft someone is speaking. I expect to see the speech bubble shrink or grow based on volume.
3) When someone is speaking behind me I want to see a speech bubble all the way to one side of my field of view with an arrow telling me where the sound is coming from. This
bubble should also be greyed out as a que that the speaker is not in my field of view.
4) When I am wearing the headset and talking, I don't want to see a speech bubble for myself.<file_sep>package com.example.testapp;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import com.chaquo.python.Python;
import com.chaquo.python.PyObject;
import com.chaquo.python.android.AndroidPlatform;
import java.util.Locale;
import androidx.annotation.Nullable;
public class SpeechService extends Service {
private String text = "hello";
PyObject stt = null;
boolean isRunning = false;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
SpeechRecognizer speechRecognizer;
Intent startIntent = new Intent("start");
intent.putExtra("Start","start");
Python py = Python.getInstance();
stt = py.getModule("SpeechToText");
speak();
Intent stopIntent = new Intent("stop");
intent.putExtra("Stop","stop");
return START_STICKY;
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) {
return super.registerReceiver(receiver, filter, broadcastPermission, scheduler);
}
private void sendMessage(String msg)
{
Intent intent = new Intent("speech");
intent.putExtra("Status", msg);
sendBroadcast(intent);
}
private void speak()
{
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
try{
startActivity(speechIntent);
speakThread();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private void restartService()
{
PyObject speech = stt.callAttr("RestartService");
}
public void speakThread()
{
Thread thread = new Thread(){
@Override
public void run() {
PyObject speech = stt.callAttr("ListenToVoice");
setText(speech.toString());
sendMessage(speech.toString());
}
};
thread.run();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 4cdd75e616602ea0d4ad366804c5717eee1af6f4 | [
"Markdown",
"Java",
"Python",
"Gradle"
]
| 12 | Python | smith-gj/SeniorDesign | f794af403ecfd392ecde7a46021910b42b1b03f0 | 3e77ff459afce8bdff043d32e724652a1cc9b722 |
refs/heads/main | <file_sep>from model.tft5 import SnapthatT5
from model.lr_schedule import CosineDecayWithWarmUP
import tensorflow as tf
def get_model(strategy=None,
metrics=None,
model_fn=SnapthatT5.from_pretrained,
P=None):
with strategy.scope():
if metrics is None:
metrics = [tf.keras.metrics.SparseTopKCategoricalAccuracy(name='accuracy', k=1)]
model = model_fn(P.model_name)
learning_rate = CosineDecayWithWarmUP(initial_learning_rate=P.initial_learning_rate,
decay_steps=P.epochs * P.steps_per_epoch - P.warm_iterations,
alpha=P.minimum_learning_rate,
warm_up_step=P.warm_iterations)
optimizer = tf.keras.optimizers.Adam(learning_rate)
model.compile(optimizer=optimizer, metrics=metrics)
return model
def load_pretrained_model(model_fn =SnapthatT5.from_pretrained,
P = None,
weight_path = None
):
if weight_path is None:
weight_path = P.weight_path
model = model_fn(P.model_name)
model.load_weights(weight_path)
return model
<file_sep>from model.tft5 import SnapthatT5
from model.lr_schedule import CosineDecayWithWarmUP
from model.model_getter import get_model
<file_sep>tensorflow==2.4.0
transformers
beautifulsoup4
compress_pickle
tqdm
sklearn
pandas
tensorflow_addons
matplotlib
lxml
<file_sep>from scaping.yelp import get_reviews
<file_sep>from bs4 import BeautifulSoup
from tqdm import tqdm
from compress_pickle import dump
def process_mams(xml_path, output_path = None):
root = BeautifulSoup(
open(xml_path))
categories = []
for ac in root.find_all('aspectcategory'):
categories.append(ac['category'])
set_of_categories = set(categories)
print(set_of_categories)
examples = []
for sentence in tqdm(root.find_all('sentence')):
example = {}
example['text'] = sentence.text.replace('\n', '')
aspects = {k: 'none' for k in set_of_categories}
for cat in sentence.find_all('aspectcategory'):
aspects[cat.get('category')] = cat.get('polarity')
example['aspects'] = aspects
examples.append(example)
if output_path is not None:
dump(examples, output_path)
return examples
<file_sep># aspect-sentiment-dashboard<file_sep>from transformers import AutoTokenizer
from tqdm import tqdm
import tensorflow as tf
class Token_Manager:
def __init__(self, P):
self.tokenizer = AutoTokenizer.from_pretrained(P.model_name)
self.P = P
@staticmethod
def to_question_answer(example):
question = ''.join([k + '? ' for k, v in example['aspects'].items() if v != 'none'])
context = example['text']
question_context = f"answer_me: {question} context: {context} </s>"
answer = ', '.join(['%s %s' % (k, v) for k, v in example['aspects'].items() if v != 'none'])
answer = f"{answer} </s>"
example['question_and_context'] = question_context
example['answer'] = answer
return example
def encode_to_tokens(self, example, decoder = True):
encoder_inputs = self.tokenizer(example['question_and_context'], truncation=True,
return_tensors='tf', max_length=self.P.encoder_max_len,
pad_to_max_length=True)
input_ids = encoder_inputs['input_ids'][0]
input_attention = encoder_inputs['attention_mask'][0]
if decoder:
decoder_inputs = self.tokenizer(example['answer'], truncation=True,
return_tensors='tf', max_length=self.P.decoder_max_len,
pad_to_max_length=True)
target_ids = decoder_inputs['input_ids'][0]
target_attention = decoder_inputs['attention_mask'][0]
else:
target_ids = tf.zeros((1,))
target_attention = tf.zeros((1,))
return {'input_ids': input_ids,
'attention_mask': input_attention,
'labels': target_ids,
'decoder_attention_mask': target_attention}
def tokenize_dataset(self, examples, compose_qa_fn = None):
tokenized_dataset = {'input_ids': [],
'labels': [],
'attention_mask': [],
'decoder_attention_mask': []}
if compose_qa_fn is not None:
examples = [compose_qa_fn(example) for example in examples]
else:
examples = [self.to_question_answer(example) for example in examples]
for example in tqdm(examples):
values = self.encode_to_tokens(example)
for i, k in enumerate(tokenized_dataset.keys()):
tokenized_dataset[k].append(values[k])
for k, v in tokenized_dataset.items():
tokenized_dataset[k] = tf.stack(v, axis=0)
self.tokenized_dataset = tokenized_dataset
return tokenized_dataset, examples
@staticmethod
def _to_x_none(example):
return (example, tf.ones((1,)))
@staticmethod
def idx_slice_dictionary(dict_, idx):
try:
return {k: v[idx] for k, v in dict_.items()}
except:
return {k: tf.convert_to_tensor(v.numpy()[idx], dtype=tf.int32) for k, v in dict_.items()}
def get_dataset(self, index = None, shuffle=False, batch_size=None, repeat=False,
to_x_none=True, limit=False):
if batch_size is None:
batch_size = self.P.batch_size
if index is None:
ds = self.tokenized_dataset
else:
ds = self.idx_slice_dictionary(self.tokenized_dataset, index)
ds = tf.data.Dataset.from_tensor_slices(ds).cache()
ds = ds.repeat() if repeat else ds
ds = ds.shuffle(self.P.shuffle_buffer) if shuffle else ds
ds = ds.map(self._to_x_none) if to_x_none else ds
ds = ds.batch(batch_size) if batch_size > 0 else ds
return ds
@staticmethod
def strip_special_tokens(text):
return text.replace('<pad>', '').replace('</s>', '')
def inference_encode_to_tokens(self, input_text):
encoded_query = self.tokenizer(input_text,
return_tensors='tf', padding=True, pad_to_max_length=True, truncation=True)
return encoded_query
def batch_generate_answer(self, model, examples):
encoded_query = self.process_question_and_context_for_inference([example['question_and_context'] for example in examples])
input_ids = encoded_query["input_ids"]
attention_mask = encoded_query["attention_mask"]
generated_answer = model.generate(input_ids, attention_mask=attention_mask,
max_length=self.P.decoder_max_len, top_p=0.98, top_k=50)
answers = []
for i in range(len(generated_answer.numpy())):
answers.append(self.strip_special_tokens(self.tokenizer.decode(generated_answer.numpy()[i])))
for i, example in enumerate(examples):
examples[i]['generated_answer'] = answers[i]
return examples<file_sep>import tensorflow as tf
class CosineDecayWithWarmUP(tf.keras.experimental.CosineDecay):
def __init__(self, initial_learning_rate, decay_steps, alpha=0.0, warm_up_step=0, name=None):
self.warm_up_step = warm_up_step
super(CosineDecayWithWarmUP, self).__init__(initial_learning_rate=initial_learning_rate,
decay_steps=decay_steps,
alpha=alpha,
name=name)
@tf.function
def __call__(self, step):
if step <= self.warm_up_step:
return step / self.warm_up_step * self.initial_learning_rate
else:
return super(CosineDecayWithWarmUP, self).__call__(step - self.warm_up_step)
<file_sep>import requests
import bs4
def get_reviews(URL):
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'}
web_page = bs4.BeautifulSoup(requests.get(URL, headers=headers).text, "lxml")
text = web_page.find_all('script', {'type' : 'application/ld+json'})[0].text
text = text.replace('&' , '&')
text = text.replace(''', "'")
d = eval(text)
reviews = d['review']
for review in reviews:
review['text'] = review['description']
return reviews
URL = "https://www.yelp.ca/biz/banh-mi-boys-toronto"
print(get_reviews(URL))<file_sep># use mams.py for semval<file_sep>from data_processing.mams import process_mams
from data_processing.token_manager import Token_Manager
| 20830dc61248e39c30774b06aed0055a99c9f02a | [
"Markdown",
"Python",
"Text"
]
| 11 | Python | hyang0129/aspect-sentiment-dashboard | 431727ef02de651e1d4cb0fa2abd9ee12c2277fa | b6f3398d942e9b9297c541cf7934efa5548164d2 |
refs/heads/master | <repo_name>BlaHaws/Thinkful<file_sep>/Mesa/c_agent.py
from mesa import Agent
class CivilianAgent(Agent):
def __init__(self, unique_id, model, agent):
super().__init__(unique_id, model)
self.age = int(agent.ages)
self.gender = int(agent.gender)
self.religion = int(agent.religion)
self.agr_bhv = float(agent.agr_bhv)
self.rel_fnt = float(agent.rel_fnt)
self.rel_conv = float(agent.rel_conv)
self.hst_twd_for = float(agent.hst_twd_for)
self.lvl_rct_act = float(agent.lvl_rct_act)
self.crt_agr_lvl = float(agent.crt_agr_lvl)
self.prob_threat = 0
self.type = 'Civilian'
def step(self):
pass<file_sep>/Mesa/requirements.txt
jupyter
matplotlib
mesa
tensorflow
numpy
pandas
sklearn<file_sep>/Exercises/sundfun.py.py
import scrapy
class CFSSpider(scrapy.Spider):
name = 'sundfun'
start_urls = ['https://www.sundbergolpinmortuary.com/listings']
allowed_domains = ['sundbergolpinmortuary.com']
def parse(self, response):
for url in response.css('span.obitlist-title > a::attr(href)').extract():
yield scrapy.Request(response.urljoin(url), self.parse_listing)
def parse_listing(self, response):
item = {
'Name': response.css('h1.obitnameV3::text').extract_first() or '',
'Date of Birth': response.css('span.dob::text').extract_first() or '',
'Date of Death': response.css('span.dod::text').extract_first() or '',
'Obituary': ' '.join(response.css('div#obtext ::text').extract()).strip().replace('\n', '')
}
yield item<file_sep>/Mesa/t_agent.py
from mesa import Agent
import numpy as np
class TerroristAgent(Agent):
def __init__(self, unique_id, model, agent):
super().__init__(unique_id, model)
self.wounded = False
self.wounded_count = 0
self.age = int(agent.age)
self.gender = int(agent.gender)
self.religion = int(agent.religion)
self.char_list = ['agr_bhv', 'rel_fnt', 'rel_conv', 'hst_twd_for', 'lvl_rct_act', 'crt_agr_lvl']
self.agr_bhv = float(agent.agr_bhv)
self.rel_fnt = float(agent.rel_fnt)
self.rel_conv = float(agent.rel_conv)
self.hst_twd_for = float(agent.hst_twd_for)
self.lvl_rct_act = float(agent.lvl_rct_act)
self.crt_agr_lvl = float(agent.crt_agr_lvl)
self.prob_threat = 0
self.type = 'Terrorist'
self.state = [self.gender, self.religion, self.agr_bhv, self.rel_fnt, self.rel_conv,
self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl, self.model.terror_score,
self.model.civilian_score, 0, 0, self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')]
def step(self):
self.grow()
if not self.wounded:
self.choose_action(self.model.t_hive.choose_action(np.expand_dims(np.array(self.state).reshape((1, 15, 1)), 1)))
else:
if self.wounded_count > 0:
self.wounded_count -= 1
else:
self.wounded = False
self.model.t_hive.learn()
self.model.t_gamma = self.model.t_hive.gamma
def grow(self):
if((self.agr_bhv >= .75) or (self.rel_fnt >= .75) or (self.hst_twd_for >= .75) or (self.crt_agr_lvl >= .65)):
self.crt_agr_lvl += .005
if((self.agr_bhv <= .25) or (self.rel_fnt <= .25) or (self.hst_twd_for <= .25) or (self.crt_agr_lvl <= .25)):
self.crt_agr_lvl -= .005
if((self.agr_bhv >= .75) and ((self.rel_fnt > .75) or (self.hst_twd_for) >= .75)):
self.crt_agr_lvl += .05
if((self.agr_bhv <= .25) and ((self.rel_fnt < .25) or (self.hst_twd_for) <= .25)):
self.crt_agr_lvl +- .05
self.agr_bhv += 0.00001
self.rel_fnt += 0.00001
self.rel_conv += 0.00001
self.hst_twd_for += 0.00001
self.crt_agr_lvl += 0.00001
if np.random.random() <= 0.05:
choice = np.random.choice(self.char_list)
attr_value = getattr(self, choice)
setattr(self, choice, attr_value * np.random.random())
self.prob_threat = float(self.model.pred_model.predict([[self.age, self.gender, self.religion, self.agr_bhv, self.rel_fnt,
self.rel_conv, self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl]]))
def choose_action(self, action):
if action == 0:
state = np.array(self.state).reshape((1, 15 ,1))
t_score = self.model.terror_score
agents = self.model.get_same_square_agents(self.pos[0], self.pos[1])
deaths = np.array([1,2])#,3,4,5,6,7,8,9,10,25])
choice = np.random.choice(deaths)
if len(agents) > choice:
killed_agents = np.random.choice(agents, choice, replace=False)
for agent in killed_agents:
self.model.schedule.remove(agent)
self.model.schedule.remove(self)
self.model.set_terror_score()
self.model.set_civil_score()
t_score_ = self.model.terror_score
state_ = np.array([self.gender, self.religion, 0, 0, 0, 0, 0, 0, self.model.terror_score, self.model.civilian_score,
self.pos[0], self.pos[1], self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1,15,1))
if t_score >= t_score_:
reward = -1
else:
reward = 1
self.model.t_hive.store_transition(state, action, reward, state_)
'''
Remove this agent from the schedule
Remove a random number of agents on this square from the schedule
'''
elif action == 1:
state = np.array(self.state).reshape((1, 15, 1))
t_score = self.model.terror_score
agents = self.model.get_same_square_type_agents(self.pos[0], self.pos[1], 'Civilian')
if len(agents) > 0:
selected_agent = np.random.choice(agents)
if selected_agent.rel_conv <= self.rel_conv:
self.model.add_terrorist(selected_agent, self.pos[0], self.pos[1])
self.model.schedule.remove(selected_agent)
self.model.set_terror_score()
self.model.set_civil_score()
t_score_ = self.model.terror_score
state_ = np.array([self.gender, self.religion, self.agr_bhv, self.rel_fnt, self.rel_conv,
self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl, self.model.terror_score,
self.model.civilian_score, self.pos[0], self.pos[1], self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 15, 1))
if t_score >= t_score_:
reward = -1
else:
reward = 1
self.model.t_hive.store_transition(state, action, reward, state_)
'''
Find a random civilian agent on the same square.
If civilian agent rel_conv < agent rel_conv, civilian agent becomes a terrorist agent
'''
elif action == 2:
reward = 0
state = np.array(self.state).reshape((1, 15, 1))
t_score = self.model.terror_score
mil_neighbors = self.model.get_neighbor_type(self, 'Military')
civ_neighbors = self.model.get_neighbor_type(self, 'Civilian')
if len(mil_neighbors) > 0:
choice = np.random.choice(mil_neighbors)
rand = np.random.random()
if rand >= 0.7:
choice.wounded = True
choice.wounded_count = 3
elif rand <= 0.2 and rand > 0.05:
self.model.schedule.remove(choice)
reward += 1
elif rand <= 0.05:
if len(civ_neighbors) > 0:
choice2 = np.random.choice(civ_neighbors)
self.model.schedule.remove(choice2)
self.model.set_terror_score()
self.model.set_civil_score()
t_score_ = self.model.terror_score
state_ = np.array([self.gender, self.religion, self.agr_bhv, self.rel_fnt, self.rel_conv,
self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl, self.model.terror_score,
self.model.civilian_score, self.pos[0], self.pos[1], self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 15, 1))
if t_score >= t_score_:
reward += -1
else:
reward += 1
self.model.t_hive.store_transition(state, action, reward, state_)
'''
Find a military agent within 1 square of agent.
30% chance to wound, 20% to kill.
5% chance to kill civilian
'''
elif action == 3:
state = np.array(self.state).reshape((1, 15, 1))
t_score = self.model.terror_score
agents = self.model.get_agent_list('Military')
if len(agents) > 0:
nearest = self.model.find_nearest_agent(self, agents)
x, y = self.model.move_toward_nearest(self, nearest)
self.model.grid.move_agent(self, (self.pos[0]+x, self.pos[1]+y))
self.model.set_terror_score()
self.model.set_civil_score()
t_score_ = self.model.terror_score
state_ = np.array([self.gender, self.religion, self.agr_bhv, self.rel_fnt, self.rel_conv,
self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl, self.model.terror_score,
self.model.civilian_score, self.pos[0], self.pos[1], self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 15, 1))
if t_score >= t_score_:
reward = -1
else:
reward = 1
self.model.t_hive.store_transition(state, action, reward, state_)
'''
Find the nearest military agent and move toward.
'''
elif action == 4:
state = np.array(self.state).reshape((1, 15, 1))
t_score = self.model.terror_score
self.model.set_terror_score()
self.model.set_civil_score()
t_score_ = self.model.terror_score
state_ = np.array([self.gender, self.religion, self.agr_bhv, self.rel_fnt, self.rel_conv,
self.hst_twd_for, self.lvl_rct_act, self.crt_agr_lvl, self.model.terror_score,
self.model.civilian_score, self.pos[0], self.pos[1], self.model.get_agent_count('Terrorist'),
self.model.get_agent_count('Civilian'), self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 15, 1))
if t_score >= t_score_:
reward = -1
else:
reward = 1
self.model.t_hive.store_transition(state, action, reward, state_)<file_sep>/Mesa/server.py
from mesa.visualization.ModularVisualization import ModularServer
from mesa.visualization.modules import CanvasGrid, ChartModule, TextElement
from mesa.visualization.UserParam import UserSettableParameter
from model import MapModel
class CCountElement(TextElement):
def __init__(self):
pass
def render(self, model):
return "# of Civilians: " + str(model.get_agent_count('Civilian')) + " Civil Score: " + str(model.civilian_score)
class TCountElement(TextElement):
def __init__(self):
pass
def render(self, model):
return "# of Terrorists: " + str(model.get_agent_count('Terrorist')) + " Terror Score: " + str(model.terror_score)
class MCountElement(TextElement):
def __init__(self):
pass
def render(self, model):
return "# of Troops: " + str(model.get_agent_count('Military'))
def get_model_params():
height = None
width = None
map_size = UserSettableParameter("choice", "Map size", value="Large", choices=["Small", "Medium", "Large"])
if map_size.value == "Large":
height = 50
width = 50
elif map_size.value == "Medium":
height = 25
width = 25
elif map_size.value == "Small":
height = 10
width = 10
density = UserSettableParameter("slider", "Terrorist density", 0.25, 0.00, 1.00, 0.25)
troop_size = UserSettableParameter("number", "Troop size", 10000)
model_params = {"height": height, "width": width, "density": density, "map_size": map_size, "troop_size": troop_size}
return model_params
def mapmodel_draw(agent):
if agent is None:
return
portrayal = {"Shape": "circle", "r": 0.8, "Filled": "true", "Layer": 0}
if agent.type == "Terrorist":
portrayal["Color"] = ["#FF0000"]
portrayal["stroke_color"] = "#000000"
elif agent.type == "Civilian":
portrayal["Color"] = ["#00ff00"]
portrayal["stroke_color"] = "#000000"
elif agent.type == "Military":
portrayal["Color"] = ["#0000FF"]
portrayal["stroke_color"] = "#000000"
return portrayal
model_params = get_model_params()
c_count_element = CCountElement()
t_count_element = TCountElement()
m_count_element = MCountElement()
canvas_element = CanvasGrid(mapmodel_draw, model_params["height"], model_params["width"], 500, 500)
ter_gamma_chart = ChartModule([{"Label": "Terrorist Epsilon", "Color": "Red"}, {"Label": "Military Epsilon", "Color": "Blue"}])
server = ModularServer(MapModel,
[canvas_element, c_count_element, t_count_element, m_count_element, ter_gamma_chart],
"Terrorist Response", model_params)
server.launch()<file_sep>/Mesa/hivemind_ter.py
from dqn_tf import DeepQNetwork
import tensorflow as tf
import os
import numpy as np
class HiveMindTer(object):
def __init__(self, alpha, gamma, mem_size, n_actions, epsilon,
batch_size, replace_target=5000, input_dims=(1, 15, 1),
q_next_dir='tmp/ter/q_next', q_eval_dir='tmp/ter/q_eval'):
self.n_actions = n_actions
self.action_space = [ i for i in range(self.n_actions)]
self.gamma = gamma
self.mem_size = mem_size
self.epsilon = epsilon
self.batch_size = batch_size
self.mem_cntr = 0
self. replace_target = replace_target
self.q_next = DeepQNetwork(alpha, n_actions, input_dims=input_dims,
name='ter_q_next', chkpt_dir=q_next_dir)
self.q_eval = DeepQNetwork(alpha, n_actions, input_dims=input_dims,
name='ter_q_eval', chkpt_dir=q_eval_dir)
self.state_memory = np.zeros((self.mem_size, *input_dims))
self.new_state_memory = np.zeros((self.mem_size, *input_dims))
self.action_memory = np.zeros((self.mem_size, self.n_actions), dtype=np.int8)
self.reward_memory = np.zeros(self.mem_size)
def store_transition(self, state, action, reward, state_):
index = self.mem_cntr % self.mem_size
self.state_memory[index] = state
actions = np.zeros(self.n_actions)
actions[action] = 1.0
self.action_memory[index] = actions
self.reward_memory[index] = reward
self.new_state_memory[index] = state_
self.mem_cntr += 1
def choose_action(self, state):
rand = np.random.random()
if rand < self.epsilon:
action = np.random.choice(self.action_space)
else:
actions = self.q_eval.sess.run(self.q_eval.Q_values,
feed_dict={self.q_eval.input: state})
action = np.argmax(actions)
return action
def learn(self):
if self.mem_cntr % self.replace_target == 0:
self.update_graph()
max_mem = self.mem_cntr if self.mem_cntr < self.mem_size else self.mem_size
batch = np.random.choice(max_mem, self.batch_size)
state_batch = self.state_memory[batch]
action_batch = self.action_memory[batch]
action_values = np.array([0, 1, 2, 3, 4], dtype=np.int8)
action_indices = np.dot(action_batch, action_values)
reward_batch = self.reward_memory[batch]
new_state_batch = self.new_state_memory[batch]
q_eval = self.q_eval.sess.run(self.q_eval.Q_values,
feed_dict={self.q_eval.input: state_batch})
q_next = self.q_next.sess.run(self.q_next.Q_values,
feed_dict={self.q_next.input: new_state_batch})
q_target = q_eval.copy()
q_target[:, action_indices] = reward_batch + \
self.gamma*np.max(q_next, axis=1)
_ = self.q_eval.sess.run(self.q_eval.train_op,
feed_dict={self.q_eval.input: state_batch,
self.q_eval.actions: action_batch,
self.q_eval.q_target: q_target})
if self.mem_cntr > 10000:
if self.epsilon > 0.05:
self.epsilon -= 4e-7
elif self.epsilon <= 0.05:
self.epsilon = 0.05
def save_models(self):
self.q_eval.save_checkpoint()
self.q_next.save_checkpoint()
def load_models(self):
self.q_eval.load_checkpoint()
self.q_next.load_checkpoint()
def update_graph(self):
t_params = self.q_next.params
e_params = self.q_eval.params
for t, e, in zip (t_params, e_params):
self.q_eval.sess.run(tf.assign(t,e))
<file_sep>/Mesa/m_agent.py
from mesa import Agent
import numpy as np
class MilitaryAgent(Agent):
def __init__(self, unique_id, model, agent):
super().__init__(unique_id, model)
self.wounded = False
self.wounded_count = 0
self.state = [self.model.terror_score, self.model.civilian_score, 0, 0,
self.model.get_agent_count('Terrorist'), self.model.get_agent_count('Civilian'),
self.model.get_agent_count('Military')]
self.type = "Military"
def step(self):
if not self.wounded:
self.choose_action(self.model.m_hive.choose_action(np.expand_dims(np.array(self.state).reshape((1, 7, 1)), 1)))
else:
if self.wounded_count > 0:
self.wounded_count -= 1
else:
self.wounded = False
self.model.m_hive.learn()
self.model.m_gamma = self.model.m_hive.gamma
def choose_action(self, action):
self.action = action
if self.action == 0:
state = np.array(self.state).reshape((1, 7, 1))
c_score = self.model.civilian_score
agents = self.model.get_agent_list('Terrorist')
if len(agents) > 0:
nearest = self.model.find_nearest_agent(self, agents)
x, y = self.model.move_toward_nearest(self, nearest)
self.model.grid.move_agent(self, (self.pos[0]+x, self.pos[1]+y))
self.model.set_terror_score()
self.model.set_civil_score()
c_score_ = self.model.civilian_score
state_ = np.array([self.model.terror_score, self.model.civilian_score, self.pos[0], self.pos[1],
self.model.get_agent_count('Terrorist'), self.model.get_agent_count('Civilian'),
self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 7, 1))
if c_score >= c_score_:
reward = -1
else:
reward = 1
self.model.m_hive.store_transition(state, action, reward, state_)
'''
Agent find nearest terrorist agent and moves toward.
'''
elif self.action == 1:
state = np.array(self.state).reshape((1, 7, 1))
c_score = self.model.civilian_score
reward = 0
agents = self.model.get_same_square_type_agents(self.pos[0], self.pos[1], 'Terrorist')
if len(agents) > 0:
selected_agent = np.random.choice(agents)
rand = np.random.random()
if rand <= 0.4:
self.model.schedule.remove(selected_agent)
reward += 2
self.model.set_terror_score()
self.model.set_civil_score()
c_score_ = self.model.civilian_score
state_ = np.array([self.model.terror_score, self.model.civilian_score, self.pos[0], self.pos[1],
self.model.get_agent_count('Terrorist'), self.model.get_agent_count('Civilian'),
self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 7, 1))
if c_score >= c_score_:
reward = -1
else:
reward = 1
self.model.m_hive.store_transition(state, action, reward, state_)
'''
Agent randomly chooses a terrorist agent within the same square
40% success rate, reward is 2-3x larger
'''
elif self.action == 2:
reward = 0
state = np.array(self.state).reshape((1, 7, 1))
c_score = self.model.civilian_score
ter_neighbors = self.model.get_neighbor_type(self, 'Terrorist')
civ_neighbors = self.model.get_neighbor_type(self, 'Civilian')
if len(ter_neighbors) > 0:
choice = np.random.choice(ter_neighbors)
rand = np.random.random()
if rand >= 0.6:
choice.wounded = True
choice.wounded_count = 3
elif rand <= 0.4 and rand > 0.05:
self.model.schedule.remove(choice)
elif rand <= 0.05:
if len(civ_neighbors) > 0:
choice2 = np.random.choice(civ_neighbors)
self.model.schedule.remove(choice2)
reward -= 1
self.model.set_terror_score()
self.model.set_civil_score()
c_score_ = self.model.civilian_score
state_ = np.array([self.model.terror_score, self.model.civilian_score, self.pos[0], self.pos[1],
self.model.get_agent_count('Terrorist'), self.model.get_agent_count('Civilian'),
self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 7, 1))
if c_score >= c_score_:
reward += -1
else:
reward += 1
self.model.m_hive.store_transition(state, action, reward, state_)
'''
Agent randomly selects a terrorist agent within 1 square and attacks.
60% to wound, 40% to kill.
5% to kill civilian agent
'''
elif self.action == 3:
state = np.array(self.state).reshape((1, 7, 1))
c_score = self.model.civilian_score
self.model.set_terror_score()
self.model.set_civil_score()
c_score_ = self.model.civilian_score
state_ = np.array([self.model.terror_score, self.model.civilian_score, self.pos[0], self.pos[1],
self.model.get_agent_count('Terrorist'), self.model.get_agent_count('Civilian'),
self.model.get_agent_count('Military')])
self.state = state_
state_ = state_.reshape((1, 7, 1))
if c_score >= c_score_:
reward = -1
else:
reward = 1
self.model.m_hive.store_transition(state, action, reward, state_)<file_sep>/Mesa/gen_agents.py
import pandas as pd
import numpy as np
from scipy.stats import truncnorm
class GenAgents(object):
def get_truncated_normal(self, mean=0, sd=1, low=0, upp=10):
return truncnorm((low - mean) / sd, (upp - mean) / sd, loc=mean, scale=sd)
def generate_ter_agents(self, agent_size):
agents = pd.DataFrame()
ages = np.round(np.random.normal(36, 5, agent_size), 0)
males = np.zeros((int(agent_size * .9),), dtype=int)
females = np.ones((int(agent_size - len(males)),), dtype=int)
genders = np.concatenate((males, females), axis=None)
reli = np.zeros((int(agent_size * .8),), dtype=int)
relo = np.ones((int(agent_size - len(reli)),), dtype=int)
religions = np.concatenate((reli, relo), axis=None)
np.random.shuffle(genders)
np.random.shuffle(religions)
X1 = self.get_truncated_normal(mean=.25, sd=.25, low=0, upp=1)
X2 = self.get_truncated_normal(mean=.5, sd=.15, low=0, upp=1)
X3 = self.get_truncated_normal(mean=.35, sd=.3, low=0, upp=1)
X4 = self.get_truncated_normal(mean=.2, sd=.35, low=0, upp=1)
X5 = self.get_truncated_normal(mean=.5, sd=.4, low=0, upp=1)
X6 = self.get_truncated_normal(mean=.15, sd=.4, low=0, upp=1)
agr_bhv = X1.rvs(int(agent_size))
rel_fnt = X2.rvs(int(agent_size))
rel_conv = X6.rvs(int(agent_size))
hst_twd_for = X3.rvs(int(agent_size))
lvl_rct_act = X4.rvs(int(agent_size))
crt_agr_lvl = X5.rvs(int(agent_size))
prob_threat = np.zeros((int(agent_size),), dtype=float)
agents['age'] = ages.astype(int)
agents['gender'] = genders
agents['religion'] = religions
agents['agr_bhv'] = agr_bhv
agents['rel_fnt'] = rel_fnt
agents['rel_conv'] = rel_conv
agents['hst_twd_for'] = hst_twd_for
agents['lvl_rct_act'] = lvl_rct_act
agents['crt_agr_lvl'] = crt_agr_lvl
agents['prob_threat'] = prob_threat
return agents
def generate_pred_agents(self, agent_size):
agents = pd.DataFrame()
ages = np.round(np.random.normal(36, 5, agent_size), 0)
males = np.zeros((int(agent_size * .9),), dtype=int)
females = np.ones((int(agent_size * .1),), dtype=int)
genders = np.concatenate((males, females), axis=None)
reli = np.zeros((int(agent_size * .8),), dtype=int)
relo = np.ones((int(agent_size * .2),), dtype=int)
religions = np.concatenate((reli, relo), axis=None)
np.random.shuffle(genders)
np.random.shuffle(religions)
X1 = self.get_truncated_normal(mean=.25, sd=.25, low=0, upp=1)
X2 = self.get_truncated_normal(mean=.5, sd=.15, low=0, upp=1)
X3 = self.get_truncated_normal(mean=.35, sd=.3, low=0, upp=1)
X4 = self.get_truncated_normal(mean=.2, sd=.35, low=0, upp=1)
X5 = self.get_truncated_normal(mean=.5, sd=.4, low=0, upp=1)
X6 = self.get_truncated_normal(mean=.15, sd=.4, low=0, upp=1)
agr_bhv = X1.rvs(int(agent_size))
rel_fnt = X2.rvs(int(agent_size))
rel_conv = X6.rvs(int(agent_size))
hst_twd_for = X3.rvs(int(agent_size))
lvl_rct_act = X4.rvs(int(agent_size))
crt_agr_lvl = X5.rvs(int(agent_size))
prob_threat = X2.rvs(int(agent_size))
agents['age'] = ages.astype(int)
agents['gender'] = genders
agents['religion'] = religions
agents['agr_bhv'] = agr_bhv
agents['rel_fnt'] = rel_fnt
agents['rel_conv'] = rel_conv
agents['hst_twd_for'] = hst_twd_for
agents['lvl_rct_act'] = lvl_rct_act
agents['crt_agr_lvl'] = crt_agr_lvl
agents['prob_threat'] = prob_threat
return agents
def generate_mil_agents(self, agent_size):
agents = pd.DataFrame()
agents['thing'] = np.zeros((int(agent_size),), dtype=int)
return agents
def generate_civ_agents(self, agent_size):
agents = pd.DataFrame()
ages = np.round(np.random.normal(36, 5, agent_size), 0)
males = np.zeros((int(agent_size * .9),), dtype=int)
females = np.ones((int(agent_size - len(males)),), dtype=int)
genders = np.concatenate((males, females), axis=None)
reli = np.zeros((int(agent_size * .8),), dtype=int)
relo = np.ones((int(agent_size - len(reli)),), dtype=int)
religions = np.concatenate((reli, relo), axis=None)
np.random.shuffle(genders)
np.random.shuffle(religions)
X1 = self.get_truncated_normal(mean=.25, sd=.3, low=0, upp=1)
X2 = self.get_truncated_normal(mean=.8, sd=.3, low=0, upp=1)
agr_bhv = X1.rvs(int(agent_size))
rel_fnt = X1.rvs(int(agent_size))
rel_conv = X2.rvs(int(agent_size))
hst_twd_for = X1.rvs(int(agent_size))
lvl_rct_act = X1.rvs(int(agent_size))
crt_agr_lvl = X1.rvs(int(agent_size))
prob_threat = np.zeros((int(agent_size),), dtype=float)
agents['ages'] = ages.astype(int)
agents['gender'] = genders
agents['religion'] = religions
agents['agr_bhv'] = agr_bhv
agents['rel_fnt'] = rel_fnt
agents['rel_conv'] = rel_conv
agents['hst_twd_for'] = hst_twd_for
agents['lvl_rct_act'] = lvl_rct_act
agents['crt_agr_lvl'] = crt_agr_lvl
agents['prob_threat'] = prob_threat
return agents<file_sep>/Mesa/model.py
import pandas as pd
import numpy as np
import warnings
from mesa import Model
from mesa.time import RandomActivation
from sklearn import ensemble
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
from scipy.stats import truncnorm
from t_agent import TerroristAgent
from c_agent import CivilianAgent
from m_agent import MilitaryAgent
from dqn_tf import DeepQNetwork
from hivemind_ter import HiveMindTer
from hivemind_mil import HiveMindMil
from gen_agents import GenAgents
warnings.filterwarnings("ignore", category=FutureWarning)
class MapModel(Model):
def __init__(self, density=.1, height=50, width=50, map_size="Large", troop_size=10000,
t_hive=HiveMindTer(gamma=0.99, epsilon=1.0, alpha=0.00025, input_dims=(1, 15, 1),
n_actions=5, mem_size=4000, batch_size=1),
m_hive=HiveMindMil(gamma=0.99, epsilon=1.0, alpha=0.00025, input_dims=(1, 7, 1),
n_actions=4, mem_size=4000, batch_size=1)):
self.height = height
self.width = width
self.density = density
self.map_size = map_size
self.gen_agents = GenAgents()
self.load_checkpoints = True
self.schedule = RandomActivation(self)
self.grid = MultiGrid(height, width, False)
self.terror_score = 0
self.civilian_score = 0
self.pred_agents = self.gen_agents.generate_pred_agents(10000)
self.pred_model = self.train_model(self.pred_agents)
self.t_hive = t_hive
self.m_hive = m_hive
self.datacollector = DataCollector({"Terrorist Epsilon": "t_epsilon", "Military Epsilon": "m_epsilon"})
if self.load_checkpoints:
self.t_hive.load_models()
self.m_hive.load_models()
self.t_epsilon = self.t_hive.epsilon
self.m_epsilon = self.m_hive.epsilon
self.metro_size = 10000
self.metro_civ = int(self.metro_size * (1 - self.density))
self.metro_ter = int(self.metro_size * self.density)
self.city_size = 1000
self.city_civ = int(self.city_size * (1 - self.density))
self.city_ter = int(self.city_size * self.density)
self.village = 50
self.village_civ = int(self.village * (1 - self.density))
self.village_ter = int(self.village * self.density)
self.troop_size = troop_size
if self.map_size == "Large":
self.basecamp = int(self.troop_size * .8)
self.outpost = int(self.troop_size * .2)
self.metro_loc = {"X": 25, "Y": 25}
self.city1_loc = {"X": 20, "Y": 20}
self.city2_loc = {"X": 45, "Y": 25}
self.village1_loc = {"X": 10, "Y": 45}
self.village2_loc = {"X": 15, "Y": 30}
self.village3_loc = {"X": 45, "Y": 45}
self.basecamp_loc = {"X": 35, "Y": 10}
self.outpost_loc = {"X": 30, "Y": 20}
self.metro_t_agents = self.gen_agents.generate_ter_agents(self.metro_ter)
self.metro_c_agents = self.gen_agents.generate_civ_agents(self.metro_civ)
self.city1_t_agents = self.gen_agents.generate_ter_agents(self.city_ter)
self.city1_c_agents = self.gen_agents.generate_civ_agents(self.city_civ)
self.city2_t_agents = self.gen_agents.generate_ter_agents(self.city_ter)
self.city2_c_agents = self.gen_agents.generate_civ_agents(self.city_civ)
self.village1_t_agents = self.gen_agents.generate_ter_agents(self.village_ter)
self.village1_c_agents = self.gen_agents.generate_civ_agents(self.village_civ)
self.village2_t_agents = self.gen_agents.generate_ter_agents(self.village_ter)
self.village2_c_agents = self.gen_agents.generate_civ_agents(self.village_civ)
self.village3_t_agents = self.gen_agents.generate_ter_agents(self.village_ter)
self.village3_c_agents = self.gen_agents.generate_civ_agents(self.village_civ)
self.basecamp_agents = self.gen_agents.generate_mil_agents(self.basecamp)
self.outpost_agents = self.gen_agents.generate_mil_agents(self.outpost)
for x in range(len(self.metro_t_agents)):
a = TerroristAgent('tm'+str(x), self, self.metro_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.metro_c_agents)):
a = CivilianAgent('cm'+str(x), self, self.metro_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.city1_t_agents)):
a = TerroristAgent('tc1'+str(x), self, self.city1_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city1_loc["X"], self.city1_loc["Y"]))
for x in range(len(self.city1_c_agents)):
a = CivilianAgent('cc1'+str(x), self, self.city1_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city1_loc["X"], self.city1_loc["Y"]))
for x in range(len(self.city2_t_agents)):
a = TerroristAgent('tc2'+str(x), self, self.city2_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city2_loc["X"], self.city2_loc["Y"]))
for x in range(len(self.city2_c_agents)):
a = CivilianAgent('cc2'+str(x), self, self.city2_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city2_loc["X"], self.city2_loc["Y"]))
for x in range(len(self.village1_t_agents)):
a = TerroristAgent('tv1'+str(x), self, self.village1_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village1_loc["X"], self.village1_loc["Y"]))
for x in range(len(self.village1_c_agents)):
a = CivilianAgent('cv1'+str(x), self, self.village1_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village1_loc["X"], self.village1_loc["Y"]))
for x in range(len(self.village2_t_agents)):
a = TerroristAgent('tv2'+str(x), self, self.village2_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village2_loc["X"], self.village2_loc["Y"]))
for x in range(len(self.village2_c_agents)):
a = CivilianAgent('cv2'+str(x), self, self.village2_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village2_loc["X"], self.village2_loc["Y"]))
for x in range(len(self.village3_t_agents)):
a = TerroristAgent('tv3'+str(x), self, self.village3_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village3_loc["X"], self.village3_loc["Y"]))
for x in range(len(self.village3_c_agents)):
a = CivilianAgent('cv3'+str(x), self, self.village3_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.village3_loc["X"], self.village3_loc["Y"]))
for x in range(len(self.basecamp_agents)):
a = MilitaryAgent('mb'+str(x), self, self.basecamp_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.basecamp_loc["X"], self.basecamp_loc["Y"]))
for x in range(len(self.outpost_agents)):
a = MilitaryAgent('mo'+str(x), self, self.outpost_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.outpost_loc["X"], self.outpost_loc["Y"]))
del self.metro_c_agents
del self.metro_t_agents
del self.city1_c_agents
del self.city1_t_agents
del self.city2_c_agents
del self.city2_t_agents
del self.village1_c_agents
del self.village1_t_agents
del self.village2_c_agents
del self.village2_t_agents
del self.village3_c_agents
del self.village3_t_agents
del self.basecamp
del self.outpost
del self.basecamp_agents
del self.outpost_agents
elif self.map_size == "Medium":
self.basecamp = self.troop_size
self.metro_loc = {"X": 25, "Y": 25}
self.city1_loc = {"X": 20, "Y": 20}
self.city2_loc = {"X": 45, "Y": 25}
self.basecamp_loc = {"X": 30, "Y": 20}
self.metro_t_agents = self.gen_agents.generate_ter_agents(self.metro_ter)
self.metro_c_agents = self.gen_agents.generate_civ_agents(self.metro_civ)
self.city1_t_agents = self.gen_agents.generate_ter_agents(self.city_ter)
self.city1_c_agents = self.gen_agents.generate_civ_agents(self.city_civ)
self.city2_t_agents = self.gen_agents.generate_ter_agents(self.city_ter)
self.city2_c_agents = self.gen_agents.generate_civ_agents(self.city_civ)
self.basecamp_agents = self.gen_agents.generate_mil_agents(self.troop_size)
for x in range(len(self.metro_t_agents)):
a = TerroristAgent('tm'+str(x), self, self.metro_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.metro_c_agents)):
a = CivilianAgent('cm'+str(x), self, self.metro_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.city1_t_agents)):
a = TerroristAgent('tc1'+str(x), self, self.city1_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city1_loc["X"], self.city1_loc["Y"]))
for x in range(len(self.city1_c_agents)):
a = CivilianAgent('cc1'+str(x), self, self.city1_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city1_loc["X"], self.city1_loc["Y"]))
for x in range(len(self.city2_t_agents)):
a = TerroristAgent('tc2'+str(x), self, self.city2_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city2_loc["X"], self.city2_loc["Y"]))
for x in range(len(self.city2_c_agents)):
a = CivilianAgent('cc2'+str(x), self, self.city2_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.city2_loc["X"], self.city2_loc["Y"]))
for x in range(len(self.basecamp_agents)):
a = MilitaryAgent('mb'+str(x), self, self.basecamp_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.basecamp_loc["X"], self.basecamp_loc["Y"]))
del self.metro_c_agents
del self.metro_t_agents
del self.city1_c_agents
del self.city1_t_agents
del self.city2_c_agents
del self.city2_t_agents
del self.basecamp
del self.basecamp_agents
elif self.map_size == "Small":
self.basecamp = self.troop_size
self.metro_loc = {"X": 25, "Y": 25}
self.basecamp_loc = {"X": 30, "Y": 20}
self.metro_t_agents = self.gen_agents.generate_ter_agents(self.metro_ter)
self.metro_c_agents = self.gen_agents.generate_civ_agents(self.metro_civ)
self.basecamp_agents = self.gen_agents.generate_mil_agents(self.troop_size)
for x in range(len(self.metro_t_agents)):
a = TerroristAgent('tm'+str(x), self, self.metro_t_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.metro_c_agents)):
a = CivilianAgent('cm'+str(x), self, self.metro_c_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.metro_loc["X"], self.metro_loc["Y"]))
for x in range(len(self.basecamp_agents)):
a = MilitaryAgent('mb'+str(x), self, self.basecamp_agents[x:x+1])
self.schedule.add(a)
self.grid.place_agent(a, (self.basecamp_loc["X"], self.basecamp_loc["Y"]))
del self.metro_c_agents
del self.metro_t_agents
del self.basecamp
del self.basecamp_agents
del self.pred_agents
del self.metro_size
del self.metro_civ
del self.metro_ter
del self.city_civ
del self.city_ter
del self.village_civ
del self.village_ter
self.set_terror_score()
self.set_civil_score()
self.running = True
def step(self):
if self.get_agent_count('Terrorist') >= 1:
self.schedule.step()
self.t_epsilon = self.t_hive.epsilon
self.m_epsilon = self.m_hive.epsilon
self.datacollector.collect(self)
if self.schedule.steps % 5 == 0:
self.t_hive.save_models()
self.m_hive.save_models()
else:
self.running = False
def get_agent_count(self, type):
count = 0
for agent in self.schedule.agents:
if agent.type == type:
count += 1
return count
def get_agent_list(self, type):
agents = []
for agent in self.schedule.agents:
if agent.type == type:
agents.append(agent)
return agents
def set_terror_score(self):
t_count = self.get_agent_count('Terrorist')
c_count = self.get_agent_count('Civilian')
m_count = self.get_agent_count('Military')
if t_count >= c_count:
self.terror_score = t_count - (c_count/2) - m_count
else:
self.terror_score = t_count - c_count - m_count
def set_civil_score(self):
t_count = self.get_agent_count('Terrorist')
c_count = self.get_agent_count('Civilian')
m_count = self.get_agent_count('Military')
self.civilian_score = c_count + (m_count / 2) - t_count
def get_same_square_agents(self, x_pos, y_pos):
agents = []
for agent in self.schedule.agents:
if agent.pos[0] == x_pos and agent.pos[1] == y_pos:
agents.append(agent)
return agents
def get_same_square_type_agents(self, x_pos, y_pos, type):
agents = []
for agent in self.schedule.agents:
if agent.pos[0] == x_pos and agent.pos[1] == y_pos and agent.type == type:
agents.append(agent)
return agents
def get_neighbor_type(self, agent, type):
agents = self.grid.neighbor_iter((agent.pos[0], agent.pos[1]), moore=True)
refined = []
for agent in agents:
if agent.type == type:
refined.append(agent)
return refined
def find_nearest_agent(self, agent1, agents):
dists = []
x_pos = agent1.pos[0]
y_pos = agent1.pos[1]
for agent in agents:
x = agent.pos[0]
x2 = (x - x_pos) ** 2
y = agent.pos[1]
y2 = (y - y_pos) ** 2
dist = np.sqrt(x2 + y2)
dists.append(dist)
min_index = dists.index(min(dists))
return agents[min_index]
def move_toward_nearest(self, agent1, agent2):
x = (agent1.pos[0] - agent2.pos[0]) // -2
y = (agent1.pos[1] - agent2.pos[1]) // -2
if x > 0:
x = 1
elif x == 0:
x = 0
elif x < 0:
x = -1
if y > 0:
y = 1
elif y == 0:
y = 0
elif y < 0:
y = -1
return x, y
def add_terrorist(self, agent, x_pos, y_pos):
a = TerroristAgent('t'+agent.unique_id, self, agent)
self.schedule.add(a)
self.grid.place_agent(a, (x_pos, y_pos))
def train_model(self, agents):
rfg = ensemble.RandomForestRegressor()
X = agents.drop(['prob_threat'], 1)
Y = agents.prob_threat
rfg.fit(X, Y)
return rfg | 45c675c1c249ac8a2d52c9b1dc128c28ea27ad5d | [
"Python",
"Text"
]
| 9 | Python | BlaHaws/Thinkful | d198af722e4145bb93bd6cb3761e3c1dbd2f8409 | 7bd3feb2ad956e1b615c3d9c61a604cff736e7f8 |
refs/heads/master | <repo_name>js-30/PC-Verwaltung-Volz-<file_sep>/PC_Verwaltung_mit_DB - Start/PC_Verwaltung_Ver1/DbAdapterPCVerwaltung.cs
using System.Collections.Generic;
using System.Globalization;
using MySql.Data.MySqlClient;
namespace PC_Verwaltung_Ver4
{
public class DbAdapterPCVerwaltung
{
/*SQL Querys aus MySql Workbench bekommen:
* 1. Neues Sql Query öffnen
* 2. Rechtsklick auf Tabelle
* 3. "Sent to Sql Editor"
* 4. Copy paste :P
*/
//Select
public List<PC> getAllPcs()
{
//1. Liste wird initialisiert und am ende zurückgegeben
List<PC> allePcs = new List<PC>();
//2. SQL Query und Command initialisieren
string query = @"SELECT id, hdd, takt, ram FROM tblPCs; ";
MySqlCommand sqlcommand = new MySqlCommand(query);
//3. Connection mit Connectionstring initialisieren
MySQLConnector mysqlConnector = new MySQLConnector();
MySqlConnection connection = new MySqlConnection(mysqlConnector.ConnectionString);
//4. Connection Eigenschaft des MySqlCommands setzen
sqlcommand.Connection = connection;
//5. Connection öffnen und schließen
connection.Open();
//6. DataReader initialisieren
MySqlDataReader dataReader = sqlcommand.ExecuteReader();
//7. Daten auslesen
while (dataReader.Read())
{
//8. Objekt initialisieren
PC neuerPC = new PC();
//9. Eigenschaften setzen
neuerPC.ID = dataReader.GetInt32("id");
neuerPC.HDD = dataReader.GetDouble("hdd");
neuerPC.RAM = dataReader.GetDouble("ram");
neuerPC.Prozessorgeschwindigkeit = dataReader.GetDouble("takt");
//10. Zur Liste hinzufügen
allePcs.Add(neuerPC);
}
//5. siehe oben
connection.Close();
//1. siehe oben
return allePcs;
}
//Insert
public void insertPc(PC neuerPc)
{
//1. Sql Query und Command initialisieren
string query = $"INSERT INTO tblpcs(hdd, takt, ram)VALUES({neuerPc.HDD.ToString(CultureInfo.InvariantCulture)},{neuerPc.Prozessorgeschwindigkeit.ToString(CultureInfo.InvariantCulture)},{neuerPc.RAM.ToString(CultureInfo.InvariantCulture)});";
MySqlCommand sqlcommand = new MySqlCommand(query);
//3. Connection mit Connectionstring initialisieren
MySQLConnector mysqlConnector = new MySQLConnector();
MySqlConnection connection = new MySqlConnection(mysqlConnector.ConnectionString);
//4. Connection Eigenschaft des MySqlCommands setzen
sqlcommand.Connection = connection;
//5. Connection öffnen und schließen
connection.Open();
//6. Query ausführen
sqlcommand.ExecuteNonQuery();
//5. Siehe oben
connection.Close();
}
//Delete
public void deletePc(int id)
{
//1. Sql Query und Command initialisieren
string query = $"DELETE FROM `pcverwaltung`.`tblpcs` WHERE id={id};";
MySqlCommand sqlcommand = new MySqlCommand(query);
//3. Connection mit Connectionstring initialisieren
MySQLConnector mysqlConnector = new MySQLConnector();
MySqlConnection connection = new MySqlConnection(mysqlConnector.ConnectionString);
//4. Connection Eigenschaft des MySqlCommands setzen
sqlcommand.Connection = connection;
//5. Connection öffnen und schließen
connection.Open();
//6. Query ausführen
sqlcommand.ExecuteNonQuery();
//5. Siehe oben
connection.Close();
}
//Update
public void updatePc(PC neuerPc)
{
//1. Sql Query und Command initialisieren
string query = $"UPDATE `pcverwaltung`.`tblpcs` SET `hdd`={neuerPc.HDD.ToString(CultureInfo.InvariantCulture)},`takt`={neuerPc.Prozessorgeschwindigkeit.ToString(CultureInfo.InvariantCulture)},`ram`={neuerPc.RAM.ToString(CultureInfo.InvariantCulture)} WHERE `id`={neuerPc.ID}; ";
MySqlCommand sqlcommand = new MySqlCommand(query);
//3. Connection mit Connectionstring initialisieren
MySQLConnector mysqlConnector = new MySQLConnector();
MySqlConnection connection = new MySqlConnection(mysqlConnector.ConnectionString);
//4. Connection Eigenschaft des MySqlCommands setzen
sqlcommand.Connection = connection;
//5. Connection öffnen und schließen
connection.Open();
//6. Query ausführen
sqlcommand.ExecuteNonQuery();
//5. Siehe oben
connection.Close();
}
}
}
<file_sep>/3. pcVerwaltung.sql
DROP DATABASE IF EXISTS pcVerwaltung;
CREATE DATABASE pcVerwaltung;
USE pcVerwaltung;
CREATE TABLE tblPCs(
id int AUTO_INCREMENT PRIMARY KEY,
hdd double,
takt double,
ram double
)engine=innodb;
INSERT INTO tblPCs(hdd, takt, ram)
VALUES
(500, 2.4, 4),
(600, 1.4, 6),
(700, 1.5, 8),
(800, 3.4, 2),
(900, 3.1, 4),
(1000, 1.6, 6),
(200, 2.4, 8),
(300, 1.4, 4),
(400, 1.8, 2),
(500, 4.0, 4),
(600, 3.2, 6),
(700, 1.4, 8),
(800, 3.6, 2),
(900, 3.4, 4),
(1000, 1.4, 6),
(1500, 2.8, 8);
<file_sep>/PC_Verwaltung_mit_DB - Start/PC_Verwaltung_Ver1/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace PC_Verwaltung_Ver4
{
public partial class Form1 : Form
{
// gibt den aktuellen Datensatz an, der angezeigt werden soll
// wenn kein Datensatz vorhanden ist, zeigt er 0 an, für den ersten
// anzulegenden Datensatz.
private int aktuellerDatensatz =0;
// Liste (Container) für alle PCs
private List<PC> allePC = new List<PC>();
public Form1()
{
InitializeComponent();
initPCListe();
aktualisiereOberflaeche();
}
private void initPCListe()
{
DbAdapterPCVerwaltung adapter = new DbAdapterPCVerwaltung();
allePC = adapter.getAllPcs();
}
private void beendenToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void überPCVerwaltungToolStripMenuItem_Click(object sender, EventArgs e)
{
String msg="PC Verwaltung 4.0"+Environment.NewLine+Environment.NewLine+
"(C) ErVo-Software 2013";
MessageBox.Show(msg);
}
private void btnUebernehmen_Click(object sender, EventArgs e)
{
try
{
DbAdapterPCVerwaltung adapter = new DbAdapterPCVerwaltung();
// TextBoxes mit den PC-Daten werden ausgelesen
double ram = Convert.ToDouble(txbRAM.Text);
double hdd = Convert.ToDouble(txbHDD.Text);
double prozgeschw = Convert.ToDouble(txbProzGeschw.Text);
PC einPC;
if (aktuellerDatensatz == allePC.Count)
{ // wenn ein neuer PC angelegt werden soll, wird ein PC-Objekt erzeugt und
// in die Liste eingefügt
einPC = new PC();
}
else // PC wird geändert
{
einPC = allePC[aktuellerDatensatz];
}
// die in den TextBoxes stehenden Daten werden in das PC-Objekt zurückgeschrieben.
einPC.Prozessorgeschwindigkeit = prozgeschw;
einPC.RAM = ram;
einPC.HDD = hdd;
if (aktuellerDatensatz == allePC.Count)
{ // wenn ein neuer PC angelegt werden soll, wird ein PC-Objekt erzeugt und
// in die Liste eingefügt
allePC.Add(einPC);
adapter.insertPc(einPC);
}
else // PC wird geändert
{
einPC.ID = allePC[aktuellerDatensatz].ID;
allePC[aktuellerDatensatz] = einPC;
adapter.updatePc(einPC);
}
aktualisiereOberflaeche();
}
catch (Exception)
{
MessageBox.Show("Geben Sie eine Zahl für die PC-Daten ein!");
}
}
private void aktualisiereOberflaeche()
{
// Steuerung der Knöpfe;
// Grundzustand: alle Knöpfe sind funktionsfähig
btnErsterDS.Enabled = true;
btnLetzterDS.Enabled = true;
btnVorherigerDS.Enabled = true;
btnNaechsterDS.Enabled = true;
if (aktuellerDatensatz<=0)
{ // wenn der erste Datensatz erreicht ist werden die Knöpfe ausgegraut,
// die zurückblättern
btnErsterDS.Enabled = false;
btnVorherigerDS.Enabled = false;
}
if (aktuellerDatensatz>=allePC.Count-1)
{ // wenn der letzte Datensatz erreicht ist werden die Knöpfe ausgegraut,
// die vorblättern
btnLetzterDS.Enabled = false;
btnNaechsterDS.Enabled = false;
}
// Aktualisierung des Datensatzanzeigers
lblDatensatz.Text = "" + (aktuellerDatensatz + 1) + "/" + allePC.Count;
if (aktuellerDatensatz >= 0 && aktuellerDatensatz < allePC.Count)
{ // Inhalt der Textfelder falls ein Datensatz vorhanden ist
btnUebernehmen.Text = "Datensatz ändern";
txbDatenAusgabe.Text = allePC[aktuellerDatensatz].zeigeDaten();
txbHDD.Text = String.Format("{0:0.0}", allePC[aktuellerDatensatz].HDD);
txbRAM.Text = String.Format("{0:0.0}", allePC[aktuellerDatensatz].RAM);
txbProzGeschw.Text = String.Format("{0:0.0}", allePC[aktuellerDatensatz].Prozessorgeschwindigkeit);
}
else if ( aktuellerDatensatz==allePC.Count)
{ // Inhalt der Textfelder, falls kein Datensatz vorhanden ist, oder
// ein neuer angelegt werden soll
btnUebernehmen.Text = "Datensatz übernehmen";
txbDatenAusgabe.Clear();
txbRAM.Clear();
txbProzGeschw.Clear();
txbHDD.Clear();
}
}
private void btnErsterDS_Click(object sender, EventArgs e)
{
aktuellerDatensatz = 0;
aktualisiereOberflaeche();
}
private void btnVorherigerDS_Click(object sender, EventArgs e)
{
aktuellerDatensatz--;
aktualisiereOberflaeche();
}
private void btnNaechsterDS_Click(object sender, EventArgs e)
{
aktuellerDatensatz++;
aktualisiereOberflaeche();
}
private void btnLetzterDS_Click(object sender, EventArgs e)
{
aktuellerDatensatz = allePC.Count-1;
aktualisiereOberflaeche();
}
private void btnNeuerDS_Click(object sender, EventArgs e)
{
// aktuellerDatensatz==allePC.Count ist das das Signal in der
// Anwendung, dass ein neuer Datensatz angelegt wird.
aktuellerDatensatz = allePC.Count ;
aktualisiereOberflaeche();
}
private void alleLoeschenToolStripMenuItem_Click(object sender, EventArgs e)
{
allePC.Clear();
aktuellerDatensatz = 0;
aktualisiereOberflaeche();
}
private void dBVerbindungTestenToolStripMenuItem_Click_1(object sender, EventArgs e)
{
MySQLConnector connector = new MySQLConnector();
MessageBox.Show(connector.testConnection());
}
}
}
<file_sep>/README.md
# PC-Verwaltung-Volz-
Beispiellösung für die Datenbankanbindung mit C# für das Projekt PC-Verwaltung von Herrn Volz
<file_sep>/PC_Verwaltung_mit_DB - Start/PC_Verwaltung_Ver1/MySQLConnector.cs
using MySql.Data.MySqlClient;
using System;
namespace PC_Verwaltung_Ver4
{
public class MySQLConnector
{
// Attribute
private string dBHost = "localhost"; // kann auch IP-Adresse sein
private string dBUser = "root";
private string dBPasswort = "";
private string dBName = "pcverwaltung";
// Gekapselte Attribute
public string DBHost { get => dBHost; set => dBHost = value; }
public string DBUser { get => dBUser; set => dBUser = value; }
public string DBPasswort { get => dBPasswort; set => dBPasswort = value; }
public string DBName { get => dBName; set => dBName = value; }
// ConnectionStringBuilder wird in der ConnectionString Property verwendet,
// um mit den gesetzten Eigenschaften den Connectionstring zusammenzusetzen.
private MySqlConnectionStringBuilder mysqlConnectionStringBuilder = new MySqlConnectionStringBuilder();
// ConnectionStringProperty
public string ConnectionString
{
get
{
mysqlConnectionStringBuilder.Server = DBHost;
mysqlConnectionStringBuilder.UserID = DBUser;
mysqlConnectionStringBuilder.Password = <PASSWORD>;
mysqlConnectionStringBuilder.Database = DBName;
return mysqlConnectionStringBuilder.ConnectionString;
}
}
// Verbindung zur Datenbank öffnen und anschließend wieder schließen
// => Bei nicht erfolgreicher Verbindung wird eine Exception geworfen
public string testConnection()
{
string msg = "DB-Verbindung erfolgreich";
MySqlConnection connection = new MySqlConnection(ConnectionString);
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
msg = ex.GetBaseException().Message;
}
// Rückgabe der msg oder der geworfenen Exception
return msg;
}
}
}
<file_sep>/PC_Verwaltung_mit_DB - Start/PC_Verwaltung_Ver1/PC.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PC_Verwaltung_Ver4
{
public class PC
{
#region Attributdeklarationen
private int id;
public int ID
{
get { return id; }
set { id = value; }
}
private double prozessorgeschwindigkeit = 0;
public double Prozessorgeschwindigkeit
{
get { return prozessorgeschwindigkeit; }
set
{
if (value > 0)
{
prozessorgeschwindigkeit = value;
}
}
}
private double ram = 0;
public double RAM
{
get { return ram; }
set
{
if (value > 0)
{
ram = value;
}
}
}
private double hdd = 0;
public double HDD
{
get { return hdd; }
set
{
if (value > 0)
{
hdd = value;
}
}
}
#endregion
public double berechneLeistungsindex()
{
return prozessorgeschwindigkeit * ram * hdd;
}
public void setDaten(double prozGeschw, double ram, double hdd)
{ // setzt alle Daten in einer Methode
Prozessorgeschwindigkeit = prozGeschw;
RAM = ram;
HDD = hdd;
}
/*
* gibt die Daten formatiert aus
*/
public String zeigeDaten()
{
String daten="------------------------------------------------------"+Environment.NewLine+
"Prozessorgeschwindigkeit:\t" + String.Format("{0:0.0}", prozessorgeschwindigkeit) +" GHz"+ Environment.NewLine +
"Arbeitsspeicher:\t\t"+String.Format("{0:0.0}", ram) +" GB"+ Environment.NewLine +
"Festplattenkapazität:\t"+String.Format("{0:0.0}", hdd) +" GB"+ Environment.NewLine +
"Leistungsindex:\t\t" + berechneLeistungsindex();
return daten;
}
/*
* gibt die Daten des aktuellen PC als strichpunkt-separierte Zeile aus
*/
public String getDatenAsCSV()
{
return "" + Prozessorgeschwindigkeit + ";" + RAM + ";" + HDD;
}
/*
* liest die Daten des aktuellen PC als strichpunktseparierte Zeile ein
*/
public void setzeDatenAusCSV(String csvString)
{
String[] daten;
daten = csvString.Split(';');
Prozessorgeschwindigkeit=Convert.ToDouble(daten[0]);
RAM = Convert.ToDouble(daten[1]);
HDD = Convert.ToDouble(daten[2]);
}
}
}
| 0cc5eebcfbcbc746c63cc3a7c45cc0c41c54e36a | [
"Markdown",
"C#",
"SQL"
]
| 6 | C# | js-30/PC-Verwaltung-Volz- | a160ba2a38d1d92aa9cb96a57870d23449ce4330 | cdb98043ea5753df5a8119ba5088eb60e1754e37 |
refs/heads/master | <repo_name>boss-srithong/sutxlane-project-admin<file_sep>/src/components/Profiles/Profiles.js
import React ,{useState, useEffect}from 'react'
import { View, Text ,Button, Dimensions, Image, ImageBackground, KeyboardAvoidingView, TouchableOpacity} from 'react-native'
import { FlatList, ScrollView, TextInput } from 'react-native-gesture-handler'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import { faSignOutAlt} from '@fortawesome/free-solid-svg-icons'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { useSelector,useDispatch } from 'react-redux';
import { LoginManager,AccessToken,GraphRequest,GraphRequestManager } from 'react-native-fbsdk'
import {userFacebookValue} from '../../slice/dataUser'
const width = Dimensions.get('window').width/384
const height = Dimensions.get('window').height/781.3333333333334
const Profile = ({navigation}) => {
// const userData = useSelector(userFacebookValue)
// useEffect(() => {
// console.log("userData",userData);
// return () => {
// }
// }, [])
const logout = () =>{
navigation.replace("login")
// var current_access_token = userData.token;
// AccessToken.getCurrentAccessToken().then((data) => {
// current_access_token = data.accessToken.toString();
// }).then(() => {
// let logout =
// new GraphRequest(
// "me/permissions/",
// {
// accessToken: current_access_token,
// httpMethod: 'DELETE'
// },
// (error, result) => {
// if (error) {
// console.log('Error fetching data: ' + error.toString());
// } else {
// LoginManager.logOut();
// navigation.replace("login")
// }
// });
// new GraphRequestManager().addRequest(logout).start();
// })
// .catch(error => {
// console.log(error)
// });
}
const [userData] = useState([
{
id:1,
name: 'Firstname Lastname',
email: '<EMAIL>',
phone: '099999999',
}
])
return (
<KeyboardAwareScrollView style={{flex:1,padding:20}} extraHeight={200} >
<ScrollView contentContainerStyle={{flex:1,position:'relative'}} bounces={false}>
<View style={{flex:0.4,alignItems:'center',justifyContent:'center'}}>
<View style={{width:width*200,height:width*200,backgroundColor:'pink',borderRadius:width*200}}>
<Image style={{flex:1,resizeMode:'cover',borderRadius:width*384}} source={{uri:userData.picture !=='' ?`${userData.picture}` : 'https://as1.ftcdn.net/jpg/02/59/39/46/500_F_259394679_GGA8JJAEkukYJL9XXFH2JoC3nMguBPNH.jpg'}}/>
</View>
</View>
<View style={{height:height*250,padding:width*20,alignItems:'center',justifyContent:'space-evenly'}}>
{/* <Text>{userData.name !=="" ? userData.name:"Firstname Lastname"}</Text>
<Text>{userData.email !=='' ?userData.email : "<EMAIL>" }</Text>
<Text style={{fontFamily:'Kanit-Regular'}}>สวัสดี {userData.name}</Text> */}
<Text>{userData.name}</Text>
<Text>{userData.email}</Text>
<Text style={{fontFamily:'Kanit-Regular'}}>เบอร์โทร {userData.email}</Text>
</View>
</ScrollView>
<View style={{width:"100%",justifyContent:'center',alignItems:'center'}}>
<TouchableOpacity style={{alignItems:'center',justifyContent:'center',flexDirection:'row',marginTop:"15%",backgroundColor:'white',width:"50%",borderRadius:20}} onPress={logout}>
<FontAwesomeIcon icon={faSignOutAlt} size={60*height} color="grey"/>
<View style={{width:20}}/>
<Text>Logout</Text>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
)
}
export default Profile
<file_sep>/src/components/Approve/Approve.js
import React, {useState, useEffect} from 'react';
import {
View,
Text,
SafeAreaView,
StyleSheet,
ImageBackground,
ScrollView,
Dimensions,
TouchableOpacity,
} from 'react-native';
import {RFPercentage, RFValue} from 'react-native-responsive-fontsize';
import 'react-native-get-random-values';
import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome';
import {
faBed,
faBath,
faTrash,
} from '@fortawesome/free-solid-svg-icons';
const STANTDARD = 781;
const width = Dimensions.get('window').width / 384;
const height = Dimensions.get('window').height / 781.3333333333334;
const Approve = ({navigation}) => {
const [mockup_data] = useState([
{
id:1,
image:'https://static.posttoday.com/media/content/2018/11/12/D8359A2BC6B14AE981163E677F466165.jpg',
type: 'condo',
price: '฿ 2,700,000',
num_room: 1,
num_bath: 1,
desc: 'Set around a lake at the foot of a hill less than 400 meters from the beach in Kamala, this development of stylishcondominiums offers 235 beautifully designed condominium apartments.',
},
{
id:2,
image:'https://www.sansiri.com/uploads/gallery/2018/07/17/650_4a38d314-0065-4cdf-90c8-94096629ecc7.jpg',
type: 'condo',
price: '฿ 5,900,00',
num_room: 2,
num_bath: 1,
desc: ' Offer 175 sq.m. A fully furnished condo on a stunning waterfront. Biggest property with direct beach access.',
},
{
id:3,
image:'https://th1-cdn.pgimgs.com/listing/7974167/UPHO.76563246.R400X300/Blossom-Condo-Sathorn-Charoenrat-%E0%B8%9A%E0%B8%A5%E0%B8%AD%E0%B8%AA%E0%B8%8B%E0%B8%B1%E0%B9%88%E0%B8%A1-%E0%B8%84%E0%B8%AD%E0%B8%99%E0%B9%82%E0%B8%94-%E0%B8%AA%E0%B8%B2%E0%B8%97%E0%B8%A3-%E0%B9%80%E0%B8%88%E0%B8%A3%E0%B8%B4%E0%B8%8D%E0%B8%A3%E0%B8%B2%E0%B8%A9%E0%B8%8E%E0%B8%A3%E0%B9%8C-%E0%B8%AA%E0%B8%B2%E0%B8%97%E0%B8%A3-Thailand.jpg',
type: 'Apartment',
price: '฿ 6,300,000',
num_room: 3,
num_bath: 2,
desc: 'Offer 175 sq.m. A fully furnished condo on a stunning waterfront. Biggest property with direct beach access.',
},
{
id:4,
image:'https://www.origin.co.th/wp-content/uploads/2019/08/DSC3469-1024x683.jpg',
type: 'Apartment',
price: '฿ 1,900,000',
num_room: 2,
num_bath: 2,
desc: 'Allsopp & Allsopp are proud to present this stunning 1 bedroom apartment. Set in the extremely desirable Executive Tower, complete with mall on your doorstep, kids play area and park along with a gym and pool in the building itself. Great location for a family, to meet friends and amazing community feel. Almost penthouse level floor!',
},
{
id:5,
image:'https://static.posttoday.com/media/content/2018/11/12/D8359A2BC6B14AE981163E677F466165.jpg',
type: 'condo',
price: '฿ 2,700,000',
num_room: 1,
num_bath: 1,
desc: 'Set around a lake at the foot of a hill less than 400 meters from the beach in Kamala, this development of stylishcondominiums offers 235 beautifully designed condominium apartments.',
}
])
return (
<SafeAreaView style={styles.main}>
<TouchableOpacity
style={{
flexDirection: 'row',
flex: 0.08,
position: 'absolute',
right: 10,
marginTop: 10,
}}
onPress={() => navigation.goBack()}>
<Text style={{fontSize: width * 18, color: 'grey'}}>Cancel</Text>
</TouchableOpacity>
<View
style={{
height: height * 70,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{fontSize: 20 * width, color: '#2c3949', fontWeight: 'bold'}}>
Approval
</Text>
</View>
<View style={styles.detail}>
<Text style={{...styles.text1, fontWeight: 'bold'}}>
Waiting Approval
</Text>
<ScrollView>
{
mockup_data.map((item, index) => (
<View style={styles.news}>
<View
style={{width: '50%', backgroundColor: 'grey', height: '100%'}}>
<ImageBackground
source={{
uri : item.image,
}}
style={{
height: '100%',
width: '100%',
position: 'relative', // because it's parent
top: 2,
left: 2,
}}>
<Text
style={{
fontWeight: 'bold',
color: 'white',
position: 'absolute', // child
bottom: 0, // position where you want
left: 0,
backgroundColor: 'rgba(255,255,255, 0.5)',
width: '100%',
paddingLeft: 5,
paddingBottom: 3,
paddingTop: 3,
}}>
{item.type}
</Text>
</ImageBackground>
</View>
<View
style={{flexDirection: 'column', width: '50%', marginLeft: 10}}>
<View
style={{
width: '90%',
alignItems: 'center',
justifyContent: 'space-between',
flexDirection: 'row',
}}>
<Text> {item.price}</Text>
<TouchableOpacity onPress={() => alert('delete')}>
<FontAwesomeIcon icon={faTrash} color="red" />
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row'}}>
<View
style={{
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
}}>
<Text> {item.num_room}</Text>
<View style={{width: 5}} />
<FontAwesomeIcon icon={faBed} />
</View>
<View style={{width: 10}} />
<View
style={{
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
}}>
<Text> {item.num_bath}</Text>
<View style={{width: 5}} />
<FontAwesomeIcon icon={faBath} />
</View>
</View>
<Text numberOfLines={4} style={{width: '100%'}}>
{item.desc}
</Text>
</View>
</View>
))
}
</ScrollView>
<View style={{marginTop: 10}}>
<TouchableOpacity
style={{
height: 45 * height,
backgroundColor: 'red',
marginTop: '5%',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#2c3949',
borderRadius: 10,
flexDirection: 'row',
width: '100%',
}}
onPress={() => alert('Approve completed')}>
<Text style={{fontSize: RFValue(20, STANTDARD), color: 'white'}}>
Approve
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
height: 45 * height,
backgroundColor: 'grey',
marginTop: '5%',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10,
flexDirection: 'row',
width: '100%',
}}
onPress={() => alert('Approve completed')}>
<Text style={{fontSize: RFValue(20, STANTDARD), color: 'white'}}>
Approve All
</Text>
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
main: {
flex: 1,
backgroundColor: '#edf0ee',
},
input: {
flex: 0.2,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'center',
},
input2: {
width: '90%',
height: 50,
backgroundColor: 'white',
borderRadius: 25,
borderColor: 'white',
borderWidth: 2,
marginLeft: 10,
marginRight: 10,
fontSize: 16,
paddingLeft: 20,
marginTop: 20,
},
content: {
flex: 0.38,
marginTop: 40,
// backgroundColor:'red'
},
detail: {
flex: 0.95,
padding: 20,
paddingTop: 0,
},
text1: {
color: 'orange',
fontSize: 20,
marginBottom: 10,
},
news: {
height: 120,
width: '100%',
// backgroundColor:'pink',
margin: 10,
marginLeft: 0,
flexDirection: 'row',
},
});
export default Approve;
<file_sep>/src/components/login/Login.js
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { View, Text , Dimensions,StyleSheet, Image, SafeAreaView, TouchableOpacity ,Modal, ActivityIndicator ,TextInput} from 'react-native'
// Import FBSDK
import {
LoginButton,
AccessToken,
GraphRequest,
GraphRequestManager,
LoginManager,
} from 'react-native-fbsdk';
import { useSelector,useDispatch } from 'react-redux';
import {fecthDataUserAction ,fecthTokenFacebookAction} from '../../slice/dataUser'
import {height,width} from '../constants'
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
const STANTDARD = 781
const login = ({navigation}) => {
const [userName, setUserName] = useState('');
const [token, setToken] = useState('');
const [profilePic, setProfilePic] = useState('');
const [tokenData ,setTokenData] = useState('')
const [loadingData , setLoadingData] = useState(false)
const dispatch = useDispatch()
const handleSignIn = ()=>{
navigation.replace("main")
}
const handleSignUp = ()=>{
navigation.navigate("signup")
}
const getResponseInfo = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
dispatch(fecthDataUserAction((result)))
navigation.replace("main")
}
};
const loginWithFacebook = () => {
setLoadingData(true)
// Attempt a login using the Facebook login dialog asking for default permissions.
LoginManager.logInWithPermissions(['public_profile','email']).then(
login => {
if (login.isCancelled) {
console.log('Login cancelled');
} else {
AccessToken.getCurrentAccessToken().then((data) => {
dispatch(fecthTokenFacebookAction(data.accessToken))
const processRequest = new GraphRequest(
'/me?fields=name,picture.type(large)',
null,
getResponseInfo,
);
// Start the graph request.
new GraphRequestManager()
.addRequest(processRequest).start();
});
}
},
error => {
console.log('Login fail with error: ' + error);
},
);
};
// const getEmail = async () =>{
// try {
// console.log({url: `https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=${tokenData}`});
// fetch( `https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=${tokenData}`)
// .then((response) => (response.json(),setLoadingData(false)))
// } catch (error) {
// console.log(error);
// }
// }
return (
<SafeAreaView style={{flex:1,padding:20,alignItems:'center',justifyContent:'center'}} extraHeight={200} >
<Text style={{fontSize:25*height,marginBottom:20*height}}>Welcome To</Text>
<Image source={require('../../picture/logo.png')} style={{width:width*150,height:width*150,resizeMode:'contain'}} />
<View style={{width:20,height:20*height}}/>
<TextInput placeholder="Username / email" style={{fontSize:RFValue(20,STANTDARD),backgroundColor:'white',width:"80%"}}/>
<View style={{width:20,height:20*height}}/>
<TextInput placeholder="Password" style={{fontSize:RFValue(20,STANTDARD),backgroundColor:'white',width:"80%"}}/>
<View style={{width:20,height:20*height}}/>
<TouchableOpacity onPress={handleSignIn} style={{width:width*220,height:45*height,backgroundColor:'red',marginTop:"5%",alignItems:'center',justifyContent:'center',backgroundColor:'#2c3949',borderRadius:30/2*height}}><Text style={{fontSize:RFValue(20,STANTDARD),color:'white'}}>Login</Text></TouchableOpacity>
<TouchableOpacity onPress={handleSignUp} style={{width:width*220,height:45*height,backgroundColor:'red',marginTop:"5%",alignItems:'center',justifyContent:'center',backgroundColor:'white',borderRadius:65/2*height}}><Text style={{fontSize:RFValue(20,STANTDARD),color:"#2c3949"}}>SignUp</Text></TouchableOpacity>
{/* <TouchableOpacity onPress={loginWithFacebook}>
<Image source={require('../../picture/Facebook.gif')} style={{width:50*width,height:50*width,marginTop:10}}/>
</TouchableOpacity> */}
</SafeAreaView>
)
}
export default login
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textStyle: {
fontSize: 20,
color: '#000',
textAlign: 'center',
padding: 10,
},
imageStyle: {
width: 200,
height: 300,
resizeMode: 'contain',
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
textAlign: 'center',
padding: 20,
},
footerHeading: {
fontSize: 18,
textAlign: 'center',
color: 'grey',
},
footerText: {
fontSize: 16,
textAlign: 'center',
color: 'grey',
},
});<file_sep>/src/components/login/SignUp.js
import React, { useEffect ,useState } from 'react'
import { View, Text , Dimensions, Image, SafeAreaView, TouchableOpacity} from 'react-native'
import { TextInput } from 'react-native-gesture-handler'
import {height,width} from '../constants'
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
const STANTDARD = 781
const SignUp = ({navigation}) => {
const [userName, setUserName] = useState('');
const [token, setToken] = useState('');
const [profilePic, setProfilePic] = useState('');
const handleSignUp = ()=>{
navigation.goBack()
}
const getResponseInfo = (error, result) => {
if (error) {
//Alert for the Error
alert('Error fetching data: ' + error.toString());
} else {
//response alert
console.log(JSON.stringify(result));
setUserName('Welcome ' + result.name);
setToken('User Token: ' + result.id);
setProfilePic(result.picture.data.url);
}
};
return (
<SafeAreaView style={{flex:1,padding:20,alignItems:'center',justifyContent:'center'}} extraHeight={200} >
<Text style={{fontSize:25*height,marginBottom:20*height}}>Wellcome To</Text>
<Image source={require('../../picture/logo.png')} style={{width:width*100,height:width*100,resizeMode:'contain'}} />
<View style={{width:20,height:20*height}}/>
<TextInput placeholder="Username / email" style={{fontSize:RFValue(20,STANTDARD),backgroundColor:'white',width:"80%"}}/>
<View style={{width:20,height:20*height}}/>
<TextInput placeholder="<PASSWORD>" style={{fontSize:RFValue(20,STANTDARD),backgroundColor:'white',width:"80%"}}/>
<View style={{width:20,height:20*height}}/>
<TextInput placeholder="Re-Password" style={{fontSize:RFValue(20,STANTDARD),backgroundColor:'white',width:"80%"}}/>
<View style={{width:20,height:20*height}}/>
<TouchableOpacity onPress={handleSignUp} style={{width:width*220,height:45*height,backgroundColor:'red',marginTop:"5%",alignItems:'center',justifyContent:'center',backgroundColor:'#2c3949',borderRadius:65/2*height}}><Text style={{fontSize:RFValue(20,STANTDARD),color:"white"}}>SignUp</Text></TouchableOpacity>
</SafeAreaView>
)
}
export default SignUp
<file_sep>/App.js
import React ,{useEffect} from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import RNBootSplash from "react-native-bootsplash";
import Login from './src/components/login/Login'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import { faHome , faPlusCircle, faMapMarker ,faHeart ,faUser, faUserEdit} from '@fortawesome/free-solid-svg-icons'
import Home from './src/components/Home/Home';
import DetailHome from './src/components/Home/DetailHome';
import Filter from './src/components/Home/Filter'
import NearMe from './src/components/NearMe/NearMe';
import Profiles from './src/components/Profiles/Profiles';
import SignUp from './src/components/login/SignUp';
import Favorites from './src/components/Favorites/Favorites';
import AddProperty from './src/components/AddProperty/AddProperty';
import EditProperty from './src/components/AddProperty/EditProperty';
import Approve from './src/components/Approve/Approve';
const Tab = createBottomTabNavigator();
const Stack = createStackNavigator()
const Stack1 = ()=>{
useEffect(()=>{
let fontName = 'Kanit-Regular'
},[])
return(
<Stack.Navigator >
<Stack.Screen name="Home" component={Home} options={{headerShown:false}}/>
<Stack.Screen name="DetailHome" component={DetailHome} options={{headerShown:false}}/>
<Stack.Screen name="Filter" component={Filter} options={{headerShown:false}}/>
<Stack.Screen name="EditProperty" component={EditProperty} options={{headerShown:false}}/>
</Stack.Navigator>
)
}
const TabSctack =()=>{
return(
<Tab.Navigator
initialRouteName="Home"
tabBarOptions={{
activeTintColor: '#e91e63',
}}
>
<Tab.Screen
name="Home"
children={Stack1}
options={{
tabBarLabel: 'Home',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faHome} color={color} size={size}/>
),
}}
/>
<Tab.Screen
name="AddProperty"
component={AddProperty}
options={{
tabBarLabel: 'Add Propery',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faPlusCircle} color={color} size={size}/>
),
}}
/>
<Tab.Screen
name="NearMe"
component={NearMe}
options={{
tabBarLabel: 'Near Me',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faMapMarker} color={color} size={size}/>
),
}}
/>
<Tab.Screen
name="Favorites"
component={Favorites}
options={{
tabBarLabel: 'Favorites',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faHeart} color={color} size={size}/>
),
}}
/>
<Tab.Screen
name="Approve"
component={Approve}
options={{
tabBarLabel: 'Approve',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faUserEdit} color={color} size={size}/>
),
}}
/>
<Tab.Screen
name="Profiles"
component={Profiles}
options={{
tabBarLabel: 'Profile',
tabBarIcon: ({ color, size }) => (
<FontAwesomeIcon icon={faUser} color={color} size={size}/>
),
}}
/>
</Tab.Navigator>
)
}
export default function App() {
useEffect(()=>{
RNBootSplash.hide({ duration: 500 }); // fade
},[])
return (
<NavigationContainer>
<Stack.Navigator >
<Stack.Screen name="login" component={Login} options={{headerShown:false}}/>
<Stack.Screen name="main" children={TabSctack} options={{headerShown:false}}/>
<Stack.Screen name="signup" component={SignUp} options={{headerShown:false}}/>
</Stack.Navigator>
</NavigationContainer>
);
}<file_sep>/src/components/Favorites/Favorites.js
import React from 'react'
import { View, Text, SafeAreaView,ScrollView ,Image, ImageBackground} from 'react-native'
import {height,width} from '../constants'
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import { faHeart} from '@fortawesome/free-solid-svg-icons'
const STANTDARD = 781
const Favorites = () => {
const data = [
{id:1,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:2,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:3,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:false},
{id:4,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:6,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:7,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:8,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:9,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:10,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
{id:11,imagUrl:'https://www.theriver-condo.com/wp-content/uploads/2015/04/The-River-Bangkok-condo-for-rent-1.jpg',message:"Helloword123465",like:true},
]
return (
<SafeAreaView style={{flex:1,padding:width*20}}>
<Text style={{marginVertical:20*height,fontSize:RFValue(30,STANTDARD),fontWeight:'bold'}}>Favorites</Text>
<ScrollView>
<View style={{flexDirection:'row'}}>
<View style={{flexDirection:'column'}}>
{data.map((e,i)=>{
return(
<React.Fragment key={e.id}>
{e.like ? (
<View key={e.id} style={{width:width*150,height:width*120,backgroundColor:'red',margin:5*width,display:i%2 ==1 ?'none':null,marginTop:i !=0 ?50*height:0}}>
<ImageBackground style={{width:"100%",height:"100%",resizeMode:'cover'}} source={{uri:e.imagUrl}}>
<View style={{position:'absolute',right:0,width:30*width,height:30*width,backgroundColor:'white',alignItems:'center',justifyContent:'center',borderRadius:999 }}>
<FontAwesomeIcon color="red" icon={faHeart}/>
</View>
</ImageBackground>
<Text>Condo 3ห้องน้ำ 1 ห้องนอน เดือนละ 200 บาท</Text>
</View>
):(
null
)}
</React.Fragment>
)
})}
</View>
<View style={{flexDirection:'column'}}>
{data.map((e,i)=>{
return(
<React.Fragment key={e.id}>
{e.like ? (
<View key={e.id} style={{width:width*150,height:width*120,backgroundColor:'red',margin:5*width,display:i%2 ==1 ?'none':null,marginTop:i !=0 ?50*height:0}}>
<ImageBackground style={{width:"100%",height:"100%",resizeMode:'cover'}} source={{uri:e.imagUrl}}>
<View style={{position:'absolute',right:0,width:30*width,height:30*width,backgroundColor:'white',alignItems:'center',justifyContent:'center',borderRadius:999 }}>
<FontAwesomeIcon color="red" icon={faHeart}/>
</View>
</ImageBackground>
<Text>Condo 3ห้องน้ำ 1 ห้องนอน เดือนละ 200 บาท</Text>
</View>
):(
null
)}
</React.Fragment>
)
})}
</View>
</View>
</ScrollView>
</SafeAreaView>
)
}
export default Favorites
<file_sep>/src/components/Home/DetailHome.js
import React from 'react'
import { View, Text ,SafeAreaView,Image,Dimensions,TouchableOpacity, ScrollView } from 'react-native'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import { faAngleLeft ,faPhone ,faEnvelope ,faHeart} from '@fortawesome/free-solid-svg-icons'
import {Linking} from 'react-native'
const width = Dimensions.get('window').width/384
const height = Dimensions.get('window').height/781.3333333333334
const DetailHome = ({navigation}) => {
console.log(width,height);
const callPhone = ()=>{
Linking.openURL(`tel:0854658721`)
}
const callMail = ()=>{
Linking.openURL(`mailto:<EMAIL>`)
}
const LineOpen = () =>{
Linking.openURL("http://line.me/ti/p/~@suthnews")
}
return (
<SafeAreaView style={{flex:1,backgroundColor:'#edf0ee'}}>
<TouchableOpacity style={{flexDirection:'row',marginTop:10*height,alignItems:'center',marginBottom:10*height}} onPress={()=>navigation.goBack()}>
<FontAwesomeIcon icon={faAngleLeft} size={width*40}/>
<Text style={{fontSize:width*20}}>Back</Text>
</TouchableOpacity>
<View style={{height:250*height,alignItems:'center',marginBottom:20*height}}>
<Image source={{uri:'https://sg2-cdn.pgimgs.com/developer-listing/4370109/OUPHO.122053829.V800/Grene-Condo-Donmueang-Songprapha-Don-Mueang-Thailand.jpg'}} style={{width:"90%",height:"100%",resizeMode:'cover'}}/>
</View>
<ScrollView>
<View style={{width:width - 40,marginLeft:20,flex:0.5,marginTop:10}}>
<Text style={{fontSize:height*20,color:'tomato'}}>Details</Text>
<View style={{ width :width - 40}}>
<View style={{flexDirection:'row'}}>
<Text>Type : </Text>
<Text>Sale</Text>
</View>
<View style={{flexDirection:'row'}}>
<Text>price : </Text>
<Text>฿ 5,000,000</Text>
</View>
<View style={{flexDirection:'row'}}>
<Text>Size : </Text>
<Text>฿ 2128 sqm</Text>
</View>
</View>
<Text style={{fontSize:height*20,color:'tomato',marginTop:height*15}}>Description</Text>
<Text style={{width:width*384 - 20 -20}}> Lorem ipsum dolor sit amet consectetur adipisicing elit. Harum consequuntur atque ipsum asperiores, laboriosam optio debitis aliquam tenetur neque nobis. A id ratione sapiente distinctio, pariatur corrupti veritatis ipsam repudiandae?</Text>
<Text style={{fontSize:height*20,color:'tomato',marginTop:height*15}}>Facilities</Text>
<Text>Car packing</Text>
<Text>Swingming pool</Text>
</View>
</ScrollView>
<View style={{width:"100%",height:80*height,backgroundColor:'rgba(0,0,0,0)',flexDirection:'row',justifyContent:'flex-end'}}>
<TouchableOpacity style={{width:width*60,height:width*60,backgroundColor:'white',margin:10,borderRadius:999,alignItems:'center',justifyContent:'center'}} onPress={callPhone}>
<FontAwesomeIcon icon={faPhone} size={40*height} color="#892b64"/>
</TouchableOpacity>
<TouchableOpacity style={{width:width*60,height:width*60,backgroundColor:'white',margin:10,borderRadius:999,alignItems:'center',justifyContent:'center'}} onPress={callMail}>
<FontAwesomeIcon icon={faEnvelope} size={40*height} color="#455e89"/>
</TouchableOpacity>
<TouchableOpacity onPress={()=>navigation.navigate("Favorites")} style={{width:width*60,height:width*60,backgroundColor:'white',margin:10,borderRadius:999,alignItems:'center',justifyContent:'center'}}>
<FontAwesomeIcon icon={faHeart} size={40*height} color="#ef233c"/>
</TouchableOpacity>
</View>
</SafeAreaView>
)
}
export default DetailHome
<file_sep>/src/slice/dataUser.js
import { createSlice } from '@reduxjs/toolkit';
export const userFacebookSlice = createSlice({
name: 'UserData',
initialState: {
picture:'',
name:'',
email:'',
token:''
},
reducers: {
fecthDataUserFacebook: (initialState, action) => {
return(
{...initialState,picture:action.payload.picture.data.url,name:action.payload.name}
)
} ,
fecthTokenFacebook : (initialState, action) => {
console.log("action.payload",action.payload);
return(
{...initialState,token:action.payload}
)
} ,
},
});
const { fecthDataUserFacebook ,fecthTokenFacebook} = userFacebookSlice.actions;
export const fecthDataUserAction = (data) => {
return(dispatch)=>{
dispatch(fecthDataUserFacebook(data));
}
};
export const fecthTokenFacebookAction = (data) => {
return(dispatch)=>{
dispatch(fecthTokenFacebook(data));
}
};
//get value
export const userFacebookValue = state => state.userFacebookState;
<file_sep>/src/slice/store.js
import { configureStore } from '@reduxjs/toolkit';
import {userSlice} from '../slice/usersSlice'
import {userFacebookSlice} from '../slice/dataUser'
import {configNavogationSlice} from '../slice/configNavogationSlice'
export default configureStore({
reducer: {
userState:userSlice.reducer,
userFacebookState:userFacebookSlice.reducer,
configNavogationState:configNavogationSlice.reducer
},
});
| f36000bb322f35e863580076a6b1c76a9c3f5e9a | [
"JavaScript"
]
| 9 | JavaScript | boss-srithong/sutxlane-project-admin | 8ca7184eb42c72e5ef7739e77e01f2990468505f | 8b7aa2dd7ecccbdf9971c6abc2589d65d7d4434a |
refs/heads/main | <file_sep>from django.apps import AppConfig
class AlbumProjectConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'album_project'
<file_sep>from django import forms
from django.db import models
from django.db.models import fields
from .models import Albums, Tracks
class AlbumsForm(forms.ModelForm):
class Meta:
model = Albums
fields = [
'title',
'artist',
'release_year',
'photo',
]
# class TracksForm(forms.ModelForm):
# class Meta:
# model = Tracks
# fields = [
# ]<file_sep>from django.shortcuts import render, redirect, get_object_or_404
from .models import Albums, Tracks
from .forms import AlbumsForm
# from django.http import HttpResponse
# trying to troubleshoot^
# Create your views here.
#Is this function erronious??
def list_albums(request):
albums = Albums.objects.all()
return render(request, 'list_albums.html', {'albums': albums})
def add_album(request):
form = None
if request.method == 'GET':
form = AlbumsForm()
else:
form = AlbumsForm(data=request.POST)
if form.is_valid():
form.save()
return redirect(to='list_albums')
# need to make that first ^
return render(request, "album_project/add_album.html", {"form": form})
def delete_album(request, pk):
album = get_object_or_404(Albums, pk=pk)
if request.method == 'POST':
album.delete()
return redirect(to='list_albums')
# need to make that first ^
return render(request, "album_project/delete_album.html",
{"album": album})
def edit_album(request, pk):
album = get_object_or_404(Albums, pk=pk)
form = None
if request.method == 'GET':
form = AlbumsForm(instance=album)
else:
form = AlbumsForm(data=request.POST, instance=album)
if form.is_valid():
form.save()
return redirect(to='list_albums')
# need to make that first
return render(request, "album_project/edit_album.html", {
"form": form,
"album": album
})
<file_sep>from django.db import models
from django.db.models.fields import DateTimeField
# Create your models here.
class Albums(models.Model):
title = models.CharField(max_length=250)
artist = models.CharField(max_length=250, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
photo = models.CharField(max_length=250, null=True, blank=True)
release_year = models.IntegerField(null=True, blank=True)
def __str__(self):
return f"{self.title}, {self.artist}, {self.release_year}"
class Tracks(models.Model):
name = models.CharField(max_length=250)
albums = models.ForeignKey(
Albums,
on_delete=models.CASCADE,
related_name="tracks"
)
def __str__(self):
return f"{self.name}, {self.albums}"
<file_sep># Generated by Django 3.2.6 on 2021-08-13 20:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('album_project', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tracks',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('album', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tracks', to='album_project.albums')),
],
),
]
<file_sep># Generated by Django 3.2.6 on 2021-08-13 21:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('album_project', '0004_tracks_name'),
]
operations = [
migrations.AlterField(
model_name='albums',
name='release_year',
field=models.IntegerField(blank=True, null=True),
),
]
| b848f5abc8573743c1ff3806bbc56a6c4cb770ee | [
"Python"
]
| 6 | Python | Connorh223/django-music-Connorh223 | 6fca2bf249a6d7e9dbb69f3c99024e885d44a2ea | 4bf1d2faad366b86d5be04ebb2f200a8ee07a980 |
refs/heads/master | <repo_name>Andirie/ProgrammingAssignment2<file_sep>/cachematrix.R
## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
invMat<- NULL ##holds the value of inverse matrix
set<- function(y){ ##set the value of matrix
x<<-y ##assign a value to an object in an environment that is different from the current environment
invMat<-NULL
}
get<- function()x ##get the value of matrix
setInverse<-function(inverse) invMat<<-inverse ##set the value of inverse matrix
getInverse<- function()invMat ##get the value of inverse matrix
list(set=set,get=get,setInverse=setInverse,getInverse=getInverse)
}
## Write a short comment describing this function
##This function computes the inverse of the special "matrix" returned by makeCacheMatrix above
## If the inverse has already been calculated,then the cachesolve should retrieve the inverse from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
invMat<- x$getInverse()
if(!is.null(invMat)){
message("getting cached matrix")
return(invMat)
}
data<- x$get()
invMat<-solve(data,...)
x$setInverse(invMat) ##sets the value of the inverse matrix in the cache via the setInverse function
return(invMat)
}
| c242fe59d5c9d1017d100cb2373c037fd3213ece | [
"R"
]
| 1 | R | Andirie/ProgrammingAssignment2 | 09aaffba5e2b36196b957b162618aa6b8d87bc9f | a88ffba2e86b5380e4b75302516bc4acf8ccfc6a |
refs/heads/master | <repo_name>Asvor93/PetShop.CrashCourse2019<file_sep>/PetShop.Core/ApplicationService/Services/OwnerService.cs
using System.Collections.Generic;
using System.Linq;
using PetShop.Core.DomainService;
using PetShop.Core.Entity;
namespace PetShop.Core.ApplicationService.Services
{
public class OwnerService: IOwnerService
{
private IOwnerRepository _ownerRepository;
public OwnerService(IOwnerRepository ownerRepository)
{
this._ownerRepository = ownerRepository;
}
public Owner AddOwner(string firstName, string lastName, string address, string phoneNr, string email)
{
Owner newOwner = new Owner
{
FirstName = firstName,
LastName = lastName,
Address = address,
PhoneNumber = phoneNr,
Email = email
};
return _ownerRepository.CreateOwner(newOwner);
}
public List<Owner> ReaOwners()
{
return _ownerRepository.ReadAllOwners().ToList();
}
public Owner UpdateOwner(Owner ownerToUpdate)
{
return _ownerRepository.UpdateOwner(ownerToUpdate);
}
public Owner RemoveOwner(Owner ownerToDelete)
{
return _ownerRepository.DeleteOwner(ownerToDelete.Id);
}
public Owner FindOwnerById(int id)
{
return _ownerRepository.ReadAllOwners().FirstOrDefault(owner => owner.Id == id);
}
}
}<file_sep>/PetShop.Infrastructure.Data/Repositories/OwnerRepository.cs
using System.Collections.Generic;
using System.Linq;
using PetShop.Core.DomainService;
using PetShop.Core.Entity;
namespace PetShop.Infrastructure.Data.Repositories
{
public class OwnerRepository: IOwnerRepository
{
public Owner CreateOwner(Owner owner)
{
owner.Id = FakeDb.OwnerId;
FakeDb.Owners.Add(owner);
return owner;
}
public IEnumerable<Owner> ReadAllOwners()
{
return FakeDb.Owners;
}
public Owner UpdateOwner(Owner ownerToUpdate)
{
var ownerFromDb = GetOwnerById(ownerToUpdate.Id);
if (ownerFromDb != null)
{
ownerFromDb.FirstName = ownerToUpdate.FirstName;
ownerFromDb.LastName = ownerToUpdate.LastName;
ownerFromDb.Address = ownerToUpdate.Address;
ownerFromDb.PhoneNumber = ownerToUpdate.PhoneNumber;
ownerFromDb.Email = ownerToUpdate.Email;
return ownerToUpdate;
}
return null;
}
public Owner DeleteOwner(int id)
{
var ownerToDelete = FakeDb.Owners.FirstOrDefault(owner => owner.Id == id);
FakeDb.Owners.Remove(ownerToDelete);
return ownerToDelete;
}
public Owner GetOwnerById(int id)
{
foreach (var owner in FakeDb.Owners)
{
if (owner.Id == FakeDb.PetId)
{
return owner;
}
}
return null;
}
}
}<file_sep>/PetShop.Core/ApplicationService/Services/PetService.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using PetShop.Core.DomainService;
using PetShop.Core.Entity;
namespace PetShop.Core.ApplicationService.Services
{
public class PetService: IPetService
{
private readonly IPetRepository _petRepository;
public PetService(IPetRepository petRepository)
{
this._petRepository = petRepository;
}
public List<Pet> GetPets()
{
return this._petRepository.ReadPets().ToList();
}
public Pet AddPet(string name, string petType, DateTime birthDate, DateTime soldDate, string color, Owner previousOwner,
double price)
{
Pet pet = new Pet
{
Name = name,
PetType = petType,
BirthDate = birthDate,
SoldDate = soldDate,
Color = color,
PreviousOwner = previousOwner,
Price = price
};
return _petRepository.CreatePet(pet);
}
public Pet FindPetById(int id)
{
return _petRepository.ReadPets().FirstOrDefault(pet => pet.Id == id);
}
public Pet FindPetByName(string petName)
{
return _petRepository.GetSinglePetByName(petName);
}
public Pet Delete(Pet petToDelete)
{
return _petRepository.DeletePet(petToDelete.Id);
}
public Pet Update(Pet petToUpdate)
{
return _petRepository.UpdatePet(petToUpdate);
}
public List<Pet> OrderByPrice()
{
var sortBy = _petRepository.ReadPets().OrderBy(pets => pets.Price).ToList();
foreach (var pet in sortBy)
{
Console.WriteLine($"The pets ordered by price: Id {pet.Id} name: {pet.Name} Type: {pet.PetType}, Birthday: {pet.BirthDate}, Color: {pet.Color}, " +
$"Previous owner: {pet.PreviousOwner} Price: {pet.Price}, Sold date: {pet.SoldDate}\n");
}
return sortBy;
}
public bool ValidateId(int inputId, int petId)
{
return _petRepository.ValidateId(inputId, petId);
}
}
}<file_sep>/PetShop.Core/DomainService/IPetRepository.cs
using System.Collections.Generic;
using PetShop.Core.Entity;
namespace PetShop.Core.DomainService
{
public interface IPetRepository
{
Pet CreatePet(Pet pet);
IEnumerable<Pet> ReadPets();
Pet UpdatePet(Pet pet);
Pet DeletePet(int id);
Pet GetSinglePetById(int id);
Pet GetSinglePetByName(string petName);
bool ValidateId(int inputId, int petId);
}
}<file_sep>/PetShop.Core/DomainService/IOwnerRepository.cs
using System.Collections.Generic;
using PetShop.Core.Entity;
namespace PetShop.Core.DomainService
{
public interface IOwnerRepository
{
Owner CreateOwner(Owner owner);
IEnumerable<Owner> ReadAllOwners();
Owner UpdateOwner(Owner ownerToUpdate);
Owner DeleteOwner(int id);
}
}<file_sep>/PetShop.Infrastructure.Data/Repositories/PetRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using PetShop.Core.DomainService;
using PetShop.Core.Entity;
namespace PetShop.Infrastructure.Data.Repositories
{
public class PetRepository: IPetRepository
{
public Pet CreatePet(Pet pet)
{
pet.Id = FakeDb.PetId++;
FakeDb.Pets.Add(pet);
return pet;
}
public IEnumerable<Pet> ReadPets()
{
return FakeDb.Pets;
}
public Pet UpdatePet(Pet pet)
{
var petFromDb = GetSinglePetById(pet.Id);
if (petFromDb != null)
{
petFromDb.Name = pet.Name;
petFromDb.PetType = pet.PetType;
petFromDb.BirthDate = pet.BirthDate;
petFromDb.SoldDate = pet.SoldDate;
petFromDb.Color = pet.Color;
petFromDb.PreviousOwner = pet.PreviousOwner;
petFromDb.Price = pet.Price;
return pet;
}
return null;
}
public Pet DeletePet(int id)
{
var petToRemove = FakeDb.Pets.FirstOrDefault(pet => pet.Id == id);
FakeDb.Pets.Remove(petToRemove);
return petToRemove;
}
public Pet GetSinglePetById(int id)
{
foreach (var pet in FakeDb.Pets)
{
if (pet.Id == FakeDb.PetId)
{
return pet;
}
}
return null;
}
public Pet GetSinglePetByName(string petName)
{
foreach (var petToGet in FakeDb.Pets)
{
if (petToGet.Name.ToLower().Equals(petName.ToLower()))
{
return petToGet;
}
}
return null;
}
public bool ValidateId(int inputId, int petId)
{
if (inputId == FakeDb.PetId)
{
return true;
}
return false;
}
}
}<file_sep>/PetShop.Core/ApplicationService/IPetService.cs
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using PetShop.Core.Entity;
namespace PetShop.Core.ApplicationService
{
public interface IPetService
{
/// <summary>
///
/// </summary>
/// <returns></returns>
List<Pet> GetPets();
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="petType"></param>
/// <param name="birthDate"></param>
/// <param name="soldDate"></param>
/// <param name="color"></param>
/// <param name="previousOwner"></param>
/// <param name="price"></param>
/// <returns></returns>
Pet AddPet(string name, string petType, DateTime birthDate, DateTime soldDate, string color, Owner previousOwner, double price);
Pet FindPetById(int id);
Pet FindPetByName(string petName);
Pet Delete(Pet petToDelete);
Pet Update(Pet petToUpdate);
List<Pet> OrderByPrice();
bool ValidateId(int inputId, int petId);
}
}<file_sep>/PetShop.Core/ApplicationService/IOwnerService.cs
using System.Collections.Generic;
using System.Net.Sockets;
using PetShop.Core.Entity;
namespace PetShop.Core.ApplicationService
{
public interface IOwnerService
{
Owner AddOwner(string firstName, string lastName, string address, string phoneNr, string email);
List<Owner> ReaOwners();
Owner UpdateOwner(Owner ownerToUpdate);
Owner RemoveOwner(Owner ownerToDelete);
Owner FindOwnerById(int id);
}
} | 5f633d23d3b32813c81f34887af9f4fca72da947 | [
"C#"
]
| 8 | C# | Asvor93/PetShop.CrashCourse2019 | 2c7cf69f3c46d1331a61b67a2f5410e8e673a964 | cd10ae861e60d00a69d9945ef9ce22ecd61e5b29 |
refs/heads/master | <file_sep>//
// Created by sulin on 2017/9/29.
//
#ifndef UILIB_WINDOWITEM_H
#define UILIB_WINDOWITEM_H
#include <QQuickItem>
#include <QWindow>
#include <QQuickWindow>
/**
* @brief For native drag
*/
class WindowTitleItem : public QQuickItem {
Q_OBJECT
public:
explicit WindowTitleItem(QQuickItem *parent = Q_NULLPTR);
~WindowTitleItem();
void mouseDoubleClickEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
};
/**
* @brief 顶级窗口控件, 采用native样式来装饰
*/
class WindowItem : public QQuickWindow {
Q_OBJECT
Q_PROPERTY(bool fakeClose READ isFakeClose WRITE setFakeClose)
private:
qreal oldRatio; // 当前窗口当前采用的像素密度, MAC环境需要在像素密度变化时手动刷新窗口
WindowTitleItem *title;
int winBorderWidth; // Win平台的边框宽度
void *macEventMonitor; // MAC平台注册的事件监听器
void *macLastEvent; // MAC平台最近的事件
bool fakeClose;
public:
explicit WindowItem(QWindow *parent = nullptr);
~WindowItem() override;
/**
* 开始窗口拖拽, 无需指定Event, 内部直接采用最近的NativeEvent.
* 可用于OSX环境
*/
void startDrag();
/**
* 挂载标题栏, 如果重复操作则覆盖旧的标题栏
* @param item 标题栏元素
*/
void setTitleBar(WindowTitleItem *item);
/**
* 响应QT事件, 某些系统在适应分辨率变化时需要监听此消息
* @return 是否已处理
*/
bool event(QEvent *event) override;
/**
* 响应系统原生事件, 某些系统需要处理native消息
* @return 是否已处理
*/
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
bool isFakeClose() { return this->fakeClose; }
void setFakeClose(bool fakeClose) { this->fakeClose = fakeClose; }
Q_SIGNALS:
/**
* 窗口关闭消息
* @param close
*/
void closing(QQuickCloseEvent *close);
};
#endif //UILIB_WINDOWITEM_H
<file_sep>//
// Created by sulin on 2017/11/21.
//
#include <QQmlEngine>
#include "ui_property.h"
PropertyNode::PropertyNode(QString &name, PropertyNode *parent) : QObject(parent) {
this->nodeName = name;
this->metadata = nullptr;
this->parentNode = parent;
this->fields = QMap<QString, Field>();
this->methods = QMap<QString, Method>();
this->subNodes = QMap<QString, PropertyNode *>();
}
const QMetaObject *PropertyNode::metaObject() const {
return this->metadata;
}
// 处理属性回调的关键函数
int PropertyNode::qt_metacall(QMetaObject::Call call, int v, void **args) {
if (call == QMetaObject::ReadProperty) {
void *ret = args[0];
QMetaProperty prop = metaObject()->property(v);
qDebug() << "before read property" << prop.name() << "with type " << prop.type();
if (subNodes.contains(prop.name())) {
qDebug() << "enter subnode to read property" << prop.name();
*reinterpret_cast< PropertyNode **>(ret) = subNodes[prop.name()];
} else if (fields.contains(prop.name())) {
qDebug() << "execute read property" << prop.name();
fields[prop.name()].reader(ret);
qDebug() << "finish read property" << prop.name();
} else {
qWarning() << "invalid ReadProperty operate:" << v;
}
} else if (call == QMetaObject::WriteProperty) {
void *arg = args[0];
QMetaProperty prop = metaObject()->property(v);
qDebug() << "before write property" << prop.name() << "with type " << prop.type();
if (fields.contains(prop.name())) {
qDebug() << "execute write property" << prop.name();
fields[prop.name()].writer(arg);
qDebug() << "finish write property" << prop.name();
} else {
qWarning() << "invalid WriteProperty operate:" << v;
}
} else if (call == QMetaObject::InvokeMetaMethod) {
QMetaMethod prop = metaObject()->method(v);
qDebug() << "before call method " << prop.name();
if (methods.contains(prop.name())) {
auto method = methods[prop.name()];
QVariantList argList;
for (int i = 1; i <= method.argNum; i++) {
argList.append((*static_cast<QJSValue *>(args[i])).toVariant());
}
if (prop.parameterCount() == method.argNum) {
qDebug() << "sync call method " << prop.name();
QVariant ret;
method.callback(ret, argList);
qDebug() << "finish call method " << prop.name();
*reinterpret_cast< QVariant *>(args[0]) = ret;
qDebug() << "return result of method " << prop.name();
} else {
qDebug() << "async call method - " << prop.name();
auto callback = static_cast<QJSValue *>(args[method.argNum + 1]);
if (callback != nullptr && callback->isCallable()) {
qDebug() << "async call method done - " << prop.name();
QtConcurrent::run(method, &Method::asyncInvoke, argList, new QJSValue(*callback));
} else {
qWarning() << "invalid InvokeMetaMethod arguments.";
}
}
} else {
qWarning() << "invalid InvokeMetaMethod operate: " << v;
}
} else {
qWarning() << "invalid metacall " << int(call) << "," << v;
}
return 0;
}
// 这个函数用于类型转换, 其实没有用
void *PropertyNode::qt_metacast(const char *str){
return QObject::qt_metacast(str);
}
// 通知属性更新, val其实没有用
bool PropertyNode::notifyProperty(QString &name, QVariant &val) {
QString rest;
if (name.contains(".")) {
rest = name.midRef(name.indexOf(".") + 1).toString();
name = name.midRef(0, name.indexOf(".")).toString();
}
if (rest.size() > 0) {
if (!subNodes.contains(name)) {
qWarning() << "key invalid: " << name;
return false;
}
return subNodes[name]->notifyProperty(rest, val);
}
if (!fields.contains(name)) {
qWarning() << "key invalid: " << name;
return false;
}
auto meta = metaObject();
int propIndex = meta->indexOfProperty(qPrintable(name));
if (propIndex == -1) {
qWarning() << "notify-property-change-FAIL, property not exist: ", name;
return false;
}
QMetaProperty prop = meta->property(propIndex);
if (prop.notifySignalIndex() == -1) {
qWarning() << "notify-property-change-FAIL, property hasn't notify: ", name;
return false;
}
void *args[] = {nullptr, &val}; // out, in
QMetaObject::activate(this, meta, prop.notifySignalIndex() - meta->methodOffset(), args);
return true;
}
// 新增属性
bool PropertyNode::addProperty(QString &name, Type type, void *v) {
if (metadata != nullptr) {
qWarning() << "Property freeze";
return false;
}
QString rest;
if (name.contains(".")) {
rest = name.midRef(name.indexOf(".") + 1).toString();
name = name.midRef(0, name.indexOf(".")).toString();
}
if (fields.contains(name) || methods.contains(name)) {
qWarning() << "key existed allready: " << name;
return false;
}
if (rest.size() == 0) {
if (type == Type::FIELD) {
auto prop = static_cast<Field *>(v);
prop->name = name;
fields.insert(name, *prop);
} else if (type == Type::METHOD) {
auto method = static_cast<Method *>(v);
method->name = name;
methods.insert(name, *method);
}
return true;
}
if (!subNodes.contains(name)) {
subNodes.insert(name, new PropertyNode(name, this));
}
return subNodes[name]->addProperty(rest, type, v);
}
// 构建节点元数据, 不需要处理子节点
PropertyNode *PropertyNode::buildMetaData() {
QMetaObjectBuilder builder;
builder.setClassName("UIClassProxy");
builder.setSuperClass(&QObject::staticMetaObject);
for (auto field : fields) {
auto typeName = QVariant::typeToName(field.type);
auto signal = builder.addSignal(qPrintable(field.name + "Changed(" + typeName + ")"));
signal.setParameterNames(QList<QByteArray>{field.name.toLocal8Bit()});
auto propBuilder = builder.addProperty(field.name.toLocal8Bit(), typeName);
propBuilder.setReadable(field.reader != nullptr);
propBuilder.setWritable(field.writer != nullptr);
propBuilder.setNotifySignal(signal);
}
for (auto method : methods) {
auto name = method.name.toLocal8Bit();
// sync
QStringList args;
for (int i = 0; i < method.argNum; ++i) {
args.append("QJSValue");
}
QMetaMethodBuilder syncMethodBuilder = builder.addMethod(name + "(" + args.join(',').toLocal8Bit() + ")");
syncMethodBuilder.setAccess(QMetaMethod::Public);
syncMethodBuilder.setReturnType("QVariant");
// async
args.append("QJSValue");
QMetaMethodBuilder asyncMethodBuilder = builder.addMethod(name + "(" + args.join(',').toLocal8Bit() + ")");
asyncMethodBuilder.setAccess(QMetaMethod::Public);
asyncMethodBuilder.setReturnType("QVariant");
}
for (auto node : subNodes) {
auto propBuilder = builder.addProperty(node->nodeName.toLocal8Bit(), QVariant::typeToName(QMetaType::QObjectStar));
propBuilder.setConstant(true); // avoid the warning of "depends on non-NOTIFYable properties"
propBuilder.setReadable(true);
propBuilder.setWritable(false);
node->buildMetaData();
}
this->metadata = builder.toMetaObject();
return this;
}
// 事件处理, 用于回调JS, 必须在main-event-loop中执行
bool PropertyNode::event(QEvent *event) {
if (event->type() == QEvent::User) { // TODO If callback was deleted by GC, would this code crash?
auto e = dynamic_cast<Event *>(event);
auto engine = e->callback->engine();
e->callback->call({engine->toScriptValue(*e->data)});
}
return QObject::event(event);
}
<file_sep>#include <QQuickView>
#include <QGuiApplication>
#include <qtwebengineglobal.h>
#include <QQmlApplicationEngine>
#include "frameless.h"
#include "filter.h"
#include "MyWindow.h"
#include "item_title.h"
int main(int argc, char *argv[]) {
QGuiApplication a(argc, argv);
qSetMessagePattern("%{time yyyy-MM-dd hh:mm:ss} [%{type}] : %{message}");
QtWebEngine::initialize();
QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
// qputenv("QML_DISABLE_DISK_CACHE", "true");
qputenv("QSG_RENDER_LOOP", "basic"); // 在frameless的窗口中, 必须设置这个环境变量, 才能避免webengine假死
// QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
// auto w = new QQuickView();
// w->setSource(QUrl("/Users/sulin/workspace/shareit/client-shell/test/qml/main1.qml"));
// w->setWidth(900);
// w->setHeight(720);
// w->show();
// w->installEventFilter(new Filter(w));
// init_no_title(*w);
qmlRegisterType<MyWindow>("UILib", 1, 0, "Window");
qmlRegisterType<TitleItem>("UILib", 1, 0, "TitleBar");
auto engine = new QQmlApplicationEngine();
engine->load("/Users/sulin/workspace/shareit/client-shell/test/qml/Window.qml");
return a.exec();
}
<file_sep>//
// Created by sulin on 2019/4/7.
//
#include <QClipboard>
#include <QPainter>
#include <QPrinter>
#include <QPrintDialog>
#include <QImage>
#include <QDebug>
#include "goxui.h"
#include "goxui_print_p.h"
void Printer::print(QVariant data){
QImage img = qvariant_cast<QImage>(data);
QPrinter printer;
QPrintDialog dialog(&printer, nullptr);
if(dialog.exec() == QDialog::Accepted) {
QPainter painter(&printer);
painter.drawImage(QPoint(0,0), img);
painter.end();
}
}
// exec init
API void ui_init_print() {
Printer* printer = new Printer();
ui_add_object(const_cast<char *>("printer"), printer);
}
<file_sep>TARGET = fulltest
TEMPLATE = app
QT += widgets qml quick concurrent core-private printsupport webengine
SOURCES += main.c
win32:CONFIG(release, debug|release): LIBS += -L$$OUT_PWD/../../goxui-web/release/ -lgoxui-web
else:win32:CONFIG(debug, debug|release): LIBS += -L$$OUT_PWD/../../goxui-web/debug/ -lgoxui-web
else:unix: LIBS += -L$$OUT_PWD/../../goxui-web/ -lgoxui-web
INCLUDEPATH += $$PWD/../../goxui-web
DEPENDPATH += $$PWD/../../goxui-web
INCLUDEPATH += $$PWD/../../src
<file_sep>#ifndef ITEM_LOADER_H
#define ITEM_LOADER_H
#include <QObject>
#include <QQmlApplicationEngine>
#include <private/qquickloader_p.h>
class LoaderItem : public QQuickLoader {
Q_OBJECT
public:
static QQmlApplicationEngine* engine;
public:
explicit LoaderItem(QQuickItem *parent = nullptr);
void setSource(const QUrl &);
// Q_INVOKABLE void setSource(QQmlV4Function *v);
};
#endif // ITEM_LOADER_H
<file_sep>//
// Created by sulin on 2018/1/14.
//
#ifndef CLIENT_SHELL_MYWINDOW_H
#define CLIENT_SHELL_MYWINDOW_H
#include <QQuickWindow>
class MyWindow : public QQuickWindow {
Q_OBJECT
private:
qreal oldRatio;
public:
explicit MyWindow(QWindow *parent = nullptr);
/**
* 响应QT事件, 某些系统在适应分辨率变化时需要监听此消息
* @return 是否已处理
*/
bool event(QEvent *event) override;
/**
* 响应系统原生事件, 某些系统需要处理native消息
* @return 是否已处理
*/
bool nativeEvent(const QByteArray &eventType, void *message, long *result) override;
};
#endif //CLIENT_SHELL_MYWINDOW_H
<file_sep># 用于测试的辅助进程
add_executable(sample main.cpp)
target_link_libraries(sample PUBLIC goxui-gui)
<file_sep>//
// Created by sulin on 2017/11/21.
//
#ifndef UILIB_PROPERTY_H
#define UILIB_PROPERTY_H
#include <QObject>
#include <private/qmetaobjectbuilder_p.h>
#include <QJSValue>
#include <QVariant>
#include <QVariantList>
#include <QtConcurrent>
#include <QEvent>
#include <utility>
using Reader = std::function<void(void *ret)>;
using Writer = std::function<void(void *arg)>;
using Callback = std::function<void(QVariant &ret, QVariantList &arg)>;
// 通过异步事件处理JS回调
class Event : public QEvent {
public:
QVariant *data;
QJSValue *callback;
Event(QVariant *data, QJSValue *callback) : QEvent(QEvent::User) {
this->data = data;
this->callback = callback;
}
~Event() override {
delete this->data;
delete this->callback;
}
};
/**
* UI属性树中的一个节点, 可以在这个节点上挂载Property、Method、subNode等
*/
class PropertyNode : public QObject {
enum Type {
FIELD, METHOD
};
// UI中暴露的属性
struct Field {
QString name;
int type;
Reader reader;
Writer writer;
};
// UI中暴露的函数
struct Method {
QString name;
int argNum;
Callback callback;
PropertyNode *eventRecever;
void asyncInvoke(QVariantList &args, QJSValue *callback) {
auto ret = new QVariant();
this->callback(*ret, args);
QCoreApplication::postEvent(eventRecever, new Event(ret, callback));
}
};
private:
PropertyNode *parentNode;
QMetaObject *metadata;
QString nodeName;
QByteArray nodeClassName;
QMap<QString, Field> fields;
QMap<QString, Method> methods;
QMap<QString, PropertyNode *> subNodes;
public:
/**
* 属性节点的构造函数
* @param name 属性树中节点的名称
* @param parent 父节点, 可以是null
*/
PropertyNode(QString &name, PropertyNode *parent);
/**
* 获取元数据
* @return
*/
const QMetaObject *metaObject() const override;
/**
* 处理回调
* @return
*/
int qt_metacall(QMetaObject::Call, int, void **) override;
void *qt_metacast(const char *) override;
/**
* 构建元数据, 执行后此PropertyNode将被冻结, 不能再进行属性修改
*/
PropertyNode *buildMetaData();
bool event(QEvent *event) override;
public:
/**
* 增加属性
* @param name 属性名
* @param type 属性类型
* @param reader 读回调
* @param writer 写回调
* @return 是否新增成功
*/
bool addField(QString &name, int type, Reader &reader, Writer &writer) {
auto field = Field{name, type, reader, writer};
return this->addProperty(name, Type::FIELD, &field);
}
/**
* 增加函数
* @param name 函数名
* @param argNum 函数入参数量
* @return 是否新增成功
*/
bool addMethod(QString &name, int argNum, Callback &callback) {
auto method = Method{name, argNum, callback, this};
return this->addProperty(name, Type::METHOD, &method);
}
/**
* 通知属性更新, 使用者需要再次读取此属性的最新值
* @param name 属性名
* @param val 属性值
* @return 是否通知成功
*/
bool notifyProperty(QString &name, QVariant &val);
QByteArray &buildClassName();
private:
// 新增属性
bool addProperty(QString &name, Type propType, void *v);
};
#endif //UILIB_PROPERTY_H
<file_sep>//
// Created by sulin on 2017/9/30.
//
#include "item_title.h"
TitleItem::TitleItem(QQuickItem *parent) : QQuickItem(parent) {
setAcceptedMouseButtons(Qt::LeftButton);
this->setAcceptHoverEvents(true);
}
bool TitleItem::event(QEvent *event) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *e = dynamic_cast<QMouseEvent *>(event);
qDebug() << "event: " << event->type() << this->childAt(e->x(), e->y());
}
return QQuickItem::event(event);
}
//
//void TitleItem::mousePressEvent(QMouseEvent *e) {
// flag = true;
// fromX = e->globalX();
// fromY = e->globalY();
// fromWinX = window()->x();
// fromWinY = window()->y();
// setCursor(Qt::SizeAllCursor);
//}
//
//void TitleItem::mouseMoveEvent(QMouseEvent *e) {
// if (flag) {
// auto x = fromWinX + e->globalX() - fromX;
// auto y = fromWinY + e->globalY() - fromY;
// window()->setPosition(x, y);
// }
// QQuickItem::mouseMoveEvent(e);
//}
//
//void TitleItem::mouseReleaseEvent(QMouseEvent *e) {
// if (flag) {
// flag = false;
// unsetCursor();
// }
// QQuickItem::mouseReleaseEvent(e);
//}
//
//void TitleItem::mouseDoubleClickEvent(QMouseEvent *e) {
// QQuickItem::mouseDoubleClickEvent(e);
//}
<file_sep>//
// Created by sulin on 2017/9/23.
//
#include <QtGlobal>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQmlContext>
#include <QNetworkProxy>
#include <QFileDialog>
#include "singleapplication.h"
#include "goxui_p.h"
static PropertyNode *root = nullptr;
static QApplication *app = nullptr;
static QQmlApplicationEngine *engine = nullptr;
static QMap<QString, QObject*> contextProperties;
static void (*logCallback)(int type, char* file, int line, char* msg);
// log handler
void logHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
QByteArray localMsg = msg.toLocal8Bit();
if (logCallback != nullptr) {
char *file = const_cast<char*>(context.file);
int line = context.line;
logCallback(type, file, line, const_cast<char*>(msg.toLocal8Bit().data()));
return;
}
const char *file = context.file ? context.file : "";
const char *function = context.function ? context.function : "";
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
}
}
// init QT context
API void ui_init(int argc, char **argv) {
qInstallMessageHandler(logHandler);
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QLoggingCategory::defaultCategory()->setEnabled(QtMsgType::QtDebugMsg, true);
// For Qt5.9
if (QT_VERSION_MINOR != 12) {
qputenv("QSG_RENDER_LOOP", "basic");
QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software);
}
static QString NULL_Str;
static int argNum = argc;
if (isEnableSingleApplication()) {
app = new SingleApplication(argNum, argv);
if(static_cast<SingleApplication *>(app)->isSecondary() ) {
qDebug() << "app repeated";
app->exit(0);
}
} else {
app = new QApplication(argNum, argv);
}
// init ui
root = new PropertyNode(NULL_Str, nullptr);
qmlRegisterType<WindowItem>("Goxui", 1, 0, "Window");
qmlRegisterType<WindowTitleItem>("Goxui", 1, 0, "TitleBar");
qmlRegisterType<EventItem>("Goxui", 1, 0, "Event");
qmlRegisterType<HotKeyItem>("Goxui", 1, 0, "HotKey");
engine = new QQmlApplicationEngine();
}
// setup logger
API void ui_set_logger(void (*logger)(int type, char* file, int line, char* msg)){
logCallback = logger;
}
// Add an QObject into QML's context
API void ui_add_object(char *name, void *ptr) {
QString nameStr(name);
QObject *obj = static_cast<QObject *>(ptr);
contextProperties.insert(nameStr, obj);
}
// Add specified c field into QML
API int ui_add_field(char *name, int type, char *(*reader)(char *), void (*writer)(char *, char *)) {
QString nameStr(name);
Reader r = [=](void *ret) {
qDebug() << "invoke c getter of property" << name;
char *data = reader(name);
qDebug() << "invoke c getter of property" << name << "done, result is:" << data;
convertStrToPtr(data, type, ret);
qDebug() << "convert to ptr success";
// free(data); // memory leak???
};
Writer w = [=](void *arg) {
QByteArray tmp = convertPtrToStr(arg, type);
writer(name, tmp.toBase64().data());
};
switch (type) {
case UI_TYPE_BOOL:
return root->addField(nameStr, QVariant::Bool, r, w);
case UI_TYPE_INT:
return root->addField(nameStr, QVariant::Int, r, w);
case UI_TYPE_LONG:
return root->addField(nameStr, QVariant::LongLong, r, w);
case UI_TYPE_DOUBLE:
return root->addField(nameStr, QVariant::Double, r, w);
case UI_TYPE_OBJECT:
return root->addField(nameStr, QMetaType::QVariant, r, w);
default:
return root->addField(nameStr, QVariant::String, r, w);
}
}
// Add specified c method into QML
API int ui_add_method(char *name, int retType, int argNum, char *(*callback)(char *, char *)) {
QString nameStr(name);
Callback call = [=](QVariant &ret, QVariantList &args) {
auto param = QJsonDocument::fromVariant(args).toJson(QJsonDocument::Compact);
qDebug() << "invoke method" << name << "with param: " << param;
auto str = callback(name, param.toBase64().data());
qDebug() << "invoke method" << name << "finish with result: "<< str;
convertStrToVar(str, retType, ret);
// free(str); // memory leak???
};
return root->addMethod(nameStr, argNum, call);
}
// Notify QML that specified data has changed
API int ui_notify_field(char *name) {
QString nameStr(name);
QVariant var;
qDebug() << "field notify: " << name;
return root->notifyProperty(nameStr, var);
}
// Trige specified QML event by name
API void ui_trigger_event(char *name, int dataType, char *data) {
QString str(name);
QVariant var;
convertStrToVar(data, dataType, var);
qDebug() << "ui_trigger_event: " << str <<var;
for (auto item : EventItem::ReceverMap.values(str)) {
if (item == nullptr) {
continue;
}
item->notify(var);
}
}
// Add RCC data to QResource as specified prefix
API void ui_add_resource(char *prefix, char *data) {
QString rccPrefix(prefix);
auto rccData = reinterpret_cast<uchar *>(data);
QResource::registerResource(rccData, rccPrefix);
}
// Add file system path to QDir's resource search path
API void ui_add_resource_path(char *path) {
QString resPath(path);
QDir::addResourceSearchPath(resPath);
}
// Add file system path to QML import
API void ui_add_import_path(char *path) {
QString importPath(path);
engine->addImportPath(importPath);
}
// Map file system resource to specify QML prefix
API void ui_map_resource(char *prefix, char *path) {
QString resPrefix(prefix);
QString resPath(path);
QDir::addSearchPath(resPrefix, resPath);
}
// start Application
API int ui_start(char *qml) {
if (isEnableSingleApplication()) {
QObject::connect(static_cast<SingleApplication *>(app), &SingleApplication::instanceStarted, [=]() {
ui_trigger_event(const_cast<char*>("app_active"), UI_TYPE_VOID, nullptr);
});
}
QObject::connect(app, &QApplication::applicationStateChanged, [=](Qt::ApplicationState state){
if (state == Qt::ApplicationActive) {
ui_trigger_event(const_cast<char*>("app_active"), UI_TYPE_VOID, nullptr);
}
});
// setup root object
root->buildMetaData();
engine->rootContext()->setContextObject(root);
// setup context properties
contextProperties.insert("system", new UISystem(engine));
for(auto name : contextProperties.keys()) {
engine->rootContext()->setContextProperty(name, contextProperties.value(name));
}
// start~
QString rootQML(qml);
engine->load(rootQML);
int code = app->exec();
// clear
delete engine;
delete root;
return code;
}
// TOOL: setup the http proxy of Application
API void ui_tool_set_http_proxy(char *host, int port) {
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(host);
proxy.setPort(static_cast<quint16>(port));
QNetworkProxy::setApplicationProxy(proxy);
}
<file_sep>#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[]) {
QGuiApplication a(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl("/Users/sulin/workspace/shareit/client-shell/test/qml/Window.qml"));
return a.exec();
}
<file_sep>//
// Created by sulin on 2017/9/22.
//
#include "goxui.h"
int main(int argc, char *argv[]) {
ui_init(argc, argv);
ui_add_import_path(const_cast<char *>("/Users/sulin/workspace/go/src/shareit/desktop/browser/ui"));
return ui_start(const_cast<char *>("/Users/sulin/workspace/go/src/shareit/desktop/browser/ui/StartDev.qml"));
// return ui_start(const_cast<char *>("/Users/sulin/Development/Qt5/Examples/Qt-5.9.4/webengine/quicknanobrowser/BrowserWindow.qml"));
}
<file_sep>//
// Created by sulin on 2017/9/30.
//
#ifndef UILIB_WINDOWTITLE_H
#define UILIB_WINDOWTITLE_H
#include <QQuickItem>
#include <QQuickWindow>
class TitleItem : public QQuickItem {
Q_OBJECT
private:
bool flag = false;
int fromX, fromY, fromWinX, fromWinY;
public:
explicit TitleItem(QQuickItem *parent = Q_NULLPTR);
bool event(QEvent *event) override;
// void mousePressEvent(QMouseEvent *e) override;
//
// void mouseMoveEvent(QMouseEvent *event) override;
//
// void mouseReleaseEvent(QMouseEvent *e) override;
//
// void mouseDoubleClickEvent(QMouseEvent *e) override;
};
#endif //UILIB_WINDOWTITLE_H
<file_sep>//
// Created by sulin on 2018/1/12.
//
#ifndef UI_SYSTEM_H
#define UI_SYSTEM_H
#include <QVariant>
#include <QVariantMap>
#include <QObject>
#include <QDateTime>
#include <QQmlApplicationEngine>
/**
* 向UI暴露的系统工具API
*/
class UISystem : public QObject {
Q_OBJECT
QQmlApplicationEngine *engine;
public:
explicit UISystem(QQmlApplicationEngine *engine);
/**
* 清除QML组件缓存, 可用于强制刷新Loader
*/
Q_INVOKABLE void clearComponentCache();
/**
* 设置剪切板的内容
*/
Q_INVOKABLE void setClipboard(QString text);
/**
* exec保存文件的对话框, 此函数阻塞直至对话框结束
*/
Q_INVOKABLE QVariantMap execSaveFileDialog(QString defaultName, QStringList nameFilters);
};
#endif //UI_SYSTEM_H
<file_sep>//
// Created by sulin on 2018/1/10.
//
#ifndef CLIENT_SHELL_FILTER_H
#define CLIENT_SHELL_FILTER_H
#include <QObject>
#include <QEvent>
#include <QDebug>
#include <QQuickView>
#include "frameless.h"
class Filter : public QObject {
Q_OBJECT
private:
qreal old;
QQuickWindow *win;
public:
explicit Filter(QQuickWindow *win) : QObject(nullptr) {
this->win = win;
this->old = 0;
}
protected:
bool eventFilter(QObject *obj, QEvent *event) override {
qreal newRatio = win->devicePixelRatio();
if (old > 0 && old < 100 && win->devicePixelRatio() != old) {
qDebug() << "ratio changed: " << old << newRatio;
frameless_flush_ratio(win, newRatio);
}
old = newRatio;
return QObject::eventFilter(obj, event);
}
};
#endif //CLIENT_SHELL_FILTER_H
<file_sep>//
// Created by sulin on 2017/9/22.
//
#include <stdio.h>
#include <stdlib.h>
#include "goxui.h"
int main(int argc, char *argv[]) {
ui_init(argc, argv);
FILE *f = fopen("/Users/sulin/workspace/go/src/shareit/asserts/uilib.rcc", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); //same as rewind(f);
char *rccData = malloc((size_t) (fsize + 1));
fread(rccData, (size_t) fsize, 1, f);
fclose(f);
rccData[fsize] = 0;
ui_add_resource("/", rccData);
ui_map_resource("img", "/Users/sulin/workspace/go/src/shareit/asserts/static");
return ui_start(("/Users/sulin/workspace/shareit/client-shell/test/fulltest/qml/main.qml"));
}<file_sep>//
// Created by sulin on 2018/1/9.
//
#ifndef CLIENT_SHELL_ITEM_HOTKEY_H
#define CLIENT_SHELL_ITEM_HOTKEY_H
#include <QObject>
#include <QHotkey>
class HotKeyItem : public QObject {
Q_OBJECT
Q_PROPERTY(QString sequence READ getSequence WRITE setSequence)
private:
QString sequence;
QHotkey *hotkey;
public:
explicit HotKeyItem(QObject *parent = nullptr);
QString getSequence();
void setSequence(QString key);
~HotKeyItem();
private:
void releaseHotKey();
signals:
void activated();
};
#endif //CLIENT_SHELL_ITEM_HOTKEY_H
<file_sep>#include <windows.h>
#include <WinUser.h>
#include <windowsx.h>
#include <dwmapi.h>
#include <objidl.h>
#include <gdiplus.h>
#include <GdiPlusColor.h>
#pragma comment (lib, "Dwmapi.lib")
#pragma comment (lib, "user32.lib")
#include "item_window.h"
// 判断窗口是否已最大化
static bool isMaximized(HWND hwnd) {
WINDOWPLACEMENT placement;
if (!::GetWindowPlacement(hwnd, &placement))
return false;
return placement.showCmd == SW_MAXIMIZE;
}
// 调整最大化的窗口的client区域, 避免溢出屏幕
void adjust_maximized_client_rect(HWND window, RECT& rect) {
if (!isMaximized(window))
return;
auto monitor = ::MonitorFromWindow(window, MONITOR_DEFAULTTONULL);
if (!monitor)
return;
MONITORINFO monitor_info{};
monitor_info.cbSize = sizeof(monitor_info);
if (!::GetMonitorInfoW(monitor, &monitor_info))
return;
// 最大化时,只使用显示器可用区域,而不是整个窗口(最大化窗口frame会溢出)
rect = monitor_info.rcWork;
}
// 判断是否启用composition
bool composition_enabled() {
BOOL composition_enabled = FALSE;
bool success = ::DwmIsCompositionEnabled(&composition_enabled) == S_OK;
return composition_enabled && success;
}
// 计算指定控件内部FocusScope控件数量
static int focusNum(QQuickItem *item, QPointF &gpos) {
if (item == nullptr || !item->isEnabled() || !item->contains(item->mapFromGlobal(gpos))) {
return 0;
}
int num = item->acceptedMouseButtons() == Qt::LeftButton ? 0 : 1;
QList<QQuickItem *> children = item->childItems();
for (int i=0; i<children.size() && num <= 1; i++) {
num += focusNum(children[i], gpos);
}
return num;
}
// 初始化标题栏, 将自己挂载在窗口之上
WindowTitleItem::WindowTitleItem(QQuickItem *parent) : QQuickItem(parent){
this->setAcceptedMouseButtons(Qt::LeftButton);
QObject::connect(this, &QQuickItem::windowChanged, [=](QQuickWindow *w) {
if (WindowItem* window = dynamic_cast<WindowItem*>(w)) {
window->setTitleBar(this);
}
});
}
// 标题栏卸载
WindowTitleItem::~WindowTitleItem() {
if (this->window() == nullptr) {
return;
}
if (WindowItem* window = dynamic_cast<WindowItem*>(this->window())) {
window->setTitleBar(nullptr);
}
}
// 响应双击, 什么也不需要做
void WindowTitleItem::mouseDoubleClickEvent(QMouseEvent *e) {
QQuickItem::mouseDoubleClickEvent(e);
}
// 响应鼠标按下, 什么也不需要做
void WindowTitleItem::mousePressEvent(QMouseEvent *event) {
QQuickItem::mousePressEvent(event);
}
// 初始化窗口
WindowItem::WindowItem(QWindow *parent) : QQuickWindow(parent) {
this->setFlag(Qt::Window,true);
this->setFlag(Qt::FramelessWindowHint, true);
this->setFlag(Qt::WindowSystemMenuHint, true);
this->title = nullptr;
this->winBorderWidth = 5;
HWND hwnd = (HWND) this->winId();
LONG lStyle = GetWindowLong(hwnd, GWL_STYLE);
lStyle = (WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX);
SetWindowLong(hwnd, GWL_STYLE, lStyle);
LONG lExStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
SetWindowLong(hwnd, GWL_EXSTYLE, lExStyle);
}
// 窗口释放
WindowItem::~WindowItem() {
}
// 开始拖拽
void WindowItem::startDrag() {
}
// 挂载标题栏, 并根据标题栏来初始化 NSTitlebarAccessoryViewController
void WindowItem::setTitleBar(WindowTitleItem *item) {
this->title = item;
}
// 监听事件
bool WindowItem::event(QEvent *e) {
if (e->type() == QEvent::FocusIn || e->type() == QEvent::FocusOut) {
QRegion region(0, 0, width(), height());
QQuickWindow::exposeEvent(new QExposeEvent(region));
}
if (e->type() == QEvent::Close && this->fakeClose) {
this->hide();
return true;
}
return QQuickWindow::event(e);
}
// 原生事件的处理, mac貌似不支持
bool WindowItem::nativeEvent(const QByteArray &eventType, void *message, long *result) {
MSG* msg = (MSG *)message;
HWND hwnd = HWND(winId());
switch (msg->message) {
// 窗口重绘时处理client区域
case WM_NCCALCSIZE: {
*result = 0;
NCCALCSIZE_PARAMS* params = reinterpret_cast<NCCALCSIZE_PARAMS*>(msg->lParam);
adjust_maximized_client_rect(hwnd, params->rgrc[0]);
return true;
}
// Prevents window frame reappearing on window activation in "basic" theme, where no aero shadow is present.
case WM_NCACTIVATE: {
*result = 0;
if (!composition_enabled())
*result = 1;
return true;
}
// 判断当前坐标是标题栏、边框、系统按钮等
case WM_NCHITTEST:{
*result = 0;
RECT winrect;
GetWindowRect(hwnd, &winrect);
long x = GET_X_LPARAM(msg->lParam);
long y = GET_Y_LPARAM(msg->lParam);
// 判断是否在边框上, 支持resize
LONG border_width = this->winBorderWidth * devicePixelRatio();
if(border_width > 0) {
bool resizeWidth = minimumWidth() != maximumWidth();
bool resizeHeight = minimumHeight() != maximumHeight();
bool hitLeft = resizeWidth && x >= winrect.left && x < winrect.left + border_width;
bool hitRight = resizeWidth && x < winrect.right && x >= winrect.right - border_width;
bool hitTop = resizeHeight && y >= winrect.top && y < winrect.top + border_width;
bool hitBottom = resizeHeight && y < winrect.bottom && y >= winrect.bottom - border_width;
if (hitBottom && hitLeft)
*result = HTBOTTOMLEFT;
else if (hitBottom && hitRight)
*result = HTBOTTOMRIGHT;
else if (hitTop && hitLeft)
*result = HTTOPLEFT;
else if (hitTop && hitRight)
*result = HTTOPRIGHT;
else if (hitLeft)
*result = HTLEFT;
else if (hitRight)
*result = HTRIGHT;
else if (hitBottom)
*result = HTBOTTOM;
else if (hitTop)
*result = HTTOP;
}
// 判断是否是标题栏
if (0 == *result && title != nullptr) {
QPointF gpos = QPointF(x/devicePixelRatio(), y/devicePixelRatio());
if (focusNum(title, gpos) == 1) {
*result = HTCAPTION;
}
}
return 0 != *result;
}
default:
return QQuickWindow::nativeEvent(eventType, message, result);
}
}
<file_sep>#include <gio/gio.h>
#include <string.h>
#include <stdio.h>
// 禁用代理
int systool_set_proxy_disable() {
int ret = 0;
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
g_type_init(); // deprecated since version 2.36, must leave here or prior glib will crash
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
GSettings *setting = g_settings_new("org.gnome.system.proxy");
gboolean success = g_settings_set_string(setting, "mode", "none");
if (!success) {
ret = 99;
printf("set proxy mode failed. \n");
goto defer;
}
defer:
g_settings_sync();
g_object_unref(setting);
return ret;
}
// 设置PAC代理
int systool_set_proxy_pac(char *addr) {
int ret = 0;
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
g_type_init(); // deprecated since version 2.36, must leave here or prior glib will crash
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
GSettings *setting = g_settings_new("org.gnome.system.proxy");
gboolean success = g_settings_set_string(setting, "mode", "auto");
if (!success) {
ret = 99;
printf("set proxy mode failed. \n");
goto defer;
}
success = g_settings_set_string(setting, "autoconfig-url", addr);
if (!success) {
ret = 99;
printf("set proxy pac failed. \n");
goto defer;
}
defer:
g_settings_sync();
g_object_unref(setting);
return ret;
}
// 设置Socks5代理
int systool_set_proxy_socks(char *host, int port) {
int ret = 0;
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
g_type_init(); // deprecated since version 2.36, must leave here or prior glib will crash
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
GSettings *setting = g_settings_new("org.gnome.system.proxy");
GSettings *sockSetting = g_settings_new("org.gnome.system.proxy.socks");
gboolean success = g_settings_set_string(setting, "mode", "manual");
if (!success) {
ret = 99;
printf("set proxy mode failed. \n");
goto defer;
}
success = g_settings_set_string(sockSetting, "host", host);
if (!success) {
ret = 99;
printf("set proxy socks host failed. \n");
goto defer;
}
success = g_settings_set_int(sockSetting, "port", port);
if (!success) {
ret = 99;
printf("set proxy socks port failed. \n");
goto defer;
}
defer:
g_settings_sync();
g_object_unref(setting);
g_object_unref(sockSetting);
return ret;
}
// 查询系统代理
char *systool_get_proxy() {
char *ret = "unknown";
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
g_type_init(); // deprecated since version 2.36, must leave here or prior glib will crash
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
GSettings *setting = g_settings_new("org.gnome.system.proxy");
char *mode = g_settings_get_string(setting, "mode");
if (strcmp(mode, "none") == 0) {
ret = "";
}
if (strcmp(mode, "auto") == 0) {
char *addr = g_settings_get_string(setting, "autoconfig-url");
if (addr != 0) {
ret = addr;
}
}
if (strcmp(mode, "manual") == 0) {
static char buf[96]; // not thread safe
GSettings *sockSetting = g_settings_new("org.gnome.system.proxy.socks");
char *host = g_settings_get_string(sockSetting, "host");
int port = g_settings_get_int(sockSetting, "port");
if (host != 0) {
sprintf(buf, "%s:%d", host, port);
ret = buf;
}
g_object_unref(sockSetting);
}
g_object_unref(setting);
return ret;
}
int main(int argc, char *argv[]) {
printf("PROXY: %s \n", systool_get_proxy());
systool_set_proxy_disable();
printf("PROXY: %s \n", systool_get_proxy());
systool_set_proxy_pac("http://localhost:9090/ddd.pac");
printf("PROXY: %s \n", systool_get_proxy());
systool_set_proxy_socks("localhost", 8009);
printf("PROXY: %s \n", systool_get_proxy());
systool_set_proxy_disable();
printf("PROXY: %s \n", systool_get_proxy());
return 0;
}<file_sep>//
// Created by sulin on 2017/9/22.
//
//#include <printf.h>
#include <cstring>
#include <cstdlib>
#include <QString>
#include <QTimer>
#include <QJsonDocument>
#include <QVariant>
#include "goxui.h"
int flag = 1;
int getFlag(char *name) {
printf("getFlag..... \n");
return flag;
}
void setFlag(char *name, int v) {
printf("setFlag..... \n");
flag = v;
}
int getNumber(char *name) {
printf("getNumber..... \n");
return 111;
}
void setNumber(char *name, int v) {
printf("setNumber..... \n");
}
double getF(char *name) {
printf("getF..... \n");
return 0.222;
}
void setF(char *name, double f) {
printf("setF..... \n");
}
char *getString(char *name) {
auto *result = (char *) malloc(sizeof(char) * 10);
strcpy(result, "!!!!!!!!!!");
printf("getString..... \n");
return result;
}
void setString(char *name, char *v) {
printf("setString..... \n");
}
char *callback(char *name, char *data) {
auto *result = (char *) malloc(sizeof(char) * 10);
strcpy(result, "1234567890");
printf("callback: %s\n", data);
return result;
}
int main(int argc, char *argv[]) {
ui_init(argc, argv);
// ui_setup_dump(const_cast<char *>("/Users/sulin/"));
ui_map_resource(const_cast<char *>("img"),
const_cast<char *>("/Users/sulin/workspace/go/src/shareit/asserts/images"));
printf("start...\n");
printf("%s \n", QJsonDocument::fromVariant(QVariant::fromValue(12233)).toJson(QJsonDocument::Compact).data());
printf("%s \n", QJsonDocument::fromVariant(QVariant::fromValue(333.22)).toJson(QJsonDocument::Compact).data());
printf("%s \n",
QJsonDocument::fromVariant(QVariant::fromValue(QString("fsdfsd"))).toJson(QJsonDocument::Compact).data());
// ui_add_field_bool(const_cast<char *>("flag"), getFlag, setFlag);
// ui_add_field_int(const_cast<char *>("number"), getNumber, setNumber);
// ui_add_field_double(const_cast<char *>("real"), getF, setF);
// ui_add_field_string(const_cast<char *>("str"), getString, setString);
// ui_add_method(const_cast<char *>("RequestApi"), callback);
// ui_add_field_string(const_cast<char *>("agentPort"), getString, setString);
// ui_add_field_string(const_cast<char *>("agentRoles"), getString, setString);
auto timer = new QTimer();
QObject::connect(timer, &QTimer::timeout, []() {
auto name = const_cast<char *>("consoleUpdate");
auto body = const_cast<char *>("{\"role\":\"test\",\"host\":\"www.baidu.com\",\"agent\":\"nil\",\"time\":\"00:00:00\"}");
ui_trigger_event(name, UI_TYPE_OBJECT, body);
});
timer->start(3000);
// ui_sys_tool_set_proxy(0, nullptr);
return ui_start(const_cast<char *>("/Users/sulin/workspace/go/src/shareit/asserts/main.qml"));
}<file_sep>#ifndef GOXUI_P_H
#define GOXUI_P_H
#include <QVariant>
#include <QJsonDocument>
#include <QQmlApplicationEngine>
#include "item/item_hotkey.h"
#include "item/item_window.h"
#include "item/item_event.h"
#include "core/ui_system.h"
#include "core/ui_property.h"
#include "goxui.h"
// check whether enable single-application or not
inline bool isEnableSingleApplication() {
return qgetenv("GOXUI_SINGLE_APPLICATION") == "1";
}
// convert string data to specified type
inline void convertStrToVar(char *data, int type, QVariant &ptr) {
QByteArray array(data);
switch (type) {
case UI_TYPE_VOID:
break;
case UI_TYPE_BOOL:
ptr.setValue(array == "0" || array.toLower() == "true");
break;
case UI_TYPE_INT:
ptr.setValue(array.toInt());
break;
case UI_TYPE_LONG:
ptr.setValue(array.toLongLong());
break;
case UI_TYPE_DOUBLE:
ptr.setValue(array.toDouble());
break;
case UI_TYPE_OBJECT:
ptr.setValue(QJsonDocument::fromJson(array).toVariant());
break;
default:
ptr.setValue(QString(array));
}
}
// 将字符串转换为指定类型的变量, 并赋值给指定指针
inline void convertStrToPtr(char *data, int type, void *ptr) {
QByteArray array(data);
switch (type) {
case UI_TYPE_BOOL:
*reinterpret_cast< bool *>(ptr) = array == "0" || array.toLower() == "true";
break;
case UI_TYPE_INT:
*reinterpret_cast< qint32 *>(ptr) = array.toInt();
break;
case UI_TYPE_LONG:
*reinterpret_cast< qint64 *>(ptr) = array.toLongLong();
break;
case UI_TYPE_DOUBLE:
*reinterpret_cast< double *>(ptr) = array.toDouble();
break;
case UI_TYPE_OBJECT:
*reinterpret_cast< QVariant *>(ptr) = QJsonDocument::fromJson(array).toVariant();
break;
default:
*reinterpret_cast< QString *>(ptr) = QString(data);
}
}
// 将指针按照指定类型格式化为字符串
inline QByteArray convertPtrToStr(void *arg, int type) {
QByteArray result;
switch (type) {
case UI_TYPE_BOOL:
result.setNum(*reinterpret_cast< bool *>(arg));
break;
case UI_TYPE_INT:
result.setNum(*reinterpret_cast< qint32 *>(arg));
break;
case UI_TYPE_LONG:
result.setNum(*reinterpret_cast< qint64 *>(arg));
break;
case UI_TYPE_DOUBLE:
result.setNum(*reinterpret_cast< double *>(arg));
break;
case UI_TYPE_OBJECT:
result.append(QJsonDocument::fromVariant(*reinterpret_cast< QVariant *>(arg)).toJson(QJsonDocument::Compact).data());
break;
default:
result.append(*reinterpret_cast< QString *>(arg));
}
return result;
}
#endif // GOXUI_P_H
<file_sep>//
// Created by sulin on 2017/10/6.
//
#include "item_event.h"
QMultiMap<QString, EventItem *> EventItem::ReceverMap;
EventItem::EventItem(QObject *parent) : QObject(parent) {
ReceverMap.insert(key, this);
}
EventItem::~EventItem() {
ReceverMap.remove(key, this); // Is this thread safe?
}
void EventItem::notify(QVariant &data) {
emit this->active(data);
}
<file_sep># 用于测试的辅助进程
IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
include_directories(/usr/include/glib-2.0)
include_directories(/usr/lib/x86_64-linux-gnu/glib-2.0/include/)
add_executable(systest linux.c)
target_link_libraries(systest gio-2.0 gobject-2.0 glib-2.0)
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")
IF (WIN32)
add_executable(systest windows.c)
target_link_libraries(systest wininet)
ENDIF (WIN32)
IF (APPLE)
add_executable(systest mac.c)
target_link_libraries(systest)
ENDIF (APPLE)
<file_sep>cmake_minimum_required(VERSION 3.5.0)
project(qttest)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_AUTOMOC ON)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC Qt5::Qml Qt5::Quick)
<file_sep>//
// Created by sulin on 2018/1/12.
//
#include <QClipboard>
#include <QWindow>
#include <QApplication>
#include <QNetworkProxy>
#include <QFileDialog>
#include <QDebug>
#include <QUrlQuery>
#include "ui_system.h"
UISystem::UISystem(QQmlApplicationEngine *engine) : QObject(engine) {
this->engine = engine;
}
void UISystem::clearComponentCache() {
engine->clearComponentCache();
}
void UISystem::setClipboard(QString text) {
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText(text);
}
QVariantMap UISystem::execSaveFileDialog(QString defaultName, QStringList nameFilters){
QVariantMap result;
QFileDialog dialog;
dialog.setAcceptMode(QFileDialog::AcceptSave);
dialog.setDefaultSuffix("html");
dialog.selectFile(defaultName);
dialog.setNameFilters(nameFilters);
result["accept"] = dialog.exec();
result["file"] = dialog.selectedFiles();
result["nameFilter"] = dialog.selectedNameFilter();
return result;
}
<file_sep>#include "item/item_loader.h"
QQmlApplicationEngine *LoaderItem::engine = nullptr;
LoaderItem::LoaderItem(QQuickItem *parent) : QQuickLoader (parent) {
}
void LoaderItem::setSource(const QUrl &src) {
QQuickLoader::setSource (QUrl(""));
if (LoaderItem::engine) {
LoaderItem::engine->trimComponentCache();
}
QQuickLoader::setSource (src);
}
//void LoaderItem::setSource(QQmlV4Function *v) {
// QQuickLoader::setSource (QUrl(""));
// if (LoaderItem::engine) {
// LoaderItem::engine->trimComponentCache();
// }
// QQuickLoader::setSource (v);
//}
<file_sep>QT += webengine widgets qml quick concurrent core-private
TARGET = webengine-test
TEMPLATE = app
SOURCES += main.cpp
#LIBS += -framework Cocoa
#LIBS += -framework Carbon
LIBS += -L$$OUT_PWD/../../goxui-web/ -lgoxui-web
INCLUDEPATH += $$PWD/../../goxui-web
DEPENDPATH += $$PWD/../../goxui-web
INCLUDEPATH += $$PWD/../../src
<file_sep>cmake_minimum_required(VERSION 3.5.0)
project(frameless-test)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_AUTOMOC ON)
IF (WIN32)
endif (WIN32)
if (APPLE)
add_definitions("-x objective-c++")
add_executable(${PROJECT_NAME} main.cpp filter.h MyWindow.cpp item_title.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC Qt5::Qml Qt5::Quick Qt5::WebEngine frameless "-framework Cocoa")
endif (APPLE)
<file_sep># 用于测试的辅助进程
add_executable(rcctest main.c)
target_link_libraries(rcctest PUBLIC goxui-gui)
<file_sep>#include <stdlib.h>
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
static unsigned long _n_size = sizeof(INTERNET_PER_CONN_OPTION_LIST);
// 执行设置
int _do_set(INTERNET_PER_CONN_OPTION_LIST *list) {
if (!InternetSetOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, list, _n_size)) {
return 90;
}
if (!InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0)) {
return 91;
}
if (!InternetSetOption(NULL, INTERNET_OPTION_REFRESH, NULL, 0)) {
return 92;
}
return 0;
}
// 设置Socks代理
int systool_set_proxy_socks(char *addr) {
INTERNET_PER_CONN_OPTION_LIST list;
INTERNET_PER_CONN_OPTION option[3];
option[0].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
option[0].Value.pszValue = (LPSTR) addr;
option[1].dwOption = INTERNET_PER_CONN_FLAGS;
option[1].Value.dwValue = PROXY_TYPE_PROXY | PROXY_TYPE_DIRECT;
option[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS;
option[2].Value.pszValue = "<local>";
list.dwSize = _n_size;
list.pszConnection = NULL;
list.dwOptionCount = 3;
list.dwOptionError = 0;
list.pOptions = option;
return _do_set(&list);
}
// 设置PAC代理
int systool_set_proxy_pac(char *pacUrl) {
INTERNET_PER_CONN_OPTION option[2];
option[0].dwOption = INTERNET_PER_CONN_FLAGS;
option[0].Value.dwValue = PROXY_TYPE_AUTO_PROXY_URL;
option[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
option[1].Value.pszValue = pacUrl;
INTERNET_PER_CONN_OPTION_LIST list;
list.dwSize = _n_size;
list.pszConnection = NULL;
list.dwOptionCount = 2;
list.dwOptionError = 0;
list.pOptions = option;
return _do_set(&list);
}
// 禁用系统代理
int systool_set_proxy_disable() {
INTERNET_PER_CONN_OPTION option[2];
option[0].dwOption = INTERNET_PER_CONN_FLAGS;
option[0].Value.dwValue = PROXY_TYPE_DIRECT;
option[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
option[1].Value.pszValue = "";
INTERNET_PER_CONN_OPTION_LIST list;
list.dwSize = _n_size;
list.pszConnection = NULL;
list.dwOptionCount = 2;
list.dwOptionError = 0;
list.pOptions = option;
return _do_set(&list);
}
// 查询Windows系统代理设置
char *systool_get_proxy_pac() {
unsigned long nSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
INTERNET_PER_CONN_OPTION_LIST List;
INTERNET_PER_CONN_OPTION Option[3];
Option[0].dwOption = INTERNET_PER_CONN_FLAGS;
Option[1].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL;
Option[2].dwOption = INTERNET_PER_CONN_PROXY_SERVER;
List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST);
List.pszConnection = NULL;
List.dwOptionCount = 3;
List.dwOptionError = 0;
List.pOptions = Option;
if (!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, &List, &nSize)) {
printf("InternetQueryOption failed! (%ld)\n", GetLastError());
return 0;
}
DWORD isPac = Option[0].Value.dwValue & PROXY_TYPE_AUTO_PROXY_URL;
DWORD isSocks = Option[0].Value.dwValue & PROXY_TYPE_PROXY;
if (isPac != 0) {
return Option[1].Value.pszValue; // PAC模式
} else if (isSocks != 0) {
return Option[2].Value.pszValue; // Socks模式
}
return "";
}
int main(int argc, char **argv) {
if (systool_set_proxy_socks("localhost:8888") != 0) {
return 99;
}
if (systool_set_proxy_pac("http://localhost:9000/test.pac") != 0) {
return 99;
}
if (systool_set_proxy_disable() != 0) {
return 99;
}
printf("TTT: %s", systool_get_proxy_pac());
}
<file_sep># 用于测试的辅助进程
set(NAME WebEngineTest)
add_executable(${NAME} main.cpp)
target_link_libraries(${NAME} PUBLIC goxui-web)
<file_sep>//
// Created by sulin on 2017/9/22.
//
//#include <printf.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "goxui.h"
char *bflag = "true";
char *rootInt = "123";
char *rootLong = "2333";
char *rootBodyReal = "0.114";
char *rootStr = "hello";
char *getFlag(char *name) {
char *result = (char *) malloc(strlen(bflag));
strcpy(result, bflag);
return result;
}
void setFlag(char *name, char *v) {
bflag = (char *) malloc(strlen(v)); // 会有内存泄漏
strcpy(bflag, v);
printf("setFlag: %s, %s\n", v, bflag);
ui_notify_field(name);
ui_trigger_event("event_bool", UI_TYPE_BOOL, v);
}
char *getNumber(char *name) {
char *result = (char *) malloc(strlen(rootInt));
strcpy(result, rootInt);
return result;
}
void setNumber(char *name, char *v) {
rootInt = (char *) malloc(strlen(v)); // 会有内存泄漏
strcpy(rootInt, v);
printf("setNumber: %s, %s\n", v, rootInt);
ui_notify_field(name);
ui_trigger_event("event_int", UI_TYPE_INT, v);
}
char *getLong(char *name) {
char *result = (char *) malloc(strlen(rootLong));
strcpy(result, rootLong);
return result;
}
void setLong(char *name, char *v) {
rootLong = (char *) malloc(strlen(v)); // 会有内存泄漏
strcpy(rootLong, v);
printf("setLong: %s, %s\n", v, rootLong);
ui_notify_field(name);
ui_trigger_event("event_long", UI_TYPE_LONG, v);
}
char *getDouble(char *name) {
char *result = (char *) malloc(strlen(rootBodyReal));
strcpy(result, rootBodyReal);
return result;
}
void setDouble(char *name, char *v) {
rootBodyReal = (char *) malloc(strlen(v)); // 会有内存泄漏
strcpy(rootBodyReal, v);
printf("setDouble: %s, %s\n", v, rootBodyReal);
ui_notify_field(name);
ui_trigger_event("event_double", UI_TYPE_DOUBLE, v);
}
char *getString(char *name) {
char *result = (char *) malloc(strlen(rootStr));
strcpy(result, rootStr);
return result;
}
void setString(char *name, char *v) {
rootStr = (char *) malloc(sizeof(v)); // 会有内存泄漏
strcpy(rootStr, v);
printf("setString: %s, %s\n", v, rootStr);
ui_notify_field(name);
ui_trigger_event("event_string", UI_TYPE_STRING, v);
}
char *callback(char *name, char *param) {
char *result = (char *) malloc(sizeof(char) * 10);
strcpy(result, "1234567890");
printf("callback: %s\n", param);
return result;
}
char *callback2(char *name, char *param) {
char *result = (char *) malloc(sizeof(char) * 4);
strcpy(result, "true");
printf("callback2: %s\n", param);
return result;
}
char *callback3(char *name, char *param) {
char *tmp = "{\"name\":\"test\",\"sub\":{\"age\":1.88}}";
char *result = (char *) malloc(strlen(tmp));
strcpy(result, tmp);
printf("callback3: %s, %s\n", param, result);
ui_trigger_event("event_object", UI_TYPE_OBJECT, tmp);
return result;
}
char *callback4(char *name, char *param) {
char *tmp = "[{\"name\":\"test\",\"sub\":{\"age\":1.88}}]";
char *result = (char *) malloc(strlen(tmp));
strcpy(result, tmp);
printf("callback4: %s, %s\n", param, result);
ui_trigger_event("event_array", UI_TYPE_OBJECT, tmp);
return result;
}
int main(int argc, char *argv[]) {
ui_init(argc, argv);
ui_add_field("Flag", UI_TYPE_BOOL, getFlag, setFlag);
ui_add_field("Root.number", UI_TYPE_INT, getNumber, setNumber);
ui_add_field("Root.number2", UI_TYPE_LONG, getLong, setLong);
ui_add_field("Root.body.real", UI_TYPE_DOUBLE, getDouble, setDouble);
ui_add_field("Root.str", UI_TYPE_STRING, getString, setString);
ui_add_method(("Test"), UI_TYPE_DOUBLE, 2, callback);
ui_add_method(("Root.Test0"), UI_TYPE_INT, 2, callback);
ui_add_method(("Root.Test1"), UI_TYPE_LONG, 2, callback);
ui_add_method(("Root.Test2"), UI_TYPE_VOID, 2, callback);
ui_add_method(("Root.Test"), UI_TYPE_BOOL, 3, callback2);
ui_add_method(("Root.Body.Test"), UI_TYPE_OBJECT, 3, callback3);
ui_add_method(("Root.Body.Test1"), UI_TYPE_OBJECT, 3, callback4);
// return ui_start(("/home/sulin/workspace/client-shell/test/fulltest/qml/main.qml"));
// return ui_start(("/Users/sulin/workspace/shareit/client-shell/test/fulltest/qml/main.qml"));
return ui_start("Z:\\sulin\\workspace\\go\\src\\github.com\\sisyphsu\\goxui\\cbridge\\test\\fulltest\\qml\\main.qml");
// return ui_start("/Users/sulin/workspace/go/src/github.com/sisyphsu/goxui/cbridge/test/fulltest/qml/main.qml");
}
<file_sep>//
// Created by sulin on 2017/10/6.
//
#ifndef UILIB_CONNECT_H
#define UILIB_CONNECT_H
#include <QObject>
#include <QArgument>
#include <QJSValue>
#include <QMultiMap>
#include <utility>
#include <QVariant>
class EventItem : public QObject {
Q_OBJECT
Q_PROPERTY(QString key READ getKey WRITE setKey)
Q_PROPERTY(bool enable MEMBER enable)
public:
static QMultiMap<QString, EventItem *> ReceverMap;
private:
QString key;
bool enable;
public:
explicit EventItem(QObject *parent = Q_NULLPTR);
~EventItem() override;
QString getKey() {
return key;
}
void setKey(QString key) {
ReceverMap.remove(this->key, this);
this->key = std::move(key);
ReceverMap.insert(this->key, this);
}
void notify(QVariant &data);
signals:
void active(QVariant data);
};
#endif //UILIB_CONNECT_H
<file_sep>//
// Created by sulin on 2019/4/7.
//
#ifndef GOXUI_PRINT_P_H
#define GOXUI_PRINT_P_H
#include <QVariant>
#include <QVariantMap>
#include <QObject>
/**
* 向UI暴露的系统工具API
*/
class Printer : public QObject {
Q_OBJECT
public:
explicit Printer();
/**
* Execute print, data's type must be Image
*/
Q_INVOKABLE void print(QVariant data);
};
#endif //GOXUI_PRINT_P_H
<file_sep>//
// Created by sulin on 2018/1/14.
//
#include <QDebug>
#include <Cocoa/Cocoa.h>
#include <QCoreApplication>
#include <QQuickItem>
#include "frameless.h"
#include "MyWindow.h"
MyWindow::MyWindow(QWindow *parent) : QQuickWindow(parent) {
frameless_init(this);
oldRatio = 0;
qDebug() << "init...";
}
bool MyWindow::event(QEvent *event) {
qreal newRatio = devicePixelRatio();
if (oldRatio > 0 && oldRatio < 100 && oldRatio != newRatio) {
qDebug() << "devicePixelRatio changed, force flush" << oldRatio << newRatio;
frameless_flush_ratio(this, newRatio); // 主动刷新ratio
QRegion region(0, 0, width(), height());
QWindow::exposeEvent(new QExposeEvent(region)); // 必须通过QWindow来expose, QQuickWindow会吞掉它
}
// qDebug() << "what??? " << event->type();
if (event->type() == QEvent::MouseButtonPress) {
if (this->mouseGrabberItem()) {
qDebug() << "mouseGrabberItem: " << this->mouseGrabberItem()->objectName();
} else {
qDebug() << "mouseGrabberItem: nil";
}
}
oldRatio = newRatio;
return QQuickWindow::event(event);
}
bool MyWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) {
qDebug() << "what??? " << eventType;
return QQuickWindow::nativeEvent(eventType, message, result);
}
<file_sep>//
// Created by sulin on 2018/1/9.
//
#include "item_hotkey.h"
HotKeyItem::HotKeyItem(QObject *parent) : QObject(parent) {
this->hotkey = nullptr;
}
QString HotKeyItem::getSequence() {
return this->sequence;
}
void HotKeyItem::setSequence(QString key) {
// release old hotkey
this->releaseHotKey();
// create new hotkey
qDebug() << "bind hotkey: "<< key;
QHotkey* hk = new QHotkey(QKeySequence(key), true);
QObject::connect(hk, &QHotkey::activated, [=]() {
emit this->activated();
});
this->hotkey = hk;
this->sequence = key;
}
void HotKeyItem::releaseHotKey() {
if (!this->hotkey) {
return;
}
qDebug() << "release hotkey: "<< this->sequence;
delete this->hotkey;
this->hotkey = nullptr;
}
HotKeyItem::~HotKeyItem() {
this->releaseHotKey();
}
<file_sep>//
// Created by sulin on 2019/4/7.
//
#include <QDebug>
#include <QtWebEngine/qtwebengineglobal.h>
#include "goxui_web.h"
// exec init
API void ui_init_web() {
qDebug() << "initialize WebEngine";
QtWebEngine::initialize();
}
| d689ec745e45d47b9242e682371c76c6f0f88a05 | [
"C",
"CMake",
"C++",
"INI"
]
| 38 | C++ | go-eden/goxui-cbridge | 6661aa8bd3ab0d3d95805bcbd0efa4ae12a2867d | 9f9ba6ef6758629d6897e44a3628f970d07269e8 |
refs/heads/master | <repo_name>Sploradorali/Tetherball<file_sep>/README.md
# Tetherball
Core JS test of basic 2D collision detection.
<h2>Concept</h2>
The ray/line rotates on the center point of the canvas by incrementing/decrementing the x- and y-coordinates of both ends. Coordinates between the start of the line, the end of the line, and the center point of the circle are used with trigonometric functions to detect whether the distance between the point of the line closest to the circle and the circle's center are smaller than the circle's radius, which indicates that the line has collided with the "ball."
<file_sep>/tetherball.js
//
document.getElementById("test").innerHTML = "Test!";
var canvas = document.getElementById("tetherball");
var ctx = canvas.getContext("2d");
// Current state values
var clockwise = true;
var collided = false;
// Line coordinates
var x1 = y1 = 0;
var x2 = y2 = 400;
// Ball coordinates and radius
var cx = 100;
var cy = 300;
var cr = 5;
// Initialize line and ball
drawLine(x1, y1, x2, y2);
drawBall(cx, cy, cr);
setInterval(refresh, 5);
setInterval(function() {
if (checkForCollision(x1, y1, x2, y2, cx, cy, cr)) {
if (!collided) {
clockwise = !clockwise;
collided = true;
}
} else {
collided = false;
}
}, 1);
/**
* Draws the "tether" line.
*
* @param {number} sx Start point x-coordinate
* @param {number} sy Start point y-coordinate
* @param {number} ex End point x-coordinate
* @param {number} ey End point y-coordinate
*/
function drawLine(sx, sy, ex, ey) {
ctx.clearRect(0, 0, 400, 400);
ctx.beginPath();
ctx.moveTo(sx, sy);
ctx.lineTo(ex, ey);
ctx.stroke();
}
/**
* Draws the "ball" arc.
*
* @param {number} x Center point x-coordinate
* @param {number} y Center point y-coordinate
* @param {number} r Radius
*/
function drawBall(x, y, r) {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.stroke();
}
/**
* Takes the current position and path of the line and
* generates the next position to simulate a spin.
*
*/
function spin() {
if (x1 == 0 && y1 == 0) {
clockwise?x1++:y1++;
clockwise?x2--:y2--;
} else if (x1 == 0 && y1 == 400) {
clockwise?y1--:x1++;
clockwise?y2++:x2--;
} else if (x1 == 400 && y1 == 400) {
clockwise?x1--:y1--;
clockwise?x2++:y2++;
} else if (x1 == 400 && y1 == 0) {
clockwise?y1++:x1--;
clockwise?y2--:x2++;
} else if (x1 < 400 && y1 == 0) {
clockwise?x1++:x1--;
clockwise?x2--:x2++;
} else if (x1 == 400 && y1 > 0) {
clockwise?y1++:y1--;
clockwise?y2--:y2++;
} else if (x1 > 0 && y1 == 400) {
clockwise?x1--:x1++;
clockwise?x2++:x2--;
} else if (x1 == 0 && y1 < 400) {
clockwise?y1--:y1++;
clockwise?y2++:y2--;
}
}
/**
* Invokes spin(), drawBall(), and drawLine() to refresh the canvas.
*
*/
function refresh() {
spin();
drawBall(cx, cy, cr);
drawLine(x1, y1, x2, y2);
}
/**
* Returns whether the line is colliding with the ball.
*
* @param {number} lx1 Line start point x-coordinate
* @param {number} ly1 Line start point y-coordinate
* @param {number} lx2 Line end point x-coordinate
* @param {number} ly2 Line end point y-coordinate
* @param {number} cx Ball center c-coodinate
* @param {number} cy Ball center y-coordinate
* @param {number} cr Ball radius
*/
function checkForCollision(lx1, ly1, lx2, ly2, cx, cy, cr) {
var dAB = Math.sqrt(Math.pow(lx2 - lx1, 2) + Math.pow(ly2 - ly1, 2));
var dAC = Math.sqrt(Math.pow(lx1 - cx, 2) + Math.pow(ly1 - cy, 2));
var dBC = Math.sqrt(Math.pow(cx - lx2, 2) + Math.pow(cy - ly2, 2));
var angleA = Math.acos(
(Math.pow(dAC, 2) + Math.pow(dAB, 2) - Math.pow(dBC, 2))
/ (2 * dAC * dAB)
);
var dCT = dAC * Math.sin(angleA);
return dCT <= cr ? true : false;
}
/**
* Listens for key presses (WASD or arrow keys) to move current ball coordinates.
*
*/
document.addEventListener("keydown", function(event) {
switch(event.keyCode) {
case(65):case(37):
cx -= 0.5;
break;
case(87):case(38):
cy -= 0.5;
break;
case(68):case(39):
cx += 0.5;
break;
case(83):case(40):
cy += 0.5;
break;
}
})
/*
* TO-DO
*
* "Blocking" center axis needed to prevent ball from phasing through middle segment of
* the line/ray.
*/
| 9df9da6d954a48f101203a3607e560f64bea7114 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | Sploradorali/Tetherball | 42461c926b3f968e27fa564e60818aefb1acb191 | cc428152d5faddc67a851b3f43cdb5165beb273c |
refs/heads/main | <repo_name>sakil-g/Projet-Adrie<file_sep>/controller/Valid_inscription.php
<?php
function validerDonneesFormInscription($data ) { // Création de la fonction qui va nous permettre de verifier les données
$champs = [ // Ici on crée un tableau ou l'on récupere les champs dans notre formulaire
array("key" => "username", "libele" => "Nom d'utilisateur"),
array("key" => "<PASSWORD>", "libele" => "<PASSWORD>"),
array("key" => "nom", "libele" => "Nom"),
array("key" => "prenom", "libele" => "Prenom"),
array("key" => "email", "libele" => "Email"),
array("key" => "numero", "libele" => "Numéro de télephone"),
array("key" => "dob", "libele" => "Date de naissance"),
];
foreach ($champs as $value){ // à l'aide de la fonction foreach je parcours le tableau pour verifier les données insérer dans les champs
if ( !isset($data[$value["key"]]) || $data[$value["key"]] == "" ) {
return array("valide" => false, "message" => 'Renseignez le champ : "'.$value["libele"].'"');
}
if(in_array($value["key"], array("nom", "prenom" , )) && !preg_match("/[A-Za-z - ]+/", $data[$value["key"]])){
return array("valide" => false, "message" => 'Le champ : "'.$value["libele"].'" doit être verifié');
}
if ( $value["key"] == "password" && strlen($data[$value["key"]]) <= 8 ) {
return array("valide" => false, "message" => 'votre mot de passe est trop faible');
}
if ( in_array($value["key"], array("password","username","email" )) && !preg_match("/[0-9a-z - ' @ ( ) ! # é è ]+/", $data[$value["key"]]) ) {
return array("valide" => false, "message" => 'Renseignez le champ : "'.$value["libele"].'"');
}
if(in_array($value["key"], array("numero", "dob")) && !preg_match("/[0-9 - ' @ ( ) ! # é è ]+/", $data[$value["key"]])){
return array("valide" => false, "message" => 'Le champ : "'.$value["libele"].'" doit être verifié');
}
}
return array("valide" => true);
}
?>
<file_sep>/includes/section_tuteur.php
<?php
if (isset ($_GET['promotion'])){
$idpromo = $_GET['promotion'];
}
?>
<table class="table" id="test">
<thead>
<tr>
<th scope="col">Nom</th>
<th scope="col">Prénom</th>
<th scope="col">Date de naissance</th>
<th scope="col">E-mail</th>
<th></th>
</tr>
</thead>
<tbody>
<?php include 'dbh_co.php'; //accéder a la base de donnée
//requête pour pouvoir sélectionner les utilisateurs par promo
$sql="SELECT * FROM utilisateur_promotion WHERE id_promo =".$idpromo.";";
$result = $db->query($sql);
if(!empty($result)){
while($row = $result->fetch_array()){
$request = "SELECT * FROM utilisateur WHERE id_user = ".$row['id_user']." AND tuteur = 1;";
$resultat = $db->query($request);
if (!empty($resultat) && $resultat -> num_rows > 0){
$line = $resultat->fetch_row();
echo '<tr>
<td>' .$line[8].'</td>
<td>' .$line[9].'</td>
<td>' .$line[5].'</td>
<td>' .$line[3].'</td>
<td>
<form method="POST" enctype="multipart/form-data" action="../pages/mod_app.php?id='.$line[0].'">
<input class="btn-sm btn-primary mb-4" type="submit" value="Modifier" name="" >
</form>
<button type="button" class="btn-sm btn-secondary modalBtn" onclick= supApp("'.$line[0].'") data-toggle="modal" data-target="#supmodal">
Supprimer
</button>
</td>
</td>
</tr>';
}
else {
echo "0 resultats trouvés";
}
}
}
?>
</tbody>
</table><file_sep>/pages/mod_tut.php
<?php session_start() ?>
<?php include_once('../config.php'); ?>
<?php include_once '../includes/dbh_co.php'; //accéder a la base de donnée
$id = $_GET['id'];
$sql = "SELECT * FROM utilisateur WHERE id_user = $id;" ; //selectionner la base de donnée UTILISATEUR
$result = $db->query($sql);
$result=$result->fetch_assoc();
?>
<!DOCTYPE html>
<html>
<head>
<title>Formulaire de modification tuteurs / tutrices</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<?php include_once('../includes/header.php');?> <!-- Ajout de la navbar -->
</head>
<body>
<div class="bg">
<div class="registration-form">
<form method="POST" action="../includes/modificateur_tut.php">
<input type="text" hidden value="<?php echo $result['id_user']?>" name = 'id'>
<div class="d-flex form-icon justify-content-center">
<img src="<?php echo BASE_URL . "\img\logo.png";?>" alt="logo" height="120" class="logoadrie">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-address-book"></i></span>
</div>
<input type="text" class="form-control " placeholder="Nom*" name="nom" value="<?php echo $result['nom'] ?>">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-id-card"></i></span>
</div>
<input type="text" class="form-control " placeholder="Prénom*" name="prenom" value="<?php echo $result['prenom'] ?>">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-at"></i></span>
</div>
<input type="text" class="form-control " placeholder="E-mail*" name="email" value="<?php echo $result['email'] ?>">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="tel" class="form-control " placeholder="Numéro de téléphone*" name="numero" value="<?php echo $result['numero'] ?>">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-birthday-cake"></i></span>
</div>
<input type="date" class="form-control" name="dob" value="<?php echo $result['dob'] ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-block create-account" name="modifier">Modifier un compte</button>
</div>
<div> <p class="champs"> Tout les champs muni d'une * sont obligatoires </p></div>
</form>
</div>
</div>
</body>
</html>
<file_sep>/includes/acc_app.php
<?php include_once('../config.php'); ?>
<?php include_once('header.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- FULL CALENDAR -->
<link href="../fullcalendar/lib/main.css" rel="stylesheet">
<title>Document</title>
</head>
<body>
<div class="container">
<?php if(isset($_SESSION['username'])){ // Si l'utilisateur est connecté afficher un message de bienvenue
$user = $_SESSION['username'];
// afficher un message
echo "<div class='text-center mt-3 alert alert-success'> Bonjour , $user </div>";
}
?>
<a class="btn btn-outline-success" href="#" role="button">Emploi du temps</a>
<a class="btn btn-outline-danger" href="#" role="button">Émargement</a>
<div id="calendar"></div>
</div>
<script src="../fullcalendar/lib/main.js"></script>
<script src='../js/fullcalendar.js'></script>
</body>
</html><file_sep>/includes/modificateur_tut.php
<?php
include_once './dbh_co.php';
//récupere les valeurs avec le $_POST
$nom = $_POST['nom'];
$prenom = $_POST['prenom'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$id = $_POST['id'];
$res=explode('-',$dob); //convertir la date en format EUR
$date=$res[2];
$month=$res[1];
$year=$res[0];
$new=$date.'-'.$month.'-'.$year;
// Met à jour les valeurs dans la BDD
$sql = "UPDATE utilisateur SET nom= '$nom',prenom='$prenom',email='$email',dob= '$new' WHERE id_user=$id ";
if (mysqli_query($db, $sql)) {
header("Location: ../includes/liste_tut.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($db);
}
mysqli_close($db);
?><file_sep>/includes/deconnexion.php
<?php
session_start();
if(isset($_POST['deconnexion']))
{
if($_POST['deconnexion']==true)
{
// On détruit les variables de notre session
session_unset();
// On détruit notre session
session_destroy ();
header("location:../index.php");
}
} ?><file_sep>/includes/acc_admin.php
<?php include_once('../config.php'); ?>
<?php include_once('header.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<!-- FULL CALENDAR -->
<link href="../fullcalendar/lib/main.css" rel="stylesheet">
<title>Admin</title>
</head>
<body>
<div class="container-fluid">
<div class="text-center mt-3 alert alert-dark animate__animated animate__fadeInDown"> Bienvenue ADMIN
</div>
<div class="d-flex mt-5 justify-content-center mobileList">
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle mr-1 Mbottom" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Ajouter
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="../pages/inscription_user.php" role="button">Ajouter un apprenant</a>
<a class="dropdown-item" href="../pages/inscription_tut.php" role="button">Ajouter un tuteur</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="../pages/ajout_promo.php" role="button">Ajouter une promo</a>
</div>
</div>
<a class="btn btn-outline-success mr-1 Mbottom" href="#" role="button">Emploi du temps</a>
<a class="btn btn-outline-danger mr-1 Mbottom" href="#" role="button">Émargement</a>
<a class="btn btn-outline-success mr-1 Mbottom" href="../includes/liste_app.php" role="button">Liste des apprenants</a>
<a class="btn btn-outline-success mr-1 Mbottom" href="../includes/liste_tut.php" role="button">Liste des tuteurs</a>
</div>
<div id="calendar"></div>
</div>
<script src="../fullcalendar/lib/main.js"></script>
<script src='../js/fullcalendar.js'></script>
</body>
</html><file_sep>/includes/sup_app.php
<?php include_once '../includes/dbh_co.php'; //accéder a la base de donnée
// Start a Session
if (!session_id()) @session_start();
$id = $_GET['id'];
// sql to delete a record
$sql = "DELETE FROM utilisateur WHERE id_user=$id;";
$rec = "DELETE FROM utilisateur_promotion WHERE id_user=$id;";
if ($db->query($sql) === TRUE) {
if ($db->query($rec) === TRUE ){
$_SESSION['flash'] = 'Apprenant supprimer avec succès'; // Message de confirmation de suppresion
header("Location: ../includes/liste_app.php");
}
else {
echo "Erreur de suppression de l'apprenant: " . $db->error;
}
}
else {
echo "Erreur de suppression de l'apprenant: " . $db->error;
}
$db->close();
?><file_sep>/includes/inscription.php
<?php
// connexion à la base de données
include './dbh_co.php';
require_once('../controller/Valid_inscription.php'); // j'appel ma function validation qui se retrouve dans le fichier controllers
if(isset($_POST["inscription"])){ //
$validation = validerDonneesFormInscription($_POST); //
if(!$validation["valide"]){
$message = '<div class=" container mt-5 text-center alert alert-danger">'.$validation["message"].'</div>';
echo $message;
}else{
$resultatDeSauvegarde = enregistrerDansBase($db);
if($resultatDeSauvegarde["succes"]){
}else{
$message = '<div class=" container mt-5 alert alert-danger">'.$resultatDeSauvegarde["erreur"].'</div>';
echo $message;
}
}
}
function enregistrerDansBase($db){
$username = htmlentities($_POST['username']);
$mdp = htmlentities($_POST['password']);
$nom = htmlentities($_POST['nom']);
$prenom = htmlentities($_POST['prenom']);
$email = htmlentities($_POST['email']);
$tel = htmlentities($_POST['numero']);
$dob = htmlentities($_POST['dob']);
$promotion= $_POST['promotion'];
//converti la date en format EUR
if(strlen($dob) >= 8){
$res=explode('-',$dob);
$date=$res[2];
$month=$res[1];
$year=$res[0];
$new=$date.'-'.$month.'-'.$year;
}
else{
session_start();
$_SESSION['flash'] = ['false','Entrer une date'];
header("location:../pages/inscription_user.php");
}
//fonction pour insérer les données que l'on à récuperer dans le $_POST dans la base de données MYSQL
$sql = "INSERT INTO utilisateur (id_user,username, mdp,nom,prenom,email,numero,dob,role_id) VALUES (NULL,'$username', md5('$mdp'),'$nom','$prenom','$email','$tel','$new',2);";
$rec = "SELECT id_user FROM utilisateur ORDER BY id_user DESC LIMIT 1";
$resulat = [];
if (mysqli_query($db, $sql))
{
$result = mysqli_query($db, $rec);
$user= $result->fetch_assoc();
$id_user = $user['id_user'];
$request = "INSERT INTO utilisateur_promotion (id_user, id_promo,tuteur) VALUES ('$id_user','$promotion',0);";
if (mysqli_query($db, $request)) {
$resulat = array("succes" => true);
header("location:../index.php");
echo '<script>alert("Enregistrement réussi")</script>';
} else {
$resulat = array("succes" => false);
$resulat["erreur"] = "Error: " . $request . "<br>" . mysqli_error($db);
}
} else {
$resulat = array("succes" => false);
$resulat["erreur"] = "Error: " . $sql . "<br>" . mysqli_error($db);
}
mysqli_close($db);
return $resulat;
}
enregistrerDansBase($db);
?>
<file_sep>/includes/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="<?php echo BASE_URL . "css/bootstrap.min.css";?>">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<!-- CSS -->
<link rel="stylesheet" href="<?php echo BASE_URL . "css/style.css"; ?>">
<!-- Anime CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">
<title> Page de connexion </title>
</head>
<body>
<div class="container-fluid navbar-container res">
<nav class="navbar navbar-expand-lg navbar-dark">
<a class="navbar-brand" href="http://www.adrie.fr">
<img src="<?php echo BASE_URL . "img/logo.png";?>" alt="logo" height="50" class="logoAdrie">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<?php
if(isset($_SESSION['username']) && $_SESSION['username'] == 'admin'){ //redirige vers ACCUEIL ADMIN si on est dans la session ADMIN
echo '<li class="nav-item active">
<a class="nav-link" href="..\pages\accueil_admin.php">Accueil</a>
<div class="underline"></div>
</li>';
} ?>
<?php
if(isset($_SESSION['user']) && $_SESSION['user']['tuteur'] == 1){ //redirige vers ACCUEIL tuteur si on est dans la session tuteur
echo '<li class="nav-item active">
<a class="nav-link" href="../pages/accueil_tut.php">Accueil</a>
<div class="underline"></div>
</li>';
} ?>
<?php
if(isset($_SESSION['user']) && $_SESSION['user']['role_id'] == 2){ //redirige vers ACCUEIL tuteur si on est dans la session tuteur
echo '<li class="nav-item active">
<a class="nav-link" href="../pages/accueil_app.php">Accueil</a>
<div class="underline"></div>
</li>';}
?>
<li class="nav-item">
<a class="nav-link" href="<?php echo BASE_URL . "pages/accueil_tut.php";?>">Tuteurs</a>
<div class="underline"></div>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo BASE_URL . "pages/accueil_app.php";?>">Apprenants</a>
<div class="underline"></div>
</li>
<!-- Affiche le menu ADMIN que si l'utilisateur est connecter en tant qu'admin -->
<?php
if(isset($_SESSION['username']) && $_SESSION['username'] == 'admin'){
echo '<li class="nav-item">
<a class="nav-link" href="..\pages\accueil_admin.php">Admin</a>
<div class="underline"></div>
</li>';
}
?>
</ul>
<ul class="navbar-nav">
<!-- Affichage des bouttons deconnexion ou connexion selon l'état de la SESSION USER -->
<?php
if(isset($_SESSION['user']) && $_SESSION['user'] != NULL){
echo '<li class="nav-item"><form method="POST" action="../includes/deconnexion.php">
<input type="submit" value="Se déconnecter" class="btn btn-primary w-100" name="deconnexion">
</form></li>';
}else{
echo '<li class="nav-item mt-1"><form method="POST" action="../index.php">
<input type="submit" value="Se connecter" class="btn btn-primary conn w-100 animate__animated animate__zoomIn" name="connexion">
</form></li>';}
?>
</ul>
</div>
</nav>
</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/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="<?php echo BASE_URL . "js/script.js"?>"></script>
</body>
</html>
<file_sep>/index.php
<?php session_start() ?>
<?php include_once('./config.php'); ?>
<?php include_once('./includes/header.php'); ?>
<?php include_once('./pages/loginform.php'); ?>
<br>
<?php include_once('./includes/footer.php'); ?><file_sep>/js/script.js
// Navbar
$('.nav-link').on('click', function() {
$('.active-link').removeClass('active-link');
$(this).addClass('active-link');
});
// Fonction pour supprimer un utilisateur
var supApp = function (id) {
let validationFormApp = document.getElementById('validationFormApp');
validationFormApp.setAttribute('action',"../includes/sup_app.php?id="+id);
}
var supTut = function (id) {
let validationFormTut = document.getElementById('validationFormTut');
validationFormTut.setAttribute('action',"../includes/sup_tut.php?id="+id);
}<file_sep>/includes/acc_tut.php
<?php include_once('../config.php'); ?>
<?php include_once('header.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<title>Document</title>
</head>
<body>
<div class="container">
<?php if(isset($_SESSION['username'])){ // Si l'utilisateur est connecté afficher un message de bienvenue
$user = $_SESSION['username'];
// afficher un message
echo "<div class='text-center mt-3 alert alert-success'> Bonjour , $user </div>";
}
?>
<div class="d-flex flex-column text-center mt-5">
<h1>
Feuille d'émargement
</h1>
</div>
<p>Promotion :</p>
<p>Date :</p>
<a class="btn btn-outline-danger" href="#" role="button">Émargement</a>
<a class="btn btn-outline-success" href="#" role="button">Emploi du temps</a>
<section class="container text-center bg-light py-5">
<form>
<table class="table" id="test">
<thead>
<tr>
<th scope="col">Nom</th>
<th scope="col">Prénom</th>
<th scope="col">Présent(e)</th>
<th scope="col">Absent(e)</th>
</tr>
</thead>
<tbody>
<?php include 'dbh_co.php'; //accéder a la base de donnée
$sql = "SELECT * FROM utilisateur WHERE role_id = '2';" ; //selectionner la base de donnée UTILISATEUR
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc())
echo '<tr>
<td>' .$row["nom"].'</td>
<td>' .$row["prenom"].'</td>
<td><input type="checkbox" value=""></td>
<td><input type="checkbox" value=""></td>
</tr>';
}
else {
echo "0 resultats trouvés";
}
$db->close();
?>
</tbody>
</table>
<input type="submit" class="btn btn-primary" value="Valider" name="valider_emargement">
</form>
</section>
<p class="lead">
<input type="button" id="create_pdf" value="Generate PDF">
<button id="txt" class="btn btn-success">EN .TEXT</button>
</p>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script>
(function () {
var
form = $('.form'),
cache_width = form.width(),
a4 = [595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click', function () {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function (canvas) {
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 20, 20);
doc.save('Bhavdip-html-to-pdf.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 2000,
removeContainer: true
});
}
}());
</script>
<script>
/*
* jQuery helper plugin for examples and tests
*/
(function ($) {
$.fn.html2canvas = function (options) {
var date = new Date(),
$message = null,
timeoutTimer = false,
timer = date.getTime();
html2canvas.logging = options && options.logging;
html2canvas.Preload(this[0], $.extend({
complete: function (images) {
var queue = html2canvas.Parse(this[0], images, options),
$canvas = $(html2canvas.Renderer(queue, options)),
finishTime = new Date();
$canvas.css({ position: 'absolute', left: 0, top: 0 }).appendTo(document.body);
$canvas.siblings().toggle();
$(window).click(function () {
if (!$canvas.is(':visible')) {
$canvas.toggle().siblings().toggle();
throwMessage("Canvas Render visible");
} else {
$canvas.siblings().toggle();
$canvas.toggle();
throwMessage("Canvas Render hidden");
}
});
throwMessage('Screenshot created in ' + ((finishTime.getTime() - timer) / 1000) + " seconds<br />", 4000);
}
}, options));
function throwMessage(msg, duration) {
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function () {
$message.fadeOut(function () {
$message.remove();
});
}, duration || 2000);
if ($message)
$message.remove();
$message = $('<div ></div>').html(msg).css({
margin: 0,
padding: 10,
background: "#000",
opacity: 0.7,
position: "fixed",
top: 10,
right: 10,
fontFamily: 'Tahoma',
color: '#fff',
fontSize: 12,
borderRadius: 12,
width: 'auto',
height: 'auto',
textAlign: 'center',
textDecoration: 'none'
}).hide().fadeIn().appendTo('body');
}
};
})(jQuery);
</script>
</body>
</html>
<file_sep>/pages/ajout_promo.php
<?php
include '../includes/dbh_co.php';
session_start();
if (!isset($_SESSION['username']) || $_SESSION['username']!='admin') {
header("location: ../index.php");
exit;
}
session_write_close(); // fermeture de la session pour éviter les warning si t'en ré-ouvres une dans ta page.
?>
<?php include_once('../config.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Formulaire d'inscription</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<?php include_once('../includes/header.php');?> <!-- Ajout de la navbar -->
</head>
<body>
<div class="bg">
<div class="registration-form">
<form method="POST" action="../includes/add_prom.php">
<div class="input-group-prepend">
<a href="#" onClick="history.go(-1)"><div class="arrow"></div></a>
</div>
<div class="d-flex form-icon justify-content-center">
<img src="<?php echo BASE_URL . "\img\logo.png";?>" alt="logo" height="120" class="logoadrie">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text mr-1"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control " placeholder="Nom de la promotion*" name="nomPromo">
</div>
<div class="input-group form-group mt-3">
<label class="ml-1" for="annee">Année (Début - Fin) :</label>
<div class="d-flex ">
<div class="input-group-prepend">
<span class="input-group-text mr-1"><i class="far fa-calendar-alt"></i></span>
</div>
<input class="form-control " type="number" name="debut_promotion" id="debut_promotion" min="2020" style="width: 44%;">
<input class="form-control " type="number" name="fin_promotion" id="fin_promotion" min="2021" style="width: 44%;">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block create-account" name="creer">Créer une promotion</button>
</div>
</form>
</div>
</div>
</body>
</html>
<file_sep>/pages/error.php
<?php include_once('../config.php'); ?>
<?php include_once('../includes/header.php'); ?>
<div class="container">
<p class="text-center mt-3 alert alert-dark">Mot de passe ou nom d'utilisateur invalide</p>
</div>
<?php include_once('../pages/loginform.php'); ?>
<file_sep>/adrie.sql
-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Hôte : 127.0.0.1
-- Généré le : jeu. 25 fév. 2021 à 07:55
-- Version du serveur : 5.7.17
-- Version de PHP : 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `adrie`
--
-- --------------------------------------------------------
--
-- Structure de la table `absence`
--
CREATE TABLE `absence` (
`id_user` int(11) NOT NULL,
`date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `promotion`
--
CREATE TABLE `promotion` (
`id_promo` int(11) NOT NULL,
`nom` varchar(255) NOT NULL,
`promotion` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `promotion`
--
INSERT INTO `promotion` (`id_promo`, `nom`, `promotion`) VALUES
(1, 'ADRIE', '2020-2021'),
(2, 'ADRIE WEB', '2020-2023'),
(3, 'ADRIE WEB', '2020-2021');
-- --------------------------------------------------------
--
-- Structure de la table `role`
--
CREATE TABLE `role` (
`id_role` int(10) UNSIGNED NOT NULL,
`role` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `role`
--
INSERT INTO `role` (`id_role`, `role`) VALUES
(1, 'admin'),
(2, 'apprenant');
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur`
--
CREATE TABLE `utilisateur` (
`id_user` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`mdp` text NOT NULL,
`email` varchar(255) NOT NULL,
`numero` int(11) NOT NULL,
`dob` varchar(255) NOT NULL,
`role_id` int(11) NOT NULL,
`nom` varchar(255) NOT NULL,
`prenom` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `utilisateur`
--
INSERT INTO `utilisateur` (`id_user`, `username`, `mdp`, `email`, `numero`, `dob`, `role_id`, `nom`, `prenom`) VALUES
(7, 'tuteur', '1234', '<EMAIL>', 2623456, '02-03-2021', 0, 'jack', 'brand'),
(1, 'admin', 'admin', '', 123, '2021-02-08', 1, 'Add', 'Min'),
(44, 'declan', '', '<EMAIL>', 262500655, '05-02-2023', 2, 'declan', 'rice'),
(42, 'jack12', '2005', '<EMAIL>', 262556699, '23-02-2021', 2, 'jack', 'brand'),
(43, 'abcd', '12345', '<EMAIL>', 262555555, '03-02-2021', 2, 'ab', 'cd');
-- --------------------------------------------------------
--
-- Structure de la table `utilisateur_promotion`
--
CREATE TABLE `utilisateur_promotion` (
`id` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`id_promo` int(11) NOT NULL,
`tuteur` tinyint(4) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Déchargement des données de la table `utilisateur_promotion`
--
INSERT INTO `utilisateur_promotion` (`id`, `id_user`, `id_promo`, `tuteur`) VALUES
(14, 44, 3, 0),
(13, 43, 2, 0),
(12, 42, 1, 0);
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `absence`
--
ALTER TABLE `absence`
ADD PRIMARY KEY (`id_user`);
--
-- Index pour la table `promotion`
--
ALTER TABLE `promotion`
ADD PRIMARY KEY (`id_promo`);
--
-- Index pour la table `role`
--
ALTER TABLE `role`
ADD PRIMARY KEY (`id_role`);
--
-- Index pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
ADD PRIMARY KEY (`id_user`);
--
-- Index pour la table `utilisateur_promotion`
--
ALTER TABLE `utilisateur_promotion`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `absence`
--
ALTER TABLE `absence`
MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `promotion`
--
ALTER TABLE `promotion`
MODIFY `id_promo` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `role`
--
ALTER TABLE `role`
MODIFY `id_role` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT pour la table `utilisateur`
--
ALTER TABLE `utilisateur`
MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
--
-- AUTO_INCREMENT pour la table `utilisateur_promotion`
--
ALTER TABLE `utilisateur_promotion`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;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>/js/fullcalendar.js
// FULL CALENDAR
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
headerToolbar: {
center: 'dayGridMonth,timeGridFourDay' // buttons for switching between views
},
views: {
timeGridFourDay: {
type: 'timeGrid',
duration: { days: 7 },
buttonText: 'Semaines'
}
}
});
calendar.setOption('locale', 'fr');
calendar.render();
});
<file_sep>/includes/sup_tut.php
<?php include_once '../includes/dbh_co.php'; //accéder a la base de donnée
// Lancer une session
if (!session_id()) @session_start();
$id = $_GET['id'];
// Requête SQL pour supprimer une entrée
$sql = "DELETE FROM utilisateur WHERE id_user=$id";
if ($db->query($sql) === TRUE) {
$_SESSION['flash'] = 'Tuteur supprimer avec succès';
header("Location: ../includes/liste_tut.php");
} else {
echo "Error deleting record: " . $db->error;
}
$db->close();
?><file_sep>/includes/add_prom.php
<?php
include_once './dbh_co.php';
function EnregistrerFormation($db){
$nomFormation = htmlentities($_POST['nomPromo']);
$debutPromotion = htmlentities($_POST['debut_promotion']);
$finPromotion = htmlentities($_POST['fin_promotion']);
$promotion= $debutPromotion.'-'.$finPromotion;
$sql = "INSERT INTO promotion (nom,promotion) VALUES ('$nomFormation', '$promotion');";
$resulat = [];
if (mysqli_query($db, $sql)) {
header("Location: ../pages/accueil_admin.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($db);
}
mysqli_close($db);
}
EnregistrerFormation($db);
?>
<file_sep>/includes/liste_tut.php
<?php session_start(); ?>
<?php include_once('../config.php'); ?>
<?php include_once('header.php'); ?>
<?php //include_once '../includes/dbh_co.php';
include './dbh_co.php';
if (!isset($_SESSION['username']) || $_SESSION['username']!='admin') {
header("location: ../index.php");
exit;
}
session_write_close(); // fermeture de la session pour éviter les warning si t'en ré-ouvres une dans ta page.
?>
<?php
if (isset ($_GET['valider'])){
$idpromo = $_GET ['promotion'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<title>Liste des tuteurs / tutrices</title>
</head>
<body>
<div class="container">
<div class="d-flex flex-column text-center mt-5">
<h1>
Liste des tuteurs / tutrices
</h1>
</div>
<div id="promotiondiv" class="prom" style="width:20%">
<form method="POST" action="" id="promotion">
<input type="text" hidden value="<?php echo $result['id_user']?>" name = 'id' id="test">
<label class="mb-2" for="promotion">Promotion :</label>
<select class="form-control mb-4" name="promotion" id="promotion">
<!-- Récupérer les promos -->
<?php
$compteur = 0;
$selected = false;
$sql = "SELECT * FROM promotion";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// Afficher le résultat de chaque lignes
while($row = $result->fetch_assoc()){
if($compteur == 0){$selected = "selected=selected";}else{$selected = "";}
echo '<option value="'.$row['id_promo'].' " '.$selected.'>'
.$row['nom'].' '.$row['promotion'].' </option>';
$compteur++;
}
}
?>
</select>
</form>
</div>
<a class="btn btn-outline-success mt-3" href="../includes/liste_app.php" role="button">Liste des apprenants</a>
<a class="btn btn-outline-danger mt-3" href="#" role="button">Émargement</a>
<a class="btn btn-outline-success mt-3" href="#" role="button">Emploi du temps</a>
<section id="utilisateurs" class="container text-center bg-light py-5">
</section>
<p class="lead">
</p>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script>
$(document).ready(function(){
$("#promotion").change(function(){
var promo = $(this).children("option:selected").val();
if(promo != "undefined"){
$.ajax({
url: 'http://127.0.0.1/edsa-adrie_proj/includes/section_tuteur.php?promotion='+promo,
async : true,
method:"GET",
//data:{promotion: value},
success: (data) => {
console.log(data)
$("#utilisateurs").html(data);
},
error: (data) => {
}
});
console.log(promo)
//console.log("a")
};
})
});
</script>
<?php include '../modal/modal_app.php'; ?>
</body>
</html><file_sep>/includes/login.php
<?php
session_start();
if(isset($_POST['user']) && isset($_POST['mdp'])) //récupere les $_POST du formulaire LOGIN
{
// connexion à la base de données
include './dbh_co.php';
// on applique les deux fonctions mysqli_real_escape_string et htmlspecialchars
// pour éliminer toute attaque de type injection SQL et XSS
$username = mysqli_real_escape_string($db,htmlspecialchars($_POST['user']));
$password = mysqli_real_escape_string($db,htmlspecialchars($_POST['mdp']));
if($username !== "" && $password !== "")
{ $requeteUser = "SELECT * FROM utilisateur where
username = '".$username."' and mdp = '".md5($password)."'limit 1 " ;
$requete = "SELECT count(*) FROM utilisateur where
username = '".$username."' and mdp = '".md5($password)."' ";
$exec_requete = mysqli_query($db,$requete);
$result =mysqli_query($db,$requeteUser);
$reponse = mysqli_fetch_array($exec_requete);
$user=$result->fetch_assoc();
$count = $reponse['count(*)'];
if($count!=0) // nom d'utilisateur et mot de passe correctes
{
$_SESSION['user']= $user;
$_SESSION['username'] = $username;
if($_SESSION['user']['role_id']==2){ //redirection quand connecté en tant qu'apprenant
header('Location: ../pages/accueil_app.php');
}
if ($_SESSION['user']['role_id']==1){
header('Location: ../pages/accueil_admin.php'); //redirection quand on est connecté en tant qu'admin
}
}
else
{
error_log("ERROR LOGGIN");
header('Location: ../pages/error.php'); // utilisateur ou mot de passe incorrect
}
}
else
{
error_log("Champs prérequis vide");
header('Location: ../index.php'); // utilisateur ou mot de passe vide
}
}
mysqli_close($db); // fermer la connexion
?><file_sep>/config.php
<?php // définir des constantes globales
define('ROOT_PATH', realpath(dirname(__FILE__)));
define('BASE_URL', 'https://adrieprojet.herokuapp.com/');
?><file_sep>/README.md
# Application ADRIE
Bienvenue sur l'application ADRIE, une application "carnet de bord apprenant".
## Users stories
| En tant que | je veux | afin de | critères d'acceptations |
|--|--|--|---------|
|Apprenant | accèder à mes heures de présence/absence | pouvoir justifier une absence | Afficher les absences |
|Apprenant|pouvoir envoyer un justificatif d'absence | d'annuler une absence | Envoyer un mail à l'admin |
|Admin|créer des comptes apprenants | que les apprenants puissent se connecter | Enregistrer les données du compte dans la BDD |
|Admin|créer des comptes tuteurs | que les formateurs puissent se connecter | Enregistrer les données du compte dans la BDD |
|Admin|créer les promotions | d'affecter les apprenants à une promotion | Enregistrer les données du compte dans la BDD |
|Admin|associer une promotion à des apprenants|lister les apprenants de la promotion|Créer un lien entre une promotion et des apprenants |
|Admin|associer un tuteur et ses apprenants | que le tuteur puisse voir la liste d'apprenants|Créer un lien tuteur et apprenant|
|Admin|modifier l'emploi du temps|pouvoir gérer les changements ou les absences d'un formateur | CRUD |
|Admin|modifier les données d'un compte|modifier des données fausses|CRUD|
| Tuteur |voir les heures de présence/absence de mes apprenants | vérifier si ils sont assidus| Afficher la liste des apprenants et leur nombre d'heures de présence/absence|
|Tuteur|voir l'historique depuis entrée en formation | pouvoir les suivre depuis le début et ne rien manquer | Afficher chaque jour et voir si l'apprenant a été absent ou pas|
## Charte Graphique
Les couleurs figurant sur le logo de l'ADRIE sont utilisées.
### Vert foncé #61a444

Il représente la stabilité et l'équilibre.
### Vert clair #9cff71

Résultat de recherche d'images pour "vert clair signification"
Couleur de l'espérance, le vert est porteur de chance. Il invite au calme et au repos.
### Logos
 

## Liens
Wireframe : https://www.figma.com/file/V8eBy0U5Z9iHVQNBbVPNxQ/PROJET-ADRIE
Méthode Kanban : https://trello.com/b/kOmq6CVc/adrieprojet
<file_sep>/includes/add_tut.php
<?php
// connexion à la base de données
include './dbh_co.php';
function enregistrerDansBase($db){
$username = htmlentities($_POST['username']);
$mdp = htmlentities($_POST['password']);
$nom = htmlentities($_POST['nom']);
$prenom = htmlentities($_POST['prenom']);
$email = htmlentities($_POST['email']);
$tel = htmlentities($_POST['numero']);
$dob = htmlentities($_POST['dob']);
$promotion= $_POST['promotion'];
//converti la date en format EUR
$res=explode('-',$dob);
$date=$res[2];
$month=$res[1];
$year=$res[0];
$new=$date.'-'.$month.'-'.$year;
$sql = "INSERT INTO utilisateur (id_user,username, mdp,nom,prenom,email,numero,dob,role_id) VALUES (NULL,'$username','$mdp','$nom','$prenom','$email','$tel','$new',2);";
$rec = "SELECT id_user FROM utilisateur ORDER BY id_user DESC LIMIT 1";
$resulat = [];
if (mysqli_query($db, $sql))
{
$result = mysqli_query($db, $rec);
$user= $result->fetch_assoc();
$id_user = $user['id_user'];
$request = "INSERT INTO utilisateur_promotion (id_user, id_promo,tuteur) VALUES ('$id_user','$promotion',1);";
if (mysqli_query($db, $request)) {
$resulat = array("succes" => true);
header("location:../pages/accueil_admin.php");
} else {
$resulat = array("succes" => false);
$resulat["erreur"] = "Error: " . $request . "<br>" . mysqli_error($db);
}
} else {
$resulat = array("succes" => false);
$resulat["erreur"] = "Error: " . $sql . "<br>" . mysqli_error($db);
}
mysqli_close($db);
return $resulat;
}
enregistrerDansBase($db);
?>
<file_sep>/pages/accueil_tut.php
<?php
include '../includes/dbh_co.php';
session_start();
if (!isset($_SESSION['username']) || $_SESSION['username']!='admin') {
if (!isset($_SESSION['user']) || $_SESSION['user']['tuteur']!=1 ) {
header("location: ../index.php");
exit;
}
}
session_write_close(); // fermeture de la session pour éviter les warning si t'en ré-ouvres une dans ta page.
?>
<?php include '../includes/acc_tut.php'; ?>
<file_sep>/pages/loginform.php
<!-- Formulaire de connexion -->
<div class="container-fluid">
<div class="d-flex justify-content-center h-100 " style="margin-top: 5rem;">
<div class="card">
<div class="card-header">
<h3 class="animate__animated animate__bounceInDown">Connexion</h3>
<div class="card-body">
<form method="POST" action="<?php echo BASE_URL . "includes\login.php";?>">
<div class="input-group form-group mt-3 animate__animated animate__flipInX ">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control " placeholder="Nom d'utilisateur" name="user">
</div>
<div class="input-group form-group animate__animated animate__flipInX ">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" class="form-control" placeholder="<PASSWORD>" name="mdp">
</div>
<div class="row align-items-center remember">
<input type="checkbox">Se souvenir de moi ?
</div>
<div class="form-group mt-2">
<input type="submit" value="Se connecter" class="btn float-right login_btn w-100 animate__animated animate__bounceInUp" name="connexion">
</div>
</form>
</div>
<div class="card-footer mt-3">
<div class="d-flex justify-content-center links">
Pas de compte ?<a href=<?php echo BASE_URL . "pages/inscription_user.php";?>>S'inscrire</a>
</div>
<div class="d-flex justify-content-center" >
<a href="#" style="color: transparent;">Mot de passe oublié?</a>
</div>
</div>
</div>
</div>
</div>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<file_sep>/pages/inscription_tut.php
<?php include_once('../config.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Formulaire d'inscription</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--Bootsrap 4 CDN-->
<link rel="stylesheet" href="../css/bootstrap.min.css">
<!--Fontawesome CDN-->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="../css/style.css">
<?php include_once('../includes/header.php');?> <!-- Ajout de la navbar -->
</head>
<body>
<div class="bg">
<div class="registration-form">
<form method="POST" action="../includes/add_tut.php">
<div class="input-group-prepend">
<a href="#" onClick="history.go(-1)"><div class="arrow"></div></a>
</div>
<div class="d-flex form-icon justify-content-center">
<img src="<?php echo BASE_URL . "\img\logo.png";?>" alt="logo" height="120" class="logoadrie">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input type="text" class="form-control " placeholder="Nom d'utilisateur*" name="username">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input type="password" class="form-control " placeholder="Mot de passe*" name="password">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-address-book"></i></span>
</div>
<input type="text" class="form-control " placeholder="Nom*" name="nom">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-id-card"></i></span>
</div>
<input type="text" class="form-control " placeholder="Prénom*" name="prenom">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-at"></i></span>
</div>
<input type="text" class="form-control " placeholder="E-mail*" name="email">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-phone"></i></span>
</div>
<input type="tel" class="form-control " placeholder="Numéro de téléphone*" name="numero">
</div>
<div class="input-group form-group mt-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-birthday-cake"></i></span>
</div>
<input type="date" class="form-control" name="dob">
</div>
<div id="promotion">
<label class="mb-2" for="promotion">Promotion :</label>
<select class="form-control mb-4" name="promotion" id="promotion">
<!-- Récupérer les promos -->
<?php include_once '../includes/dbh_co.php';
$sql = "SELECT * FROM promotion";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// Afficher le résultat de chaque lignes
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['id_promo'].'">'.$row['nom'].' '.$row['promotion'].' </option>';
}
} ?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-block create-account" name="connexion">Créer un compte</button>
</div>
<div> <p class="champs"> Tout les champs muni d'une * sont obligatoires </p></div>
</form>
</div>
</div>
</body>
</html>
| 699d5f2fad38e9ddaa34d2e5a6bd86d337407efe | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
]
| 27 | PHP | sakil-g/Projet-Adrie | 0262f62221404db9ad29d1fb8eaebbb77ebfa363 | 15d8e59a90b039b1354bc285ca035081e68f0bda |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace TournamentTracker.Models
{
public class Tournament
{
private readonly IPairingGenerator _pairingGenerator;
private IEnumerable<Player> _players;
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Round> Rounds { get; private set; }
public IEnumerable<Player> Players
{
get { return _players; }
set
{
var players = value.ToList();
if (value.Count() % 2 != 0)
{
players.Add(Player.CreateEmpty());
}
_players = players;
Rounds = CreateEmptyRounds(Rounds.Count());
}
}
public Tournament(IPairingGenerator generator, int rounds)
{
if (rounds <= 0)
{
throw new ArgumentException("Tournament should have at least one round");
}
_pairingGenerator = generator;
Rounds = CreateEmptyRounds(rounds);
}
public IEnumerable<Pairing> RandomizePairings()
{
return _pairingGenerator.Shuffle(Players.ToList());
}
public IEnumerable<Pairing> SwissPairings()
{
return _pairingGenerator.Swiss(GetPlayerStandings(), GetPairingHistory().ToList()).ToList();
}
public IOrderedEnumerable<KeyValuePair<Player, int>> GetPlayerStandings()
{
var standings = Players.ToDictionary(i => i, i => 0);
foreach (var k in Rounds.SelectMany(j => j.GetStandings()))
{
standings[k.Key] += k.Value;
}
return standings.OrderByDescending(i => i.Value);
}
private IEnumerable<Pairing> GetPairingHistory()
{
return Rounds.SelectMany(i => i.Pairings).ToList();
}
#region Private methods
private static IEnumerable<Round> CreateEmptyRounds(int count)
{
var rounds = new Round[count];
for (var i = 0; i < count; i++)
{
rounds[i] = new Round();
}
return rounds;
}
#endregion
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
namespace TournamentTracker.Models
{
public interface IPairingGenerator
{
IEnumerable<Pairing> Shuffle(IList<Player> players);
IEnumerable<Pairing> Swiss(IOrderedEnumerable<KeyValuePair<Player, int>> standings, IList<Pairing> history);
}
}
<file_sep>namespace TournamentTracker.Models
{
public class Player
{
public string Name { get; set; }
public override bool Equals(System.Object other)
{
var p = other as Player;
return p != null && Equals(p);
}
protected bool Equals(Player other)
{
return string.Equals(Name, other.Name);
}
public override int GetHashCode()
{
return (Name != null ? Name.GetHashCode() : 0);
}
public static Player CreateEmpty()
{
return new Player
{
Name = string.Empty
};
}
}
}<file_sep># tournamenttracker-lib #
This is a class library that contains logic for managing records of tournaments of various kinds. The logic has been generated with Swiss-style tournaments in mind, however, randomizing is also an option.
The user can create tournaments with a desired number of rounds, set a player list, generate pairings for rounds (randomized or Swiss) and set scores for individual pairings. The swiss logic keeps track of pairings that have already been played to avoid the same pairing happening twice (unless it is not possible, due to a certain number of players / rounds). A thorough explanation of the swiss pairing logic can be seen <a href="https://github.com/akukolu/tournamenttracker-lib/blob/master/src/tournamenttracker.lib/Documents/PairingAlgorithm.txt">here</a>.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using TournamentTracker.Models;
using Xunit;
namespace TournamentTrackerTests.Models
{
public class TournamentTests
{
private static readonly Mock<IPairingGenerator> PairingGenerator = new Mock<IPairingGenerator>();
private static readonly Player P1 = new Player { Name = "P1" };
private static readonly Player P2 = new Player { Name = "P2" };
private static readonly Player P3 = new Player { Name = "P3" };
private static readonly Player P4 = new Player { Name = "P4" };
#region Tournament tests
[Fact]
public void CreatingTournamentWithZeroOrNegativeRounds_ThrowsArgumentExecption()
{
Assert.Throws<ArgumentException>(() => CreateTournament(-1));
}
[Fact]
public void CreatingTournament_InitializesEmptyUniqueRounds()
{
const int rounds = 5;
var tournament = CreateTournament(rounds);
Assert.Equal(rounds, tournament.Rounds.Count());
tournament.Rounds.ToList().ForEach(i => Assert.True(i.GetType() == typeof(Round)));
tournament.Rounds.ToList().ForEach(i => Assert.Equal(1, tournament.Rounds.Count(n => n == i)));
}
[Fact]
public void CreatingTournamentWithOddNumberOfPlayers_CreatesEmptyPlayerToPlayerList()
{
var tournament = CreateTournament(1);
tournament.Players = new[] { P1, P2, P3 };
Assert.Equal(4, tournament.Players.Count());
Assert.Contains(Player.CreateEmpty(), tournament.Players.ToList());
}
[Fact]
public void RandomizePairings_CallsPairingGeneratorShuffle()
{
var tournament = CreateTournament(1);
tournament.Players = new[] { P1, P2, P3, P4 };
PairingGenerator.Setup(pg => pg.Shuffle(It.IsAny<List<Player>>())).Returns(new List<Pairing>());
tournament.RandomizePairings();
PairingGenerator.Verify(pg => pg.Shuffle(It.IsAny<List<Player>>()), Times.Once);
}
[Fact]
public void SwissPairings_CallsPairingGeneratorSwiss()
{
var tournament = CreateTournament(1);
tournament.Players = new[] { P1, P2, P3, P4 };
PairingGenerator.Setup(
pg => pg.Swiss(It.IsAny<IOrderedEnumerable<KeyValuePair<Player, int>>>(), It.IsAny<IList<Pairing>>()))
.Returns(new List<Pairing>())
.Verifiable();
tournament.SwissPairings();
PairingGenerator.Verify(
pg => pg.Swiss(It.IsAny<IOrderedEnumerable<KeyValuePair<Player, int>>>(), It.IsAny<IList<Pairing>>()));
}
[Fact]
public void ModifyingPlayerList_ResetsRounds()
{
var tournament = new Tournament(new PairingGenerator(), 1) { Players = new[] { P1, P2 } };
var round = tournament.Rounds.First();
round.Pairings = tournament.RandomizePairings();
Assert.NotNull(tournament.Rounds.First().Pairings);
tournament.Players = new[] { P1, P2, P3 };
Assert.NotEqual(round, tournament.Rounds.First());
Assert.Empty(tournament.Rounds.First().Pairings);
}
/// <summary>
/// Four players play two rounds, scoring as follows (round scores in brackets):
///
/// Round 1: Round 2 Total
/// P1 (12) vs P2 (8) P4 (13) vs P1 (7) P1 = 19 P3 = 11
/// P3 (1) vs P4 (19) P2 (10) vs P3 (10) P2 = 18 P4 = 32
/// </summary>
[Fact]
public void GetPlayerStandings_CalculatesScoresFromAllRounds()
{
var tournament = new Tournament(new PairingGenerator(), 3)
{
Players = new List<Player> { P1, P2, P3, P4 }
};
var pairings = tournament.SwissPairings().ToList();
pairings[0].SetScore(12, 8);
pairings[1].SetScore(1, 19);
tournament.Rounds.ElementAt(0).Pairings = pairings;
pairings = tournament.SwissPairings().ToList();
pairings[0].SetScore(13, 7);
pairings[1].SetScore(10, 10);
tournament.Rounds.ElementAt(1).Pairings = pairings;
var standings = tournament.GetPlayerStandings();
VerifyPlayersStandingWithScore(standings.ElementAt(0), P4, 32);
VerifyPlayersStandingWithScore(standings.ElementAt(1), P1, 19);
VerifyPlayersStandingWithScore(standings.ElementAt(2), P2, 18);
VerifyPlayersStandingWithScore(standings.ElementAt(3), P3, 11);
}
#endregion
#region Round tests
[Fact]
public void CreateRound_InitializesRoundWithEmptyPairings()
{
var round = new Round();
Assert.NotNull(round.Pairings);
Assert.Empty(round.Pairings);
}
[Fact]
public void GetStandings_ReturnsPlayersWithScoresInDescOrder()
{
var tournament = new Tournament(new PairingGenerator(), 2) { Players = new[] { P1, P2, P3, P4 } };
var pairings = tournament.RandomizePairings().ToList();
pairings[0].SetScore(15, 5);
pairings[1].SetScore(10, 10);
PairingGenerator.Setup(
pg => pg.Swiss(It.IsAny<IOrderedEnumerable<KeyValuePair<Player, int>>>(), It.IsAny<IList<Pairing>>()))
.Returns(pairings);
var standings = new Round { Pairings = pairings }.GetStandings().Select(i => i.Value).ToList();
Assert.Equal(tournament.Players.Count(), standings.Count);
Assert.Equal(standings, standings.OrderByDescending(i => i));
}
/// <summary>
/// Initial pairings are:
/// P1 vs P2
/// P3 vs P4
/// After swapping P1 and P4, pairings are:
/// P4 vs P2
/// P3 vs P1
/// After second swap (P2 and P1), pairings are:
/// P4 vs P1
/// P3 vs P2
/// </summary>
[Fact]
public void Swap_ChangesPlacesOfTwoPlayersInRound()
{
var p1 = new Player { Name = "P1" };
var p2 = new Player { Name = "P2" };
var p3 = new Player { Name = "P3" };
var p4 = new Player { Name = "P4" };
var tournament = new Tournament(new PairingGenerator(), 1) { Players = new[] { p1, p2, p3, p4 } };
var pairings = tournament.SwissPairings().ToList();
var round = tournament.Rounds.ElementAt(0);
round.Pairings = pairings;
round.Swap(pairings.ElementAt(0).Player1, pairings.ElementAt(1).Player2);
Assert.Equal(p4, pairings[0].Player1);
Assert.Equal(p2, pairings[0].Player2);
Assert.Equal(p3, pairings[1].Player1);
Assert.Equal(p1, pairings[1].Player2);
round.Swap(p2, p1);
Assert.Equal(p4, pairings[0].Player1);
Assert.Equal(p1, pairings[0].Player2);
Assert.Equal(p3, pairings[1].Player1);
Assert.Equal(p2, pairings[1].Player2);
}
#endregion
#region Pairing tests
[Fact]
public void SetScore_AddsScoresForBothPlayers()
{
var pairing = new Pairing(new Player { Name = "P1" }, new Player { Name = "P2" });
pairing.SetScore(9, 12);
Assert.Equal(9, pairing.P1Score);
Assert.Equal(12, pairing.P2Score);
}
[Fact]
public void ContainsPlayer_ReturnsTrueIfPlayerIsInPairing()
{
var players = new[] { P1, P2, P3 };
var pairing = new Pairing(players[0], players[1]);
Assert.True(pairing.ContainsPlayers(players[0]));
Assert.True(pairing.ContainsPlayers(players[1]));
Assert.False(pairing.ContainsPlayers(players[2]));
Assert.False(pairing.ContainsPlayers(new Player { Name = "foo" }));
}
[Fact]
public void ContainsPlayers_ReturnsTrueIfBothPlayersExistInPairing()
{
var pairing = new Pairing(P1, P2);
Assert.False(pairing.ContainsPlayers(P1, P3));
Assert.False(pairing.ContainsPlayers(P3, P2));
Assert.True(pairing.ContainsPlayers(P1, P2));
Assert.True(pairing.ContainsPlayers(P2, P1));
}
[Fact]
public void GetOpponent_ReturnsPlayersOpponentOrThrowsException()
{
var players = new[] { P1, P2, P3 };
var tournament = new Tournament(new PairingGenerator(), 1) { Players = players };
tournament.Rounds.ElementAt(0).Pairings = tournament.SwissPairings();
Assert.Equal(players[0], tournament.Rounds.ElementAt(0).Pairings.ElementAt(0).GetOpponent(players[1]));
Assert.Equal(Player.CreateEmpty(), tournament.Rounds.ElementAt(0).Pairings.ElementAt(1).GetOpponent(players[2]));
Assert.Throws<ArgumentException>(() => tournament.Rounds.ElementAt(0).Pairings.ElementAt(0).GetOpponent(new Player { Name = "P4" }));
}
#endregion
#region Helper methods
private static Tournament CreateTournament(int numberOfRounds)
{
return new Tournament(PairingGenerator.Object, numberOfRounds);
}
private static void VerifyPlayersStandingWithScore(KeyValuePair<Player, int> standing, Player player, int score)
{
Assert.Equal(player, standing.Key);
Assert.Equal(score, standing.Value);
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace TournamentTracker.Models
{
public class Round
{
public IEnumerable<Pairing> Pairings { get; set; }
public Round()
{
Pairings = new Pairing[0];
}
public IOrderedEnumerable<KeyValuePair<Player, int>> GetStandings()
{
var standings = new Dictionary<Player, int>();
foreach (var i in Pairings)
{
standings.Add(i.Player1, i.P1Score);
standings.Add(i.Player2, i.P2Score);
}
return standings.OrderByDescending(i => i.Value);
}
public int GetPlayerScore(Player player)
{
foreach (var i in Pairings)
{
if (player.Equals(i.Player1))
{
return i.P1Score;
}
if (player.Equals(i.Player2))
{
return i.P2Score;
}
}
throw new ArgumentException("Player not found!");
}
public void Swap(Player first, Player second)
{
var pairing1 = Pairings.FirstOrDefault(i => i.ContainsPlayers(first));
var pairing2 = Pairings.FirstOrDefault(i => i.ContainsPlayers(second));
if (pairing1 == null || pairing2 == null)
{
throw new ArgumentException("Could not swap players! Requested player was not found");
}
pairing1.ReplacePlayer(first, second);
pairing2.ReplacePlayer(second, first);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using TournamentTracker.Models;
using Xunit;
namespace TournamentTrackerTests.Models
{
public class PairingGeneratorTests
{
private readonly IPairingGenerator _generator = new PairingGenerator();
private static readonly Player P1 = new Player { Name = "P1" };
private static readonly Player P2 = new Player { Name = "P2" };
private static readonly Player P3 = new Player { Name = "P3" };
private static readonly Player P4 = new Player { Name = "P4" };
private static readonly Player P5 = new Player { Name = "P5" };
private static readonly Player P6 = new Player { Name = "P6" };
[Fact]
public void AfterShuffling_PairingsContainSamePlayers()
{
var p1 = new[] { P1, P2, P3, P4 };
var p2 = new List<Player>();
var pairings = _generator.Shuffle(p1);
foreach (var i in pairings)
{
p2.Add(i.Player1);
p2.Add(i.Player2);
}
Assert.Empty(p1.Where(item => item != null && !p2.Contains(item)));
Assert.Empty(p2.Where(item => item != null && !p1.Contains(item)));
}
[Fact]
public void Shuffle_ThrowsExceptionOnOddNumberOfPlayers()
{
var p1 = new[] { P1, P2, P3 };
Assert.Throws<ArgumentException>(() => _generator.Shuffle(p1));
}
[Fact]
public void Swiss_CreatesPairingsByScore()
{
var p1 = new Dictionary<Player, int>
{
{ P1, 4 },
{ P2, 1 },
{ P3, 18 },
{ P4, 4 },
{ P5, 12 },
{ Player.CreateEmpty(), 0 }
};
var p2 = new List<Player>();
var pairings = _generator.Swiss(p1.OrderBy(i => i.Value), new List<Pairing>());
foreach (var i in pairings)
{
p2.Add(i.Player1);
p2.Add(i.Player2);
}
var orderedPlayerList = p2.Where(p => p != null).ToList();
Assert.Empty(p1.Select(p => p.Key).ToList().Where(item => !orderedPlayerList.Contains(item)));
Assert.Empty(orderedPlayerList.Where(item => !p1.Select(p => p.Key).Contains(item)));
Assert.Equal(p1.OrderByDescending(i => i.Value).Select(i => i.Key), orderedPlayerList);
}
[Fact]
public void Swiss_ThrowsExceptionOnOddNumberOfPlayers()
{
var p1 = new Dictionary<Player, int>
{
{ P1, 0 },
{ P2, 0 },
{ P3, 0 }
};
Assert.Throws<ArgumentException>(() => _generator.Swiss(p1.OrderBy(i => i.Value), new List<Pairing>()));
}
/// <summary>
/// Players play three rounds according to the following table.
/// Total score before round is displayed in brackets.
/// See PairingAlgorithm.txt for details.
/// </summary>
[Fact]
public void Swiss_AvoidsCreatingSamePairingTwice()
{
var tournament = new Tournament(new PairingGenerator(), 3) { Players = new[] { P1, P2, P3, P4, P5, P6 } };
var round = tournament.Rounds.First();
round.Pairings = tournament.SwissPairings().ToList();
round.Pairings.ElementAt(0).SetScore(11, 9); //P1 vs P2
round.Pairings.ElementAt(1).SetScore(0, 20); //P3 vs P4
round.Pairings.ElementAt(2).SetScore(10, 10); //P5 vs P6
var round2 = tournament.Rounds.ElementAt(1);
round2.Pairings = tournament.SwissPairings().ToList();
round2.Pairings.ElementAt(0).SetScore(1, 19); //P4 vs P1
round2.Pairings.ElementAt(1).SetScore(0, 20); //P5 vs P2
round2.Pairings.ElementAt(2).SetScore(0, 20); //P6 vs P3
var round3 = tournament.Rounds.ElementAt(2);
round3.Pairings = tournament.SwissPairings().ToList();
VerifyPairing(round3.Pairings.ElementAt(0), P1, P3);
VerifyPairing(round3.Pairings.ElementAt(1), P2, P6);
VerifyPairing(round3.Pairings.ElementAt(2), P4, P5);
}
/// <summary>
/// Four Players play four rounds, but unique pairing is only possible for the first three rounds.
/// Total score before round is displayed in brackets. Note that the last player is EMPTY
///
/// Round 1: Round 2: Round 3: Round 4:
/// P1 (0) vs P2 (0) P1 (20) vs P3 (20) P3 (40) vs P2 (20) P1 (43) vs P3 (43)
/// P3 (0) vs EMPTY P2 (0) vs EMPTY P1 (23) vs EMPTY P2 (34) vs EMPTY
/// </summary>
[Fact]
public void Swiss_CreatesSamePairingsIfUniqueNotPossible()
{
var tournament = new Tournament(new PairingGenerator(), 4) { Players = new[] { P1, P2, P3 } };
var empty = Player.CreateEmpty();
var round = tournament.Rounds.First();
round.Pairings = tournament.SwissPairings().ToList();
round.Pairings.ElementAt(0).SetScore(20, 0);
round.Pairings.ElementAt(1).SetScore(20, 0);
var round2 = tournament.Rounds.ElementAt(1);
round2.Pairings = tournament.SwissPairings().ToList();
round2.Pairings.ElementAt(0).SetScore(3, 17);
round2.Pairings.ElementAt(1).SetScore(20, 0);
var round3 = tournament.Rounds.ElementAt(2);
round3.Pairings = tournament.SwissPairings().ToList();
round3.Pairings.ElementAt(0).SetScore(6, 14);
round3.Pairings.ElementAt(1).SetScore(20, 0);
var round4 = tournament.Rounds.ElementAt(3);
round4.Pairings = tournament.SwissPairings().ToList();
VerifyPairing(round4.Pairings.ElementAt(0), P1, P3);
VerifyPairing(round4.Pairings.ElementAt(1), P2, empty);
}
private static void VerifyPairing(Pairing pairing, Player p1, Player p2)
{
Assert.Equal(p1, pairing.Player1);
Assert.Equal(p2, pairing.Player2);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace TournamentTracker.Models
{
public class PairingGenerator : IPairingGenerator
{
private const int SwissTimeout = 5000;
public IEnumerable<Pairing> Shuffle(IList<Player> players)
{
ValidatePlayerCount(players);
var pairings = new List<Pairing>();
var shuffled = players.OrderBy(i => Guid.NewGuid()).ToList();
for (var i = 0; i < shuffled.Count; i += 2)
{
pairings.Add(new Pairing(shuffled[i], shuffled[i + 1]));
}
return pairings;
}
/// <summary>
/// Pairs the players against each other in swiss format, e.g. top player plays
/// against the second, third against the fourth and so on. Avoids creating the
/// same pairing twice. See the PairingAlgorithm.txt document for details.
/// </summary>
public IEnumerable<Pairing> Swiss(IOrderedEnumerable<KeyValuePair<Player, int>> standings, IList<Pairing> history)
{
ValidatePlayerCount(standings.Select(i => i.Key));
var players = standings.OrderByDescending(i => i.Value).Select(i => i.Key).ToList();
var pairings = new Stack<Pairing>();
var timer = Stopwatch.StartNew();
while (!AllPlayersPaired(pairings, players))
{
TryAddPairing(pairings, players, history);
if (timer.ElapsedMilliseconds > SwissTimeout)
{
throw new TimeoutException("The requested operation took too long to complete.");
}
}
return pairings.ToArray().Reverse();
}
#region Private methods
private static void TryAddPairing(Stack<Pairing> pairings, ICollection<Player> players, IList<Pairing> history)
{
var unpaired = players.Where(i => !pairings.Any(j => j.ContainsPlayers(i))).ToList();
var pairing = GetUniquePairing(players, unpaired, history);
if (pairing != null)
{
pairings.Push(pairing);
return;
}
history.Add(pairings.Peek());
pairings.Pop();
}
private static Pairing GetUniquePairing(ICollection<Player> players, IList<Player> unpaired, IList<Pairing> history)
{
for (var i = 0; i < unpaired.Count; i++)
{
for (var j = i + 1; j < unpaired.Count; j++)
{
var pairing = new Pairing(unpaired[i], unpaired[j]);
if (IsUniquePairingPossible(players, history) && PlayersHavePlayedBefore(history, pairing))
{
continue;
}
return pairing;
}
}
return null;
}
private static bool AllPlayersPaired(IEnumerable<Pairing> pairings, IEnumerable<Player> players)
{
return players.All(i => pairings.Any(p => p.ContainsPlayers(i)));
}
private static bool PlayersHavePlayedBefore(IEnumerable<Pairing> history, Pairing pairing)
{
return history.Any(p => p.ContainsPlayers(pairing.Player1, pairing.Player2));
}
/// <summary>
/// Check if finding a unique pairing is possible.
/// </summary>
/// <param name="players">Player list</param>
/// <param name="history">Pairing history</param>
/// <returns>False if any player has played against every other player, true otherwise</returns>
private static bool IsUniquePairingPossible(ICollection<Player> players, IEnumerable<Pairing> history)
{
return players.All(i => history.Count(h => h.ContainsPlayers(i)) < players.Count - 1);
}
private static void ValidatePlayerCount(IEnumerable<Player> players)
{
if (players.Count() % 2 != 0)
{
throw new ArgumentException("Can't create pairings from an odd number of players");
}
}
#endregion
}
}<file_sep>using System;
using System.Globalization;
using System.Linq;
namespace TournamentTracker.Models
{
public class Pairing
{
public Player Player1 { get; set; }
public Player Player2 { get; set; }
public int P1Score { get; private set; }
public int P2Score { get; private set; }
public Pairing(Player p1, Player p2)
{
Player1 = p1;
Player2 = p2;
}
public void SetScore(int p1, int p2)
{
P1Score = p1;
P2Score = p2;
}
public bool ContainsPlayers(params Player[] other)
{
return other.All(player => player.Equals(Player1) || player.Equals(Player2));
}
public Player GetOpponent(Player player)
{
if (!ContainsPlayers(player))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Player '{0}' does not exist in this pairing", player.Name));
}
return player.Equals(Player1) ? Player2 : Player1;
}
public void ReplacePlayer(Player initial, Player replacement)
{
if (Player1.Equals(initial))
{
Player1 = replacement;
}
else if (Player2.Equals(initial))
{
Player2 = replacement;
}
else
{
throw new ArgumentException("Requested player could not be found!");
}
}
}
} | 64240f6dde910ae4d2803d987095e5453de4b5e7 | [
"Markdown",
"C#"
]
| 9 | C# | akukolu/tournamenttracker-lib | d91c398a8fb6ec28f4e7b5291d7a26af1dee2d82 | e191454a7f023332525a823abce48e0bd540e89a |
refs/heads/master | <repo_name>Mukulikaa/bookroast<file_sep>/requirements.txt
alembic==1.4.2
astroid==2.4.1
cachelib==0.1
certifi==2020.4.5.2
chardet==3.0.4
click==7.1.2
colorama==0.4.3
Flask==1.1.2
Flask-Cors==3.0.8
Flask-Session==0.3.2
Flask-SQLAlchemy==2.4.1
Flask-WTF==0.14.3
Flask-Login
gunicorn==20.0.4
idna==2.9
isort==4.3.21
itsdangerous==1.1.0
Jinja2==2.11.2
lazy-object-proxy==1.4.3
Mako==1.1.3
MarkupSafe==1.1.1
mccabe==0.6.1
playsound==1.2.2
psycopg2-binary==2.8.5
pylint==2.5.2
python-dateutil==2.8.1
python-editor==1.0.4
requests==2.23.0
six==1.15.0
SQLAlchemy==1.3.17
toml==0.10.1
urllib3==1.25.9
Werkzeug==1.0.1
wrapt==1.12.1
WTForms==2.3.1
<file_sep>/app.py
import os
import requests
from flask import Flask, session, flash
from flask import render_template, request, redirect
from flask import url_for
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, EqualTo
from flask_login import LoginManager, login_required, login_user, logout_user, current_user
from models import *
app = Flask(__name__)
# Check for environment variable
#if not os.getenv("DATABASE_URL"):
#raise RuntimeError("DATABASE_URL is not set")
# Set up database
app.config["SQLALCHEMY_DATABASE_URI"] = "postgres://eegfjegitfwjpd:10dc44b25f3a970cc60e798dddcf6e0d60719873542f35468bef133c5ce1965b@ec2-54-246-89-234.eu-west-1.compute.amazonaws.com:5432/d6o4kqf8gea8g3"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
#engine = create_engine(os.getenv("DATABASE_URL"))
#db = scoped_session(sessionmaker(bind=engine))
#set DATABASE_URL=postgres://eegfjegitfwjpd:10dc44b25f3a970cc60e798dddcf6e0d60719873542f35468bef133c5ce1965b@ec2-54-246-89-234.eu-west-1.compute.amazonaws.com:5432/d6o4kqf8gea8g3
#API info
#APIkey: <KEY>
#APIsecret: 4aG2mrZiYhYQASBkqQtZkDlAepY3c3yKDIXPT9B0
#import requests
#res = requests.get("https://www.goodreads.com/book/review_counts.json", params={"key": "KEY", "isbns": "9781632168146"})
#print(res.json())
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SECRET_KEY'] = '#6ghu439f0$'
#Session(app)
class RegisterForm(FlaskForm):
fname = StringField('First Name', validators=[DataRequired()])
lname = StringField('Last Name', validators=[DataRequired()])
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('<PASSWORD>',validators=[DataRequired(),EqualTo('confirm', message='Passwords must match')])
confirm = PasswordField('<PASSWORD> Password')
remember_me = BooleanField('Remember Me')
submit = SubmitField('Register')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('<PASSWORD>', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Log In')
login_manager = LoginManager()
login_manager.init_app(app)
@login_manager.user_loader
def user_loader(user_id):
"""Given *user_id*, return the associated User object.
:param unicode user_id: user_id (email) user to retrieve
"""
return users.query.get(user_id)
data = []
@app.route("/")
def index():
return render_template('index.html')
@app.route("/gh6?w")
@login_required
def index1():
book = books.query.filter_by(ratings = 4.5).all()
return render_template('index1.html', book=book)
@app.route("/login", methods=["GET","POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
try:
user = users.query.filter_by(username=form.username.data).first_or_404()
if (form.password.data==user.password):
user.authenticated = True
#db.session.add(user)
db.session.commit()
login_user(user)
if form.remember_me.data==True:
session.permanent = True
return redirect(url_for("index1"))
else:
return render_template('login.html', form=form, error='Incorrect Username/Password.')
except:
return render_template('login.html', form=form, error='Incorrect Username/Password.')
return render_template('login.html', title='Sign In', form=form)
@app.route("/register", methods=["GET","POST"])
def register():
form = RegisterForm()
if form.validate_on_submit():
try:
user = users(fname=form.fname.data, lname=form.lname.data, username=form.username.data, password=form.password.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
except:
return render_template("register.html", title='Sign Up', form=form, error='Username/password already taken!')
return render_template("register.html", title='Sign Up', form=form)
@app.route("/logout", methods=["GET"])
@login_required
def logout():
"""Logout the current user."""
user = current_user
user.authenticated = False
db.session.commit()
logout_user()
return redirect("/")
@app.route("/results", methods=["GET","POST"])
@login_required
def search():
global data
if request.method == "POST":
term = request.form.get("search").title()
print(term)
data = []
book = books.query.filter(books.title.contains(term)).all()
for b in book:
data.append(b)
print("...")
author = books.query.filter(books.author.contains(term)).all()
for a in author:
data.append(a)
print(data)
isbn = books.query.filter(books.ISBN.contains(term)).all()
for i in isbn:
data.append(i)
print(data)
return render_template('books.html', data=data)
@app.route("/isbn/<string:isbn>", methods=['GET','POST'])
@login_required
def book(isbn):
book = books.query.filter_by(ISBN=isbn).first()
if request.method == 'POST':
review = request.form.get("review")
myreview = reviews(username = current_user.username , review_id = book.id, review = review)
db.session.add(myreview)
db.session.commit()
message = "Submitted succesfully"
review = reviews.query.filter_by(review_id=book.id).all()
db.session.close()
return render_template("book.html", book=book, review=review)
<file_sep>/models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class books(db.Model):
__tablename__= 'books'
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String, nullable=False)
author= db.Column(db.String, nullable=False)
pub_year= db.Column(db.Integer, nullable=False)
ISBN= db.Column(db.String, nullable=False)
ratings = db.Column(db.Float, nullable=True)
class users(db.Model):
__tablename__= 'users'
id = db.Column(db.Integer, primary_key=True)
fname = db.Column(db.String, nullable=False)
lname = db.Column(db.String, nullable=False)
username = db.Column(db.String,unique=True, nullable=False)
password = db.Column(db.String, unique=True, nullable=False)
authenticated = db.Column(db.Boolean, default=False)
def is_active(self):
"""True, as all users are active."""
return True
def get_id(self):
"""Return the email address to satisfy Flask-Login's requirements."""
return self.id
def is_authenticated(self):
"""Return True if the user is authenticated."""
return self.authenticated
def is_anonymous(self):
"""False, as anonymous users aren't supported."""
return False
class reviews(db.Model):
__tablename__= 'reviews'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, db.ForeignKey('users.username'))
review_id = db.Column(db.Integer, db.ForeignKey('books.id'))
review = db.Column(db.String, nullable=False )
| 3fe56d33edc6ff9435b666b2603435e73f3b13e3 | [
"Python",
"Text"
]
| 3 | Text | Mukulikaa/bookroast | 05a0b66f89db5aba239146405d3cc4ee80f1d018 | ce39a6851f37e7937d29fe64f7c5805ca90e14e1 |
refs/heads/master | <file_sep>#include "coin.h"
Coin::Coin()
{
location = {0, 25, 0};
radius = 10;
thickness = 8;
rotationSpeed = 0.1;
color = {1.0, 0.8, 0.1, 1.0};
hoverPeriod = 60;
tickNumberModHoverPeriod = 0;
hoverSpeed = hoverPeriod / (2*PI);
hoverAmplitude = 6;
hoverScaleFactor = hoverAmplitude*2*PI/hoverPeriod;
initializeSolids();
initializeHitbox();
}
Coin::Coin(Point inputLocation, double inputRadius, double inputThickness, double inputRotationSpeed,
RGBAcolor inputColor, int inputHoverPeriod, int inputHoverAmplitude)
{
location = inputLocation;
radius = inputRadius;
thickness = inputThickness;
rotationSpeed = inputRotationSpeed;
color = inputColor;
hoverPeriod = inputHoverPeriod;
hoverAmplitude = inputHoverAmplitude;
tickNumberModHoverPeriod = 0;
hoverSpeed = hoverPeriod / (2*PI);
hoverScaleFactor = hoverAmplitude*2*PI/hoverPeriod;
initializeSolids();
initializeHitbox();
}
void Coin::initializeSolids()
{
std::shared_ptr<EllipticCyl> coinShape = std::make_shared<EllipticCyl>(EllipticCyl(location, color, 2*radius,
thickness, 2*radius, {1,1,1,1}, Medium));
coinShape->rotate(-PI/2, 0, 0);
solids.push_back(coinShape);
}
void Coin::initializeHitbox()
{
hitbox = RecPrism(location, {1,0,0,0.5}, 2*radius, 2*radius, thickness, {1,1,1,1});
}
// Getters
Point Coin::getLocation() const
{
return location;
}
double Coin::getRadius() const
{
return radius;
}
double Coin::getThickness() const
{
return thickness;
}
double Coin::getXZAngle() const
{
return xzAngle;
}
void Coin::setXZAngle(double inputAngle)
{
if(inputAngle > 2*PI)
{
xzAngle = inputAngle - 2*PI;
}
else if(inputAngle < 0)
{
xzAngle = inputAngle + 2*PI;
}
else
{
xzAngle = inputAngle;
}
}
void Coin::move(double deltaX, double deltaY, double deltaZ)
{
movePoint(location, deltaX, deltaY, deltaZ);
for(std::shared_ptr<Solid> s : solids)
{
s->move(deltaX, deltaY, deltaZ);
}
hitbox.move(deltaX, deltaY, deltaZ);
}
void Coin::draw(double lightLevel) const
{
for(std::shared_ptr<Solid> s : solids)
{
s->draw(lightLevel);
}
}
void Coin::tick()
{
for(std::shared_ptr<Solid> s : solids)
{
s->rotate(0, rotationSpeed, 0);
}
hitbox.rotate(0, rotationSpeed, 0);
tickNumberModHoverPeriod++;
hoverSpeed = hoverScaleFactor*sin(2*PI*tickNumberModHoverPeriod / hoverPeriod);
move(0, hoverSpeed, 0);
if(tickNumberModHoverPeriod == hoverPeriod)
{
tickNumberModHoverPeriod = 0;
}
}
bool Coin::hasCollision(Point p, double buffer) const
{
return correctRectangularPrism(p, buffer, hitbox.getCenter(), hitbox.getXWidth(), hitbox.getYWidth(), hitbox.getZWidth(), hitbox.getXZAngle()) != std::experimental::nullopt;
}<file_sep>#include "lampPost.h"
LampPost::LampPost()
{
location = {0, 15, 0};
poleRadius = 4;
poleHeight = 30;
lightRadius = 5;
lightHeight = 8;
baseHeight = poleHeight/6;
poleColor = {0, 0.5, 0.1, 1.0};
lightColor = {1.0, 1.0, 0.5, 1.0};
lightIntensity = 8;
initializeSolids();
}
LampPost::LampPost(Point inputLocation, double inputPoleRadius, double inputPoleHeight, double inputLightRadius,
double inputLightHeight, RGBAcolor inputPoleColor, RGBAcolor inputLightColor, double inputLightIntensity)
{
location = inputLocation;
poleRadius = inputPoleRadius;
poleHeight = inputPoleHeight;
lightRadius = inputLightRadius;
lightHeight = inputLightHeight;
baseHeight = poleHeight/6;
poleColor = inputPoleColor;
lightColor = inputLightColor;
lightIntensity = inputLightIntensity;
initializeSolids();
}
void LampPost::initializeSolids()
{
// Make the base (cone-shaped)
Point baseCenter = {location.x, baseHeight/2, location.z};
double baseRadius = 3.5*poleRadius;
double baseTopRadius = 2.5*poleRadius;
std::shared_ptr<EllipticCyl> base = std::make_shared<EllipticCyl>(EllipticCyl(baseCenter, poleColor,
2*baseRadius, baseHeight, 2*baseRadius, {1,1,1,1},
2*baseTopRadius, 2*baseTopRadius,
NoLines));
solids.push_back(base);
// Pole
Point poleCenter = {location.x, baseCenter.y + baseHeight/2 + poleHeight/2, location.z};
solids.push_back(std::make_shared<EllipticCyl>(EllipticCyl(poleCenter, poleColor, 2*poleRadius, poleHeight, 2*poleRadius, {1,1,1,1}, NoLines)));
// Light bulb
Point lightCenter = getLightLocation();
solids.push_back(std::make_shared<EllipticCyl>(EllipticCyl(lightCenter, lightColor, 2*lightRadius, lightHeight, 2*lightRadius, {1,1,1,1}, NoLines)));
// Light covering
RGBAcolor glass = {1.0, 1.0, 1.0, 0.5};
solids.push_back(std::make_shared<Frustum>(Frustum(lightCenter, glass, 2*baseTopRadius, lightHeight, 2*baseTopRadius, poleColor, 2*baseRadius, 2*baseRadius)));
// Roof
double roofHeight = lightHeight/3;
Point roofCenter = {location.x, lightCenter.y + lightHeight/2 + roofHeight/2, location.z};
solids.push_back(std::make_shared<Frustum>(Frustum(roofCenter, poleColor, 2*baseRadius+1, roofHeight, 2*baseRadius+1, {1,1,1,1}, poleRadius, poleRadius, NoLines)));
}
// Getters
Point LampPost::getLocation() const
{
return location;
};
double LampPost::getLightIntensity() const
{
return lightIntensity;
};
Point LampPost::getLightLocation() const
{
return {location.x, baseHeight + poleHeight + lightHeight/2, location.z};
};
void LampPost::draw(double lightLevel) const
{
for(std::shared_ptr<Solid> s : solids)
{
s->draw(lightLevel);
}
};<file_sep>#ifndef STREETNIGHT_COIN_H
#define STREETNIGHT_COIN_H
#include "recPrism.h"
#include "ellipticCyl.h"
class Coin
{
private:
Point location;
double radius;
double thickness;
double xzAngle;
int hoverPeriod;
int hoverAmplitude;
double hoverScaleFactor; // chain rule from the derivative of sin()
int tickNumberModHoverPeriod;
double hoverSpeed;
double rotationSpeed;
RGBAcolor color;
std::vector<std::shared_ptr<Solid>> solids;
RecPrism hitbox;
public:
Coin();
Coin(Point inputLocation, double inputRadius, double inputThickness, double inputRotationSpeed,
RGBAcolor inputColor, int inputHoverPeriod, int inputHoverAmplitude);
void initializeSolids();
void initializeHitbox();
// Getters
Point getLocation() const;
double getRadius() const;
double getThickness() const;
double getXZAngle() const;
void setXZAngle(double inputAngle);
void move(double deltaX, double deltaY, double deltaZ);
void draw(double lightLevel) const;
void tick();
bool hasCollision(Point p, double buffer) const;
};
#endif //STREETNIGHT_COIN_H
<file_sep>#include "gameManager.h"
GameManager::GameManager()
{
screenWidth = 1024;
screenHeight = 512;
chunkSize = 24;
renderRadius = 20;
viewDistance = renderRadius*chunkSize;
initializePlayer();
updateCurrentChunks();
initializeButtons();
makeInstructions();
initializePlayerLight();
makeTrain();
}
GameManager::GameManager(int inputScreenWidth, int inputScreenHeight, int inputChunkSize, int inputRenderRadius)
{
screenWidth = inputScreenWidth;
screenHeight = inputScreenHeight;
chunkSize = inputChunkSize;
renderRadius = inputRenderRadius;
viewDistance = renderRadius*chunkSize;
initializePlayer();
updateCurrentChunks();
initializeButtons();
makeInstructions();
initializePlayerLight();
makeTrain();
}
// =================================
//
// Initialization Functions
//
// =================================
void GameManager::initializePlayer()
{
Point playerStartLoc = {0, PLAYER_HEIGHT/2, 0};
Point playerStartLook = {0, PLAYER_HEIGHT/2, -10};
Point playerStartUp = {0, PLAYER_HEIGHT, 0};
player = Player(playerStartLoc, playerStartLook, playerStartUp, PLAYER_SPEED, MOUSE_SENSITIVITY,
PLAYER_HEIGHT, PLAYER_RADIUS, MAX_DISTANCE_FROM_SPAWN, GRAVITY, PLAYER_JUMP_AMOUNT);
currentPlayerChunkID = getChunkIDContainingPoint(player.getLocation(), chunkSize);
playerHealth = MAX_PLAYER_HEALTH;
playerScore = 0;
}
void GameManager::initializeButtons()
{
playButton = Button(screenWidth/2, screenHeight/2, BUTTON_WIDTH, BUTTON_HEIGHT,
BUTTON_RADIUS, "Play", PLAY_BUTTON_COLOR, BUTTON_TEXT_COLOR, PLAY_BUTTON_COLOR_H);
playAgainButton = Button(screenWidth/2, screenHeight/2, BUTTON_WIDTH, BUTTON_HEIGHT,
BUTTON_RADIUS, "Play Again", PLAY_BUTTON_COLOR, BUTTON_TEXT_COLOR, PLAY_BUTTON_COLOR_H);
continueButton = Button(screenWidth/2, screenHeight/2, BUTTON_WIDTH, BUTTON_HEIGHT,
BUTTON_RADIUS, "Continue", PLAY_BUTTON_COLOR, BUTTON_TEXT_COLOR, PLAY_BUTTON_COLOR_H);
quitButton = Button(screenWidth/2, screenHeight/2 - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT,
BUTTON_RADIUS, "Quit", QUIT_BUTTON_COLOR, BUTTON_TEXT_COLOR, QUIT_BUTTON_COLOR_H);
}
void GameManager::makeInstructions()
{
instructions.emplace_back("Use w,a,s,d to move and spacebar to jump. Press p to pause.");
instructions.emplace_back("Earn points by collecting coins. If a train hits you, you will lose health.");
}
void GameManager::initializePlayerLight()
{
playerLight = {player.getLocation(), player.getXZAngle(), player.getYAngle(), PLAYER_LIGHT_FOV, MAX_LIGHT_LEVEL};
}
// ===========================
//
// Getters
//
// ===========================
Player GameManager::getPlayer() const
{
return player;
}
bool GameManager::getWKey() const
{
return wKey;
}
bool GameManager::getAKey() const
{
return aKey;
}
bool GameManager::getSKey() const
{
return sKey;
}
bool GameManager::getDKey() const
{
return dKey;
}
bool GameManager::getSpacebar() const
{
return spacebar;
}
GameStatus GameManager::getCurrentStatus() const
{
return currentStatus;
}
bool GameManager::getCloseWindow() const
{
return closeWindow;
}
bool GameManager::getShowMouse() const
{
return showMouse;
}
// =============================
//
// Setters
//
// =============================
void GameManager::setWKey(bool input)
{
wKey = input;
player.setVelocity(wKey, aKey, sKey, dKey);
}
void GameManager::setAKey(bool input)
{
aKey = input;
player.setVelocity(wKey, aKey, sKey, dKey);
}
void GameManager::setSKey(bool input)
{
sKey = input;
player.setVelocity(wKey, aKey, sKey, dKey);
}
void GameManager::setDKey(bool input)
{
dKey = input;
player.setVelocity(wKey, aKey, sKey, dKey);
}
void GameManager::setSpacebar(bool input)
{
spacebar = input;
}
void GameManager::setCurrentStatus(GameStatus input)
{
currentStatus = input;
}
// Chunks
void GameManager::updateCurrentChunks()
{
// Update the list of current chunks
currentChunks = std::vector<std::shared_ptr<Chunk>>();
std::vector<Point2D> chunksInRadius = getChunkTopLeftCornersAroundPoint(currentPlayerChunkID, renderRadius);
for(Point2D p : chunksInRadius)
{
int index = point2DtoChunkID(p);
if(allSeenChunks.count(index) == 0) // if the chunk has never been seen before
{
// Create and add a new Chunk
allSeenChunks[index] = std::make_shared<Chunk>(p, chunkSize, CHUNK_GROUND_COLOR);
// Make a lamp post sometimes
if(rand() % 1000 < 4)
{
createRandomLampPost(allSeenChunks[index]->getCenter(), chunkSize);
}
}
currentChunks.push_back(allSeenChunks[index]);
}
}
// =================================
//
// Trains
//
// =================================
void GameManager::makeTrain()
{
// Make the train come from in front of the player
double randAngle = player.getXZAngle() + (rand() % 100)*PI/4 / 100 - (rand() % 100)*PI/2 / 100;
double x = player.getLocation().x + cos(randAngle)*viewDistance;
double y = TRAIN_HEIGHT/2;
double z = player.getLocation().z + sin(randAngle)*viewDistance;
Point trainLocation = {x, y, z};
Point trainTarget = predictMovement(trainLocation, TRAIN_SPEED, player.getLocation(), player.getVelocity());
double trainAngle = atan2(trainTarget.z - z, trainTarget.x - x);
train = Train(trainLocation, TRAIN_COLOR, TRAIN_WIDTH, TRAIN_HEIGHT, TRAIN_LENGTH, TRAIN_SPEED, trainAngle);
}
// =================================
//
// Coins
//
// =================================
void GameManager::spawnRandomlyLocatedCoin()
{
double distanceAwayFromPlayer = (rand() % 3*viewDistance/4) + 3*viewDistance/4;
double randAngle = (rand() % 100)*2*PI / 100;
double x = player.getLocation().x + cos(randAngle)*distanceAwayFromPlayer;
double y = COIN_FLOAT_HEIGHT + COIN_RADIUS;
double z = player.getLocation().z + sin(randAngle)*distanceAwayFromPlayer;
coins.push_back(std::make_shared<Coin>(Coin({x,y,z}, COIN_RADIUS, COIN_THICKNESS, COIN_ROTATION_SPEED, COIN_COLOR, COIN_HOVER_PERIOD, COIN_HOVER_AMPLITUDE)));
}
void GameManager::checkCoins()
{
int L = coins.size();
int i = 0;
while(i < L)
{
std::shared_ptr<Coin> c = coins[i];
double distanceFromPlayer = distance2d(c->getLocation(), player.getLocation());
// First check if the coin is too far away and should despawn
if(distanceFromPlayer > 2*viewDistance)
{
coins.erase(coins.begin() + i);
L -= 1;
i--;
}
// If not, check if the player is hitting the coin
else if(c->hasCollision(player.getLocation(), PLAYER_RADIUS))
{
coins.erase(coins.begin() + i);
playerScore++;
L -= 1;
i--;
}
else if(distanceFromPlayer < COIN_ATTRACTION_DISTANCE)
{
double angleToPlayer = xzAngleBetweenPoints(c->getLocation(), player.getLocation());
double deltaX = cos(angleToPlayer)*COIN_ATTRACTION_FORCE;
double deltaZ = sin(angleToPlayer)*COIN_ATTRACTION_FORCE;
c->move(deltaX, 0, deltaZ);
}
i++;
}
if(coins.size() < MAX_NUM_COINS)
{
spawnRandomlyLocatedCoin();
}
}
// =================================
//
// Player
//
// =================================
void GameManager::correctPlayerCollisions()
{
std::experimental::optional<Point> correctedPoint = train.correctCollision(player.getLocation(), 2*PLAYER_RADIUS);
if(correctedPoint)
{
player.moveToCorrectedLocation(*correctedPoint);
playerHealth -= TRAIN_DAMAGE_PER_TICK;
}
}
// =================================
//
// Camera
//
// =================================
Point GameManager::getCameraLocation() const
{
return player.getLocation();
}
Point GameManager::getCameraLookingAt() const
{
return player.getLookingAt();
}
Point GameManager::getCameraUp() const
{
return player.getUp();
}
// =================================
//
// Mouse
//
// =================================
void GameManager::reactToMouseMovement(int mx, int my, double theta)
{
if(currentStatus == Intro)
{
playButton.setIsHighlighted(playButton.containsPoint(mx, screenHeight - my));
quitButton.setIsHighlighted(quitButton.containsPoint(mx, screenHeight - my));
}
else if(currentStatus == Playing)
{
player.updateAngles(theta);
player.updateSphericalDirectionBasedOnAngles();
player.setVelocity(wKey, aKey, sKey, dKey);
}
else if(currentStatus == Paused)
{
continueButton.setIsHighlighted(continueButton.containsPoint(mx, screenHeight - my));
quitButton.setIsHighlighted(quitButton.containsPoint(mx, screenHeight - my));
}
else if(currentStatus == End)
{
playAgainButton.setIsHighlighted(playAgainButton.containsPoint(mx, screenHeight - my));
quitButton.setIsHighlighted(quitButton.containsPoint(mx, screenHeight - my));
}
}
void GameManager::reactToMouseClick(int mx, int my)
{
if(currentStatus == Intro)
{
if(playButton.containsPoint(mx, screenHeight - my))
{
showMouse = false;
currentStatus = Playing;
resetGame();
}
else if(quitButton.containsPoint(mx, screenHeight - my))
{
closeWindow = true;
}
}
else if(currentStatus == Playing)
{
}
else if(currentStatus == Paused)
{
if(continueButton.containsPoint(mx, screenHeight - my))
{
showMouse = false;
currentStatus = Playing;
}
else if(quitButton.containsPoint(mx,screenHeight - my))
{
closeWindow = true;
}
}
else if(currentStatus == End)
{
if(playAgainButton.containsPoint(mx, screenHeight - my))
{
showMouse = false;
resetGame();
}
else if(quitButton.containsPoint(mx,screenHeight - my))
{
closeWindow = true;
}
}
}
// ===============================
//
// Lighting
//
// ===============================
double GameManager::determineOverallLightLevelAt(Point p) const
{
double maxSeen = 0.0;
for(LightSource ls : lightSources)
{
double curIntensity = determineLightLevelAt(p, ls, LIGHT_FADE_FACTOR);
if(curIntensity > maxSeen)
{
maxSeen = curIntensity;
}
}
maxSeen = fmax(maxSeen, determineLightLevelAt(p, playerLight, LIGHT_FADE_FACTOR));
return fmin(1.0, maxSeen / MAX_LIGHT_LEVEL);
}
double GameManager::determineChunkLightLevel(Point p) const
{
double maxSeen = 0.0;
for(LightSource ls : lightSources)
{
double curIntensity = determineLightIntensityAt(p, ls, LIGHT_FADE_FACTOR);
if(curIntensity > maxSeen)
{
maxSeen = curIntensity;
}
}
maxSeen = fmax(maxSeen, determineLightIntensityAt(p, playerLight, LIGHT_FADE_FACTOR));
return fmin(1.0, maxSeen / MAX_LIGHT_LEVEL);
}
void GameManager::createRandomLampPost(Point chunkCenter, int chunkSize)
{
double x = chunkCenter.x + chunkSize/2 - (rand() % chunkSize);
double z = chunkCenter.z + chunkSize/2 - (rand() % chunkSize);
Point location = {x, LAMP_POST_HEIGHT/2, z};
std::shared_ptr<LampPost> lamp = std::make_shared<LampPost>(LampPost(location, LAMP_POST_RADIUS, LAMP_POST_HEIGHT,
LAMP_POST_RADIUS, LAMP_POST_HEIGHT/6, LAMP_POST_COLOR, LIGHT_COLOR, MAX_LIGHT_LEVEL/2));
lampPosts[lamp] = false;
lightSources.push_back({lamp->getLightLocation(), 0, 0, 2*PI, static_cast<int>(lamp->getLightIntensity())});
}
void GameManager::updateLampPostCloseness()
{
for(std::pair<std::shared_ptr<LampPost>, bool> element : lampPosts)
{
if(distance2d(element.first->getLocation(), player.getLocation()) < renderRadius*chunkSize)
{
lampPosts[element.first] = true;
}
else
{
lampPosts[element.first] = false;
}
}
}
// ================================
//
// Draw
//
// ================================
void GameManager::draw() const
{
if(currentStatus == Playing || currentStatus == Paused)
{
drawChunks();
drawLampPosts();
drawTrain();
drawCoins();
}
}
void GameManager::drawLampPosts() const
{
for(std::pair<std::shared_ptr<LampPost>, bool> element : lampPosts)
{
if(element.second)
{
element.first->draw(element.first->getLightIntensity() / MAX_LIGHT_LEVEL);
}
}
}
void GameManager::drawChunks() const
{
for(std::shared_ptr<Chunk> c : currentChunks)
{
double lightLevel = determineChunkLightLevel(c->getCenter());
if(lightLevel > 0.01) // for performance, don't draw if it's too dark
{
c->draw(lightLevel);
}
}
}
void GameManager::drawTrain() const
{
double lightLevel = determineOverallLightLevelAt(train.getLocation());
train.draw(lightLevel);
}
void GameManager::drawCoins() const
{
for(std::shared_ptr<Coin> c : coins)
{
if(distance2d(c->getLocation(), player.getLocation()) < viewDistance)
{
double lightLevel = determineOverallLightLevelAt(c->getLocation());
c->draw(lightLevel);
}
}
}
// ================================
//
// Tick
//
// ================================
void GameManager::tick()
{
if(currentStatus == Playing)
{
updateLampPostCloseness();
trainTick();
playerTick();
coinsTick();
checkForGameEnd();
}
}
void GameManager::playerTick()
{
player.tick();
if(spacebar)
{
player.tryToJump();
}
correctPlayerCollisions();
// Check if the player has entered a new chunk
int newPlayerChunkID = getChunkIDContainingPoint(player.getLocation(), chunkSize);
if(newPlayerChunkID != currentPlayerChunkID)
{
currentPlayerChunkID = newPlayerChunkID;
updateCurrentChunks();
}
playerLight.location = player.getLocation();
playerLight.xzAngle = player.getXZAngle();
playerLight.yAngle = player.getYAngle();
}
void GameManager::trainTick()
{
train.tick();
if(distance2d(train.getLocation(), player.getLocation()) > 1.5*viewDistance)
{
makeTrain();
}
}
void GameManager::coinsTick()
{
for(std::shared_ptr<Coin> c : coins)
{
c->tick();
}
checkCoins();
}
// ===========================================
//
// Game Management
//
// ===========================================
void GameManager::checkForGameEnd()
{
if(playerHealth < 1)
{
currentStatus = End;
showMouse = true;
}
}
void GameManager::resetGame()
{
initializePlayer();
updateCurrentChunks();
makeTrain();
currentStatus = Playing;
}
void GameManager::togglePaused()
{
if(currentStatus == Paused)
{
currentStatus = Playing;
showMouse = false;
}
else if(currentStatus == Playing)
{
currentStatus = Paused;
showMouse = true;
}
}
// UI
void GameManager::drawUI() const
{
if(currentStatus == Intro)
{
playButton.draw();
quitButton.draw();
displayInstructions();
}
else if(currentStatus == Playing)
{
drawCursor();
drawHealthBar();
displayPlayerScore();
}
else if(currentStatus == Paused)
{
continueButton.draw();
quitButton.draw();
}
else if(currentStatus == End)
{
displayFinalScore();
playAgainButton.draw();
quitButton.draw();
}
}
void GameManager::drawCursor() const
{
setGLColor(CURSOR_COLOR);
glBegin(GL_QUADS); // Draw a + shape with two quads
glVertex2f(screenWidth/2 - 5, screenHeight/2 + 2);
glVertex2f(screenWidth/2 - 5, screenHeight/2 - 2);
glVertex2f(screenWidth/2 + 5, screenHeight/2 - 2);
glVertex2f(screenWidth/2 + 5, screenHeight/2 + 2);
glVertex2f(screenWidth/2 - 2, screenHeight/2 + 5);
glVertex2f(screenWidth/2 - 2, screenHeight/2 - 5);
glVertex2f(screenWidth/2 + 2, screenHeight/2 - 5);
glVertex2f(screenWidth/2 + 2, screenHeight/2 + 5);
glEnd();
}
void GameManager::displayInstructions() const
{
setGLColor({1,1,1,1});
for(int i = 0; i < instructions.size(); i++)
{
std::string s = instructions[i];
glRasterPos2i(10, screenHeight - 15*i - 15);
for(const char &letter : s)
{
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, letter);
}
}
}
void GameManager::drawHealthBar() const
{
double dividingPoint = HEALTH_BAR_LENGTH * playerHealth / MAX_PLAYER_HEALTH;
setGLColor(HEALTH_BAR_HEALTH);
glBegin(GL_QUADS);
glVertex2f(0, screenHeight);
glVertex2f(0, screenHeight - HEALTH_BAR_HEIGHT);
glVertex2f(dividingPoint, screenHeight - HEALTH_BAR_HEIGHT);
glVertex2f(dividingPoint, screenHeight);
glEnd();
setGLColor(HEALTH_BAR_VOID);
glBegin(GL_QUADS);
glVertex2f(dividingPoint, screenHeight);
glVertex2f(dividingPoint, screenHeight - HEALTH_BAR_HEIGHT);
glVertex2f(HEALTH_BAR_LENGTH, screenHeight - HEALTH_BAR_HEIGHT);
glVertex2f(HEALTH_BAR_LENGTH, screenHeight);
glEnd();
}
void GameManager::displayPlayerScore() const
{
glColor4f(1.0, 1.0, 1.0, 1.0);
std::string score = "Score: " + std::to_string(playerScore);
glRasterPos2i(screenWidth - (20 * score.length()), screenHeight - 15);
for(const char &letter : score)
{
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, letter);
}
}
void GameManager::displayFinalScore() const
{
glColor4f(1.0, 1.0, 1.0, 1.0);
std::string score = "Final Score: " + std::to_string(playerScore);
glRasterPos2i(screenWidth/2 - (4 * score.length()), screenHeight - 15);
for(const char &letter : score)
{
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, letter);
}
}<file_sep># Streetnight
A 3D game where the user tries to collect coins in the dark. Streetlamps light things up, while
trains can damage you if you get hit. Use w,a,s,d, and spacebar to move around.
## Build Instructions
If you are on windows, you need to download freeglut, make the
directory C:/Program Files/Common Files/freeglut/, copy the
include/ and lib/ folders from freeglut into there, and copy
freeglut.dll from freeglut/bin/ into the cmake-build-debug/ folder.
If you are not on windows, maybe it will just work.
<file_sep>#ifndef FPS_TEMPLATE_CHUNK_H
#define FPS_TEMPLATE_CHUNK_H
#include <experimental/optional>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include "graphics.h"
#include "structs.h"
#include "mathHelper.h"
#include "recPrism.h"
class Chunk
{
private:
// The top left coordinate divided by sideLength
// So if sideLength = 512, then (3,2) describes the
// chunk whose top left corner is (1536, 1024)
Point2D topLeft;
int sideLength;
Point center; // The actual center (y-coordinate = 0)
// The number of the chunk based on its location
int chunkID;
RGBAcolor groundColor;
public:
Chunk();
Chunk(Point2D inputTopLeft, int inputSideLength, RGBAcolor inputGroundColor);
void initializeCenter();
void initializeChunkID();
// Getters
Point2D getTopLeft() const;
int getSideLength() const;
Point getCenter() const;
int getChunkID();
void draw(double lightLevel) const;
};
#endif //FPS_TEMPLATE_CHUNK_H
<file_sep>#ifndef STREETNIGHT_ELLIPTICCYL_H
#define STREETNIGHT_ELLIPTICCYL_H
#include "solid.h"
class EllipticCyl : public Solid
{
private:
const static int smoothness = 24;
double topXWidth;
double topZWidth;
Point topCenter, bottomCenter; // These need to be kept track of when the cylinder rotates.
// Because this wasn't in my original design, it's an easier fix to make separate variables
// rather than put them into the corners vector.
const static int distanceBetweenHighLines = 8;
const static int distanceBetweenMediumLines = 32;
const static int distanceBetweenLowLines = 56;
std::vector<std::vector<Point>> linePoints;
public:
EllipticCyl();
EllipticCyl(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
linesDrawnEnum inputLinesDrawn=Normal);
EllipticCyl(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
double inputTopXWidth, double inputTopZWidth,
linesDrawnEnum inputLinesDrawn=Normal);
// Make the corners, which in this case are the points along the circumference of the
// top and bottom ellipses (the 2i th entry is a top point, and the 2i+1 th entry is the
// bottom point corresponding to it).
void initializeCorners();
// Make points for drawing gridlines, if applicable
void initializeLinePoints();
// Getters
double getTopXWidth() const;
double getTopZWidth() const;
// Geometry
// Returns the x or z radius at a height of y above the base
double getXRadiusAtHeight(double y) const;
double getZRadiusAtHeight(double y) const;
// Get the coordinates on circumference at given height and angle
Point getPointAtHeight(double y, double theta) const;
void draw(double lightLevel) const;
void drawLines(double lightLevel) const;
void drawFaces(double lightLevel) const;
void drawGridLines(double lightLevel) const;
void move(double deltaX, double deltaY, double deltaZ) override;
void rotate(double deltaX, double deltaY, double deltaZ) override;
void rotateAroundPoint(const Point &p, double deltaX, double deltaY, double deltaZ) override;
};
#endif //STREETNIGHT_ELLIPTICCYL_H
<file_sep>#ifndef STREETNIGHT_RECPRISM_H
#define STREETNIGHT_RECPRISM_H
#include "solid.h"
#include <iostream>
#include <stdexcept>
class RecPrism : public Solid
{
private:
const static int distanceBetweenHighLines = 8;
const static int distanceBetweenMediumLines = 16;
const static int distanceBetweenLowLines = 24;
// Points for drawing extra gridlines on the faces of the rectangular prism
std::vector<Point> xLinePoints;
std::vector<Point> yLinePoints;
std::vector<Point> zLinePoints;
public:
RecPrism();
RecPrism(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
linesDrawnEnum inputLinesDrawn=Normal);
// Make the corners of the rec prism
void initializeCorners();
// Make points for drawing gridlines, if applicable
void initializeLinePoints();
void initializeXLinePoints();
void initializeYLinePoints();
void initializeZLinePoints();
void draw(double lightLevel) const;
void drawLines(double lightLevel) const;
void drawFaces(double lightLevel) const;
void drawGridLines(double lightLevel) const;
};
#endif //STREETNIGHT_RECPRISM_H
<file_sep>cmake_minimum_required(VERSION 3.8)
project(streetnight)
if (WIN32)
set(FREEGLUT_INCLUDE_DIRS "C:/Program\ Files/Common\ Files/freeglut/include")
set(FREEGLUT_LIBRARY_DIRS "C:/Program\ Files/Common\ Files/freeglut/lib")
endif (WIN32)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++14 -Wno-deprecated -Werror=return-type")
find_package (OpenGL REQUIRED)
if (UNIX)
find_package(GLUT REQUIRED)
endif (UNIX)
if (WIN32)
include_directories(${OPENGL_INCLUDE_DIR} ${FREEGLUT_INCLUDE_DIRS})
link_directories(${FREEGLUT_LIBRARY_DIRS})
elseif (UNIX)
include_directories(${OPENGL_INCLUDE_DIR} ${GLUT_INCLUDE_DIRS})
endif ()
file(GLOB SOURCE_FILES
*.cpp
*.h
)
add_executable(graphics graphics.h graphics.cpp graphics.cpp graphics.h structs.h mathHelper.cpp mathHelper.h
gameManager.cpp gameManager.h chunk.cpp chunk.h player.cpp player.h button.cpp button.h solid.cpp solid.h
recPrism.cpp recPrism.h lampPost.cpp lampPost.h train.cpp train.h coin.cpp coin.h ellipticCyl.cpp ellipticCyl.h frustum.cpp frustum.h)
add_executable(testing testing.cpp testing.cpp structs.h mathHelper.cpp mathHelper.h)
if (WIN32)
target_link_libraries (graphics ${OPENGL_LIBRARIES} freeglut)
target_link_libraries (testing ${OPENGL_LIBRARIES} freeglut)
elseif (UNIX)
target_link_libraries (graphics ${OPENGL_LIBRARIES} ${GLUT_LIBRARIES})
target_link_libraries (testing ${OPENGL_LIBRARIES} ${GLUT_LIBRARIES})
endif ()
<file_sep>#include "train.h"
Train::Train()
{
location = {0, 30, 100};
color = {0.0, 0.0, 0.3, 1.0};
xWidth = 60;
yWidth = 60;
zWidth = 120;
speed = 2.5;
xzAngle = 3*PI/2;
initializeVelocity();
initializeSolids();
initializeHitbox();
}
Train::Train(Point inputLocation, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth,
double inputSpeed, double inputXZAngle)
{
location = inputLocation;
color = inputColor;
xWidth = inputXWidth;
yWidth = inputYWidth;
zWidth = inputZWidth;
speed = inputSpeed;
xzAngle = inputXZAngle;
initializeVelocity();
initializeSolids();
initializeHitbox();
}
void Train::initializeVelocity()
{
velocity.x = cos(xzAngle)*speed;
velocity.y = 0;
velocity.z = sin(xzAngle)*speed;
}
void Train::initializeSolids()
{
// Main tank
Point center = {location.x, location.y + yWidth/2 - xWidth/2, location.z - zWidth/8};
std::shared_ptr<EllipticCyl> mainTank = std::make_shared<EllipticCyl>(EllipticCyl(center, color, xWidth, 3*zWidth/4, xWidth, {1,1,1,1}));
mainTank->rotate(PI/2, 0, 0);
mainTank->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(mainTank);
// Back
center = {location.x, location.y + yWidth/2 - xWidth/2, location.z + 3*zWidth/8};
std::shared_ptr<RecPrism> back = std::make_shared<RecPrism>(RecPrism(center, color, xWidth, xWidth, zWidth/4, {1,1,1,1}));
back->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(back);
// Roof
center = {location.x, location.y + yWidth/2, location.z + 3*zWidth/8};
std::shared_ptr<EllipticCyl> roof = std::make_shared<EllipticCyl>(EllipticCyl(center, color, xWidth, zWidth/4, xWidth/4, {1,1,1,1}, NoLines));
roof->rotate(PI/2, 0, 0);
roof->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(roof);
// Smokestack
center = {location.x, location.y + yWidth/2, location.z - 3*zWidth/8};
std::shared_ptr<EllipticCyl> smokestack = std::make_shared<EllipticCyl>(EllipticCyl(center, color, xWidth/4, yWidth/2, xWidth/4, {1,1,1,1}));
smokestack->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(smokestack);
// Base
center = {location.x, location.y - xWidth/2, location.z};
std::shared_ptr<RecPrism> base = std::make_shared<RecPrism>(RecPrism(center, color, xWidth/2, yWidth - xWidth, zWidth, {1,1,1,1}));
base->rotate(0, xzAngle - 3*PI/2, 0);
solids.push_back(base);
// Front bar
center = {location.x, location.y - yWidth/4, location.z - zWidth/2};
std::shared_ptr<RecPrism> frontBar = std::make_shared<RecPrism>(RecPrism(center, {1,0,0,1}, xWidth, yWidth/8, xWidth/8, {1,1,1,1}));
frontBar->rotateAroundPoint(location,0, xzAngle - 3*PI/2, 0);
solids.push_back(frontBar);
// Wheels
double wheelWidth = xWidth/10;
double largeDiameter = zWidth/4;
double smallDiameter = zWidth/8;
center = {location.x - xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - largeDiameter/2};
std::shared_ptr<EllipticCyl> backLeftWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
backLeftWheel->rotate(0, 0, PI/2);
backLeftWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(backLeftWheel);
center = {location.x + xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - largeDiameter/2};
std::shared_ptr<EllipticCyl> backRightWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
backRightWheel->rotate(0, 0, PI/2);
backRightWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(backRightWheel);
center = {location.x - xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - 3*largeDiameter/2};
std::shared_ptr<EllipticCyl> secondBackLeftWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
secondBackLeftWheel->rotate(0, 0, PI/2);
secondBackLeftWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(secondBackLeftWheel);
center = {location.x + xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - 3*largeDiameter/2};
std::shared_ptr<EllipticCyl> secondBackRightWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
secondBackRightWheel->rotate(0, 0, PI/2);
secondBackRightWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(secondBackRightWheel);
center = {location.x - xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - 5*largeDiameter/2};
std::shared_ptr<EllipticCyl> thirdBackLeftWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
thirdBackLeftWheel->rotate(0, 0, PI/2);
thirdBackLeftWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(thirdBackLeftWheel);
center = {location.x + xWidth/2, location.y - yWidth/2 + largeDiameter/2, location.z + zWidth/2 - 5*largeDiameter/2};
std::shared_ptr<EllipticCyl> thirdBackRightWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, largeDiameter, wheelWidth, largeDiameter, {1,1,1,1}));
thirdBackRightWheel->rotate(0, 0, PI/2);
thirdBackRightWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(thirdBackRightWheel);
center = {location.x - xWidth/2, location.y - yWidth/2 + smallDiameter/2, location.z - zWidth/2 + smallDiameter/2};
std::shared_ptr<EllipticCyl> frontLeftWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, smallDiameter, wheelWidth, smallDiameter, {1,1,1,1}));
frontLeftWheel->rotate(0, 0, PI/2);
frontLeftWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(frontLeftWheel);
center = {location.x + xWidth/2, location.y - yWidth/2 + smallDiameter/2, location.z - zWidth/2 + smallDiameter/2};
std::shared_ptr<EllipticCyl> frontRightWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, smallDiameter, wheelWidth, smallDiameter, {1,1,1,1}));
frontRightWheel->rotate(0, 0, PI/2);
frontRightWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(frontRightWheel);
center = {location.x - xWidth/2, location.y - yWidth/2 + smallDiameter/2, location.z - zWidth/2 + 3*smallDiameter/2};
std::shared_ptr<EllipticCyl> secondFrontLeftWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, smallDiameter, wheelWidth, smallDiameter, {1,1,1,1}));
secondFrontLeftWheel->rotate(0, 0, PI/2);
secondFrontLeftWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(secondFrontLeftWheel);
center = {location.x + xWidth/2, location.y - yWidth/2 + smallDiameter/2, location.z - zWidth/2 + 3*smallDiameter/2};
std::shared_ptr<EllipticCyl> secondFrontRightWheel = std::make_shared<EllipticCyl>(EllipticCyl(center, color, smallDiameter, wheelWidth, smallDiameter, {1,1,1,1}));
secondFrontRightWheel->rotate(0, 0, PI/2);
secondFrontRightWheel->rotateAroundPoint(location, 0, xzAngle - 3*PI/2, 0);
solids.push_back(secondFrontRightWheel);
}
void Train::initializeHitbox()
{
hitbox = RecPrism(location, {1,0.9,0.9,0.5}, xWidth, yWidth, zWidth, {1,1,1,1});
hitbox.rotate(0, xzAngle - 3*PI/2, 0);
}
// Getters
Point Train::getLocation() const
{
return location;
}
Point Train::getVelocity() const
{
return velocity;
}
void Train::draw(double lightLevel) const
{
for(std::shared_ptr<Solid> s : solids)
{
s->draw(lightLevel);
}
}
void Train::tick()
{
move();
}
void Train::move()
{
location.x += velocity.x;
location.y += velocity.y;
location.z += velocity.z;
for(std::shared_ptr<Solid> s : solids)
{
s->move(velocity.x, velocity.y, velocity.z);
}
hitbox.move(velocity.x, velocity.y, velocity.z);
}
std::experimental::optional<Point> Train::correctCollision(Point p, double buffer) const
{
return correctRectangularPrism(p, buffer, hitbox.getCenter(), hitbox.getXWidth(), hitbox.getYWidth(), hitbox.getZWidth(), hitbox.getXZAngle());
}<file_sep>#ifndef FPS_TEMPLATE_MATHHELPER_H
#define FPS_TEMPLATE_MATHHELPER_H
#include "structs.h"
#include <cmath>
#include <vector>
#include <experimental/optional>
// This file contains general math helper functions
const double PI = 3.14159265358979323846;
// Assuming n > 0, this returns the integer closest to n that
// is a perfect square
int nearestPerfectSquare(int n);
// Returns the square root of n, assuming that n is a perfect square
int isqrt(int n);
// Convert between chunkID's and Point2D's
Point2D chunkIDtoPoint2D(int n);
int point2DtoChunkID(Point2D p);
// Euclidean distance
double distanceFormula(double x1, double y1, double x2, double y2);
// Returns the distance in the xz plane, ignoring the y-coordinate
// (calls distanceFormula())
double distance2d(Point p1, Point p2);
double distance3d(Point p1, Point p2);
double xzAngleBetweenPoints(Point base, Point other);
// m and b represent a line such that z = mx + b.
// This determines if p lies above the line in the xz plane
bool isAboveLineXZPlane(Point p, double m, double b);
// Returns the ints corresponding to to all chunks that are within radius of this one,
// using the taxicab metric
std::vector<int> getChunkIDsAroundPoint(Point2D p, int radius);
std::vector<Point2D> getChunkTopLeftCornersAroundPoint(Point2D p, int radius);
// Wrappers
std::vector<int> getChunkIDsAroundPoint(int chunkID, int radius);
std::vector<Point2D> getChunkTopLeftCornersAroundPoint(int chunkID, int radius);
int getChunkIDContainingPoint(Point p, int chunkSize);
// Point operations
void movePoint(Point &p, double deltaX, double deltaY, double deltaZ);
void rotatePointAroundPoint(Point &p, const Point &pBase, double thetaX, double thetaY, double thetaZ);
Point getRotatedPointAroundPoint(const Point &p, const Point &pBase, double thetaX, double thetaY, double thetaZ);
// Light sources
// Return the difference between the two angles, taking into account the fact
// that angles wrap around at 2PI
double trueAngleDifference(double angle1, double angle2);
// Checks if a point is within a given field of view
bool isInFieldOfView(Point target, Point location, double xzAngle, double yAngle, double fov);
// Determines the light intensity based on the distance away
double determineLightIntensityAt(Point target, LightSource source, double fadeFactor);
// Takes into account field of view to determine light level
double determineLightLevelAt(Point target, LightSource source, double fadeFactor);
// Returns the point that the train should aim for if the target moves with a constant
// velocity
Point predictMovement(Point location, double speed, Point targetLocation, Point targetVelocity);
// Working in the xz-plane, assume there is a rectangle centered at c that is aligned with the x,z-axes
// with xw and zw as its dimensions. This returns the Point with adjusted x and z coordinates to move
// p exactly buffer away from the rectangle.
std::experimental::optional<Point> correctAlignedRectangularCrossSection(Point p, int buffer, Point c,
double xw, double zw);
// Performs a rotation and calls correctAlignedRectangularCrossSection(), then unrotates
std::experimental::optional<Point> correctRectangularCrossSection(Point p, int buffer, Point c,
double xw, double zw, double xzAngle);
// This assumes x, y, and z are all aligned.
std::experimental::optional<Point> correctAlignedRectangularPrism(Point p, int buffer, Point c,
double xw, double yw, double zw);
// This assumes the y-axis is aligned. If there was a y-rotation, this does not work.
std::experimental::optional<Point> correctRectangularPrism(Point p, int buffer, Point c,
double xw, double yw, double zw, double xzAngle);
#endif //FPS_TEMPLATE_MATHHELPER_H
<file_sep>#include "player.h"
Player::Player()
{
location = {0, 10, 0};
lookingAt = {0, 10, -10};
up = {0, 20, 0};
speed = 2;
velocity = {0, 0, 0};
sensitivity = 0.1;
height = 20;
radius = 5;
initializeAngles();
initializeSphericalDirection();
maxDistanceFromSpawn = 5120;
isGrounded = true;
gravity = -0.1;
jumpAmount = 10;
}
Player::Player(Point inputLocation, Point inputLookingAt, Point inputUp,
double inputSpeed, double inputSensitivity, double inputHeight, double inputRadius, int inputMaxDistanceFromSpawn,
double inputGravity, double inputJumpAmount)
{
location = inputLocation;
lookingAt = inputLookingAt;
up = inputUp;
speed = inputSpeed;
velocity = {0, 0, 0};
sensitivity = inputSensitivity;
height = inputHeight;
radius = inputRadius;
initializeAngles();
initializeSphericalDirection();
maxDistanceFromSpawn = inputMaxDistanceFromSpawn;
isGrounded = true;
gravity = inputGravity;
jumpAmount = inputJumpAmount;
}
void Player::initializeAngles()
{
xzAngle = atan2(lookingAt.z - location.z, lookingAt.x - location.x);
yAngle = atan2(lookingAt.y - location.y, distance2d(location, lookingAt));
}
void Player::initializeSphericalDirection()
{
sphericalDirection.x = cos(xzAngle);
sphericalDirection.z = sin(xzAngle);
// Must scale the component in the xz plane for spherical coordinates
double scaleAmount = cos(yAngle) / sqrt(sphericalDirection.x*sphericalDirection.x + sphericalDirection.z*sphericalDirection.z);
sphericalDirection.x *= scaleAmount;
sphericalDirection.z *= scaleAmount;
sphericalDirection.y = sin(yAngle);
}
// ==========================
//
// Getters
//
// ==========================
Point Player::getLocation() const
{
return location;
}
Point Player::getLookingAt() const
{
return lookingAt;
}
Point Player::getUp() const
{
return up;
}
Point Player::getVelocity() const
{
return velocity;
}
double Player::getSpeed() const
{
return speed;
}
double Player::getXZAngle() const
{
return xzAngle;
}
double Player::getYAngle() const
{
return yAngle;
}
double Player::getHeight() const
{
return height;
}
double Player::getRadius() const
{
return radius;
}
// ==========================
//
// Setters
//
// ==========================
void Player::setLocation(Point inputLocation)
{
location = inputLocation;
}
void Player::setLookingAt(Point inputLookingAt)
{
lookingAt = inputLookingAt;
}
void Player::setUp(Point inputUp)
{
up = inputUp;
}
void Player::setSpeed(double inputSpeed)
{
speed = inputSpeed;
}
void Player::setSensitivity(double inputSensitivity)
{
sensitivity = inputSensitivity;
}
void Player::setXZAngle(double inputXZAngle)
{
xzAngle = inputXZAngle;
}
void Player::setYAngle(double inputYAngle)
{
yAngle = inputYAngle;
}
// ===============================
//
// Movement
//
// ==============================
void Player::move()
{
location.x += velocity.x;
lookingAt.x += velocity.x;
location.y += velocity.y;
lookingAt.y += velocity.y;
location.z += velocity.z;
lookingAt.z += velocity.z;
}
void Player::correctGround()
{
if(location.y < height/2)
{
lookingAt.y += height/2 - location.y;
location.y = height/2;
isGrounded = true;
velocity.y = 0;
}
}
void Player::applyGravity()
{
if(!isGrounded)
{
velocity.y += gravity;
}
}
void Player::stayWithinBoundary()
{
if(location.x > maxDistanceFromSpawn)
{
lookingAt.x -= maxDistanceFromSpawn - location.x;
location.x = maxDistanceFromSpawn;
}
else if(location.x < -maxDistanceFromSpawn)
{
lookingAt.x += maxDistanceFromSpawn + location.x;
location.x = -maxDistanceFromSpawn;
}
if(location.z > maxDistanceFromSpawn)
{
lookingAt.z -= maxDistanceFromSpawn - location.z;
location.z = maxDistanceFromSpawn;
}
else if(location.z < -maxDistanceFromSpawn)
{
lookingAt.z += maxDistanceFromSpawn + location.z;
location.z = -maxDistanceFromSpawn;
}
}
void Player::moveToCorrectedLocation(Point newLocation)
{
lookingAt.x += newLocation.x - location.x;
lookingAt.y += newLocation.y - location.y;
lookingAt.z += newLocation.z - location.z;
location = newLocation;
}
// Based on which keys are pressed, set the velocity
void Player::setVelocity(bool wKey, bool aKey, bool sKey, bool dKey)
{
bool forward = wKey && !sKey;
bool backward = !wKey && sKey;
bool left = aKey && !dKey;
bool right = !aKey && dKey;
// The angle the player should move based on input
double angleToMove;
if(forward)
{
if(right)
{
angleToMove = xzAngle + PI/4;
}
else if(left)
{
angleToMove = xzAngle - PI/4;
}
else
{
angleToMove = xzAngle;
}
}
else if(backward)
{
if(right)
{
angleToMove = xzAngle - PI - PI/4;
}
else if(left)
{
angleToMove = xzAngle - PI + PI/4;
}
else
{
angleToMove = xzAngle - PI;
}
}
else
{
if(right)
{
angleToMove = xzAngle + PI/2;
}
else if(left)
{
angleToMove = xzAngle - PI/2;
}
else // If no arrow keys are being held
{
velocity.x = 0;
velocity.z = 0;
return;
}
}
velocity.x = speed * cos(angleToMove);
velocity.z = speed * sin(angleToMove);
}
// Update the xzAngle and yAngle based on theta resulting from a mouse movement
void Player::updateAngles(double theta)
{
double horizontalAmount = sensitivity * cos(theta);
xzAngle += horizontalAmount;
if(xzAngle > 2*PI)
{
xzAngle -= 2*PI;
}
else if(xzAngle < 0)
{
xzAngle += 2*PI;
}
double verticalAmount = sensitivity * sin(theta);
yAngle -= verticalAmount; // negative sign since Glut's mouse functions treat +y as down
if(yAngle > PI/2 - VERTICAL_LIMIT)
{
yAngle = PI/2 - VERTICAL_LIMIT;
}
else if(yAngle < -PI/2 + VERTICAL_LIMIT)
{
yAngle = -PI/2 + VERTICAL_LIMIT;
}
}
// Use xzAngle, yAngle, and location to determine the spherical direction.
void Player::updateSphericalDirectionBasedOnAngles()
{
sphericalDirection.x = cos(xzAngle);
sphericalDirection.z = sin(xzAngle);
// Must scale the component in the xz plane for spherical coordinates
double scaleAmount = cos(yAngle) / sqrt(sphericalDirection.x*sphericalDirection.x + sphericalDirection.z*sphericalDirection.z);
sphericalDirection.x *= scaleAmount;
sphericalDirection.z *= scaleAmount;
sphericalDirection.y = sin(yAngle);
lookingAt.x = location.x + sphericalDirection.x;
lookingAt.y = location.y + sphericalDirection.y;
lookingAt.z = location.z + sphericalDirection.z;
}
void Player::tryToJump()
{
if(isGrounded)
{
velocity.y = jumpAmount;
isGrounded = false;
}
}
void Player::tick()
{
move();
correctGround();
applyGravity();
stayWithinBoundary();
}<file_sep>#include "mathHelper.h"
int nearestPerfectSquare(int n)
{
int squareJumpAmount = 3;
int curSquare = 1;
int prevSquare = 0;
while(curSquare < n)
{
prevSquare = curSquare;
curSquare += squareJumpAmount;
squareJumpAmount += 2; // the difference between consecutive squares is odd integer
}
if(n - prevSquare > curSquare - n)
{
return curSquare;
}
else
{
return prevSquare;
}
}
int isqrt(int n)
{
return round(sqrt(n));
}
Point2D chunkIDtoPoint2D(int n)
{
int s = nearestPerfectSquare(n);
int sq = isqrt(s);
if(s % 2 == 0)
{
if(n >= s)
{
return {sq/2, -sq/2 + n - s};
}
else
{
return {sq/2 - s + n, -sq/2};
}
}
else
{
if(n >= s)
{
return {-(sq + 1)/2, (sq + 1)/2 - 1 - n + s};
}
else
{
return {-(sq + 1)/2 + s - n, (sq + 1)/2 - 1};
}
}
}
int point2DtoChunkID(Point2D p)
{
int a = p.x;
int b = p.z;
// Bottom Zone
if(b > 0 && a >= -b && a < b)
{
return 4*b*b + 3*b - a;
}
// Left Zone
else if(a < 0 && b < -a && b >= a)
{
return 4*a*a + 3*a - b;
}
// Top Zone
else if(b < 0 && a <= -b && a > b)
{
return 4*b*b + b + a;
}
// Right Zone
else if(a > 0 && b <= a && b > -a)
{
return 4*a*a + a + b;
}
// Only a=0, b=0 is not in a zone
else
{
return 0;
}
}
double distance2d(Point p1, Point p2)
{
return distanceFormula(p1.x, p1.z, p2.x, p2.z);
}
double distanceFormula(double x1, double y1, double x2, double y2)
{
return sqrt((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
double distance3d(Point p1, Point p2)
{
return sqrt((p1.x - p2.x)*(p1.x - p2.x) +
(p1.y - p2.y)*(p1.y - p2.y) +
(p1.z - p2.z)*(p1.z - p2.z));
}
double xzAngleBetweenPoints(Point base, Point other)
{
return atan2(other.z - base.z, other.x - base.x);
}
bool isAboveLineXZPlane(Point p, double m, double b)
{
return p.z < m*p.x + b; // Reverse inequality because up is negative z
}
std::vector<int> getChunkIDsAroundPoint(Point2D p, int radius)
{
std::vector<int> result;
// Start at the bottom of the diamond and work up from there
for(int b = p.z + radius; b >= p.z - radius; b--)
{
int distanceFromZ = abs(b - p.z);
for(int a = p.x - (radius - distanceFromZ); a <= p.x + (radius - distanceFromZ); a++)
{
result.push_back(point2DtoChunkID({a,b}));
}
}
return result;
}
std::vector<Point2D> getChunkTopLeftCornersAroundPoint(Point2D p, int radius)
{
std::vector<Point2D> result;
// Start at the bottom of the diamond and work up from there
for(int b = p.z + radius; b >= p.z - radius; b--)
{
int distanceFromZ = abs(b - p.z);
for(int a = p.x - (radius - distanceFromZ); a <= p.x + (radius - distanceFromZ); a++)
{
result.push_back({a,b});
}
}
return result;
}
std::vector<int> getChunkIDsAroundPoint(int chunkID, int radius)
{
return getChunkIDsAroundPoint(chunkIDtoPoint2D(chunkID), radius);
}
std::vector<Point2D> getChunkTopLeftCornersAroundPoint(int chunkID, int radius)
{
return getChunkTopLeftCornersAroundPoint(chunkIDtoPoint2D(chunkID), radius);
}
int getChunkIDContainingPoint(Point p, int chunkSize)
{
int x = floor(p.x / chunkSize);
int z = floor(p.z / chunkSize);
return point2DtoChunkID({x, z});
}
void movePoint(Point &p, double deltaX, double deltaY, double deltaZ)
{
p.x += deltaX;
p.y += deltaY;
p.z += deltaZ;
}
void rotatePointAroundPoint(Point &p, const Point &pBase, double thetaX, double thetaY, double thetaZ)
{
// Store the previous coordinates during calculations
double prevX = 0, prevY = 0, prevZ = 0;
// Translate pBase to the origin by moving p
p.x -= pBase.x;
p.y -= pBase.y;
p.z -= pBase.z;
// Rotate around x-axis
prevY = p.y;
prevZ = p.z;
p.y = prevY * cos(thetaX) - prevZ * sin(thetaX);
p.z = prevY * sin(thetaX) + prevZ * cos(thetaX);
// Rotate around y-axis
prevX = p.x;
prevZ = p.z;
p.x = prevX * cos(thetaY) - prevZ * sin(thetaY);
p.z = prevX * sin(thetaY) + prevZ * cos(thetaY);
// Rotate around z-axis
prevX = p.x;
prevY = p.y;
p.x = prevX * cos(thetaZ) - prevY * sin(thetaZ);
p.y = prevX * sin(thetaZ) + prevY * cos(thetaZ);
// Translate back
p.x += pBase.x;
p.y += pBase.y;
p.z += pBase.z;
}
Point getRotatedPointAroundPoint(const Point &p, const Point &pBase, double thetaX, double thetaY, double thetaZ)
{
Point result = {p.x, p.y, p.z};
rotatePointAroundPoint(result, pBase, thetaX, thetaY, thetaZ);
return result;
}
double trueAngleDifference(double angle1, double angle2)
{
double theta = angle1 - angle2;
while(theta < 0)
{
theta += 2*PI;
}
if(theta > PI)
{
return 2*PI - theta;
}
return theta;
}
bool isInFieldOfView(Point target, Point location, double xzAngle, double yAngle, double fov)
{
double angleDifXZ = atan2(target.z - location.z, target.x - location.x);
double angleDifY = atan2(target.y - location.y, distance2d(location, target));
return trueAngleDifference(angleDifXZ, xzAngle) < fov && trueAngleDifference(angleDifY, yAngle) < fov;
}
double determineLightIntensityAt(Point target, LightSource source, double fadeFactor)
{
double d = distance3d(target, source.location);
if(d == 0)
{
return source.intensity;
}
return source.intensity / (d*d * fadeFactor);
}
double determineLightLevelAt(Point target, LightSource source, double fadeFactor)
{
if(!isInFieldOfView(target, source.location, source.xzAngle, source.yAngle, source.fieldOfView))
{
return 0;
}
else
{
return determineLightIntensityAt(target, source, fadeFactor);
}
}
// To come up with the algebra, pretend there is a circle expanding out from location. Find the time
// when the target is on the circumference of the circle, and return the point where the target is
// at that time.
Point predictMovement(Point location, double speed, Point targetLocation, Point targetVelocity)
{
double x1 = location.x, z1 = location.z, x2 = targetLocation.x, z2 = targetLocation.z;
double vx = targetVelocity.x, vz = targetVelocity.z, s = speed;
// For the quadratic formula
double a = s*s - (vx*vx + vz*vz);
double b = 2*(vx*(x1-x2) + vz*(z1-z2));
double c = -(x1-x2)*(x1-x2) - (z1-z2)*(z1-z2);
double discriminant = b*b - 4*a*c;
// If there would be an arithmetic error, just return the target's current location
if(a <= 0 || discriminant < 0)
{
return targetLocation;
}
double t = (-b + sqrt(discriminant)) / (2*a);
// If hitting the target is impossible based on it's current velocity, just shoot at it
if(t < 0)
{
return targetLocation;
}
// Finally, if nothing went wrong, lead the target
return {x2 + vx*t, targetLocation.y, z2 + vz*t};
}
/*
* + - - - - - +
* | \ 1 / |
* | 4 X 2 |
* | / 3 \ |
* + - - - - - +
*/
std::experimental::optional<Point> correctAlignedRectangularCrossSection(Point p, int buffer, Point c,
double xw, double zw)
{
// Determine which of the 4 zones of the rectangle p lies in
// Let line 1 have the negative slope, and line 2 have the positive slope
// Line 1: z = -mx + b1
// Line 2: z = mx + b2
double m = zw / xw;
double b1 = c.z + m*c.x;
double b2 = c.z - m*c.x;
bool above1 = isAboveLineXZPlane(p, -m, b1);
bool above2 = isAboveLineXZPlane(p, m, b2);
if(above1 && above2) // zone 1
{
if(p.z > c.z - zw/2 - buffer)
{
return std::experimental::optional<Point>({p.x, p.y, c.z - zw/2 - buffer});
}
}
else if(above1) // zone 4
{
if(p.x > c.x - xw/2 - buffer)
{
return std::experimental::optional<Point>({c.x - xw/2 - buffer, p.y, p.z});
}
}
else if(above2) // zone 2
{
if(p.x < c.x + xw/2 + buffer)
{
return std::experimental::optional<Point>({c.x + xw/2 + buffer, p.y, p.z});
}
}
else // zone 3
{
if(p.z < c.z + zw/2 + buffer)
{
return std::experimental::optional<Point>({p.x, p.y, c.z + zw/2 + buffer});
}
}
return std::experimental::nullopt;
}
std::experimental::optional<Point> correctRectangularCrossSection(Point p, int buffer, Point c,
double xw, double zw, double xzAngle)
{
Point rotatedPoint = getRotatedPointAroundPoint(p, c, 0, -xzAngle, 0);
std::experimental::optional<Point> correctedPoint = correctAlignedRectangularCrossSection(rotatedPoint, buffer, c, xw, zw);
if(correctedPoint)
{
return getRotatedPointAroundPoint(*correctedPoint, c, 0, xzAngle, 0);
}
return correctedPoint;
}
std::experimental::optional<Point> correctAlignedRectangularPrism(Point p, int buffer, Point c,
double xw, double yw, double zw)
{
double distanceOutsideLeftEdge = c.x - xw/2 - p.x;
double distanceOutsideRightEdge = p.x - c.x - xw/2;
double distanceAboveTopEdge = p.y - c.y - yw/2;
double distanceBelowBottomEdge = c.y - yw/2 - p.y;
double distanceOutsideFrontEdge = p.z - c.z - zw/2;
double distanceOutsideBackEdge = c.z - zw/2 - p.z;
// If the point is closest to the top face
if(distanceAboveTopEdge > distanceOutsideLeftEdge && distanceAboveTopEdge > distanceOutsideRightEdge &&
distanceAboveTopEdge > distanceOutsideFrontEdge && distanceAboveTopEdge > distanceOutsideBackEdge)
{
if(distanceAboveTopEdge >= buffer)
{
return std::experimental::nullopt;
}
else
{
return std::experimental::optional<Point>({p.x, c.y + yw/2 + buffer, p.z});
}
}
// If the point is closest to the bottom face
else if(distanceBelowBottomEdge > distanceOutsideLeftEdge && distanceBelowBottomEdge > distanceOutsideRightEdge &&
distanceBelowBottomEdge > distanceOutsideFrontEdge && distanceBelowBottomEdge > distanceOutsideBackEdge)
{
if(distanceBelowBottomEdge >= buffer)
{
return std::experimental::nullopt;
}
else
{
return std::experimental::optional<Point>({p.x, c.y - yw/2 - buffer, p.z});
}
}
// Otherwise, assume it is near a side face and correct that
else
{
return correctAlignedRectangularCrossSection(p, buffer, c, xw, zw);
}
}
std::experimental::optional<Point> correctRectangularPrism(Point p, int buffer, Point c,
double xw, double yw, double zw, double xzAngle)
{
Point rotatedPoint = getRotatedPointAroundPoint(p, c, 0, -xzAngle, 0);
std::experimental::optional<Point> correctedPoint = correctAlignedRectangularPrism(rotatedPoint, buffer, c, xw, yw, zw);
if(correctedPoint)
{
return getRotatedPointAroundPoint(*correctedPoint, c, 0, xzAngle, 0);
}
return correctedPoint;
}<file_sep>#include "chunk.h"
Chunk::Chunk()
{
topLeft = {0, 0};
sideLength = 512;
groundColor = {1,1,1,1};
initializeCenter();
initializeChunkID();
}
Chunk::Chunk(Point2D inputTopLeft, int inputSideLength, RGBAcolor inputGroundColor)
{
topLeft = inputTopLeft;
sideLength = inputSideLength;
groundColor = inputGroundColor;
initializeCenter();
initializeChunkID();
}
void Chunk::initializeCenter()
{
center = {sideLength*topLeft.x + sideLength/2.0, 0,sideLength*topLeft.z + sideLength/2.0};
}
void Chunk::initializeChunkID()
{
chunkID = point2DtoChunkID(topLeft);
}
// Getters
Point2D Chunk::getTopLeft() const
{
return topLeft;
}
int Chunk::getSideLength() const
{
return sideLength;
}
Point Chunk::getCenter() const
{
return center;
}
int Chunk::getChunkID()
{
return chunkID;
}
void Chunk::draw(double lightLevel) const
{
setGLColorLightLevel(groundColor, lightLevel);
glBegin(GL_QUADS);
glVertex3f(center.x - sideLength/2, 0, center.z - sideLength/2);
glVertex3f(center.x - sideLength/2, 0, center.z + sideLength/2);
glVertex3f(center.x + sideLength/2, 0, center.z + sideLength/2);
glVertex3f(center.x + sideLength/2, 0, center.z - sideLength/2);
glEnd();
}<file_sep>#ifndef FPS_TEMPLATE_PLAYER_H
#define FPS_TEMPLATE_PLAYER_H
#include "structs.h"
#include "mathHelper.h"
class Player
{
private:
Point location;
Point lookingAt;
Point up;
// The direction the player is facing in spherical coordinates
// Must be on the unit sphere
Point sphericalDirection;
double xzAngle; // Where the player is looking in the xz-plane
double yAngle; // How much the player is looking up (in [-Pi/2, Pi/2])
double speed; // how fast the player can move
Point velocity; // current x y and z velocity
double jumpAmount;
double gravity;
bool isGrounded;
double sensitivity; // turning speed for mouse movement
// Treat the Player as a Cylinder
double height;
double radius;
// Keep the Player restricted to a square around (0,0)
int maxDistanceFromSpawn;
// Can't look perfectly vertically or it will glitch
double VERTICAL_LIMIT = 0.01;
public:
Player();
Player(Point inputLocation, Point inputLookingAt, Point inputUp,
double inputSpeed, double inputSensitivity, double inputHeight, double inputRadius,
int inputMaxDistanceFromSpawn, double inputGravity, double inputJumpAmount);
void initializeAngles();
void initializeSphericalDirection();
// Getters
Point getLocation() const;
Point getLookingAt() const;
Point getVelocity() const;
Point getUp() const;
double getSpeed() const;
double getXZAngle() const;
double getYAngle() const;
double getHeight() const;
double getRadius() const;
// Setters
void setLocation(Point inputLocation);
void setLookingAt(Point inputLookingAt);
void setUp(Point inputUp);
void setSpeed(double inputSpeed);
void setSensitivity(double inputSensitivity);
void setXZAngle(double inputXZAngle);
void setYAngle(double inputYAngle);
// Movement
void move();
// Keep the Player from going through the ground
void correctGround();
void applyGravity();
// Don't allow the Player to move past maxDistanceFromSpawn
void stayWithinBoundary();
// Move the player due to an external force
void moveToCorrectedLocation(Point newLocation);
// Based on which keys are pressed, set the velocity
void setVelocity(bool wKey, bool aKey, bool sKey, bool dKey);
// Update the xzAngle and yAngle based on theta resulting from a mouse movement
void updateAngles(double theta);
// Use xzAngle, yAngle, and location to determine the spherical direction.
void updateSphericalDirectionBasedOnAngles();
void tryToJump();
void tick();
};
#endif //FPS_TEMPLATE_PLAYER_H
<file_sep>#ifndef STREETNIGHT_FRUSTUM_H
#define STREETNIGHT_FRUSTUM_H
#include "solid.h"
class Frustum : public Solid
{
private:
double upperXWidth;
double upperZWidth;
const static int distanceBetweenHighLines = 8;
const static int distanceBetweenMediumLines = 16;
const static int distanceBetweenLowLines = 24;
// Points for drawing extra gridlines on the faces
std::vector<Point> xLinePoints;
std::vector<Point> yLinePoints;
std::vector<Point> zLinePoints;
public:
Frustum();
Frustum(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
double inputUpperXWidth, double inputUpperZWidth,
linesDrawnEnum inputLinesDrawn=Normal);
void initializeCorners();
// Make points for drawing gridlines, if applicable
void initializeLinePoints();
void initializeXLinePoints();
void initializeYLinePoints();
void initializeZLinePoints();
// Geometry
// Returns the x or z width at a height of y above the base
double getXWidthAtHeight(double y) const;
double getZWidthAtHeight(double y) const;
void draw(double lightLevel) const;
void drawLines(double lightLevel) const;
void drawFaces(double lightLevel) const;
void drawGridLines(double lightLevel) const;
};
#endif //STREETNIGHT_FRUSTUM_H
<file_sep>#ifndef FPS_TEMPLATE_STRUCTS_H
#define FPS_TEMPLATE_STRUCTS_H
#include <memory>
// This file contains some structs to make
// including simpler
// int points used for the chunks
// in the xz plane
struct Point2D
{
int x;
int z;
bool operator ==(const Point2D& p1)
{
return x == p1.x && z == p1.z;
}
bool operator !=(const Point2D& p1)
{
return x != p1.x || z != p1.z;
}
};
struct Point
{
double x;
double y;
double z;
};
struct RGBAcolor
{
double r;
double g;
double b;
double a;
};
struct LightSource
{
Point location;
double xzAngle;
double yAngle;
double fieldOfView;
int intensity;
};
#endif //FPS_TEMPLATE_STRUCTS_H
<file_sep>#include "structs.h"
#include "mathHelper.h"
#include <string>
#include <iostream>
#include <vector>
std::string testNearestPerfectSquare();
std::string testISqrt();
std::string testChunkIDtoPoint2D();
std::string testPoint2DtoChunkID();
std::string testDistanceFormula();
std::string testDistance2d();
std::string testGetChunkIDsAroundPoint();
std::string testGetChunkTopLeftCornersAroundPoint();
std::string testGetChunkIDContainingPoint();
std::string testTrueAngleDifference();
std::string testIsInFieldOfView();
std::string testCorrectAlignedRectangularCrossSection();
std::string testCorrectRectangularCrossSection();
int main()
{
std::string results = "";
results += testNearestPerfectSquare();
results += testISqrt();
results += testChunkIDtoPoint2D();
results += testPoint2DtoChunkID();
results += testDistanceFormula();
results += testDistance2d();
results += testGetChunkIDsAroundPoint();
results += testGetChunkTopLeftCornersAroundPoint();
results += testGetChunkIDContainingPoint();
results += testTrueAngleDifference();
results += testIsInFieldOfView();
results += testCorrectAlignedRectangularCrossSection();
results += testCorrectRectangularCrossSection();
std::cout << "\n" << results << std::endl;
return 0;
}
std::string testNearestPerfectSquare()
{
std::cout << "\nTesting nearestPerfectSquare()" << std::endl;
std::string results = "";
std::vector<int> input {0,1,2,3,4,5,6,7,8,9,10,24,25,26,27,28,29,30,31};
std::vector<int> exp {0,1,1,4,4,4,4,9,9,9,9,25,25,25,25,25,25,25,36};
for(int i = 0; i < input.size(); i++)
{
int obs = nearestPerfectSquare(input[i]);
if(obs != exp[i])
{
results += "F";
std::cout << "Test FAILED on input = " << input[i] << std::endl;
std::cout << "Expected " << exp[i] << ", got " << obs << std::endl;
}
else
{
results += ".";
}
}
return results;
}
std::string testISqrt()
{
std::cout << "\nTesting isqrt()" << std::endl;
std::string results = "";
std::vector<int> input {0,1,4,9,16,100};
std::vector<int> exp {0,1,2,3,4,10};
for(int i = 0; i < input.size(); i++)
{
int obs = isqrt(input[i]);
if(obs != exp[i])
{
results += "F";
std::cout << "Test FAILED on input = " << input[i] << std::endl;
std::cout << "Expected " << exp[i] << ", got " << obs << std::endl;
}
else
{
results += ".";
}
}
return results;
}
std::string testChunkIDtoPoint2D()
{
std::cout << "\nTesting chunkIDtoPoint2D()" << std::endl;
std::string results = "";
std::vector<int> input;
std::vector<Point2D> exp;
input.push_back(0);
exp.push_back({0,0});
input.push_back(1);
exp.push_back({-1,0});
input.push_back(2);
exp.push_back({-1,-1});
input.push_back(3);
exp.push_back({0,-1});
input.push_back(4);
exp.push_back({1,-1});
input.push_back(5);
exp.push_back({1,0});
input.push_back(6);
exp.push_back({1,1});
input.push_back(7);
exp.push_back({0,1});
input.push_back(8);
exp.push_back({-1,1});
input.push_back(9);
exp.push_back({-2,1});
input.push_back(10);
exp.push_back({-2,0});
input.push_back(11);
exp.push_back({-2,-1});
input.push_back(12);
exp.push_back({-2,-2});
input.push_back(13);
exp.push_back({-1,-2});
input.push_back(14);
exp.push_back({0,-2});
input.push_back(35);
exp.push_back({2,-3});
input.push_back(49);
exp.push_back({-4,3});
for(int i = 0; i < input.size(); i++)
{
Point2D obs = chunkIDtoPoint2D(input[i]);
if(obs != exp[i])
{
results += "F";
std::cout << "Test FAILED on input = " << input[i] << std::endl;
std::cout << "Expected " << exp[i].x << "," << exp[i].z << ", got " << obs.x << "," << obs.z << std::endl;
}
else
{
results += ".";
}
}
return results;
}
std::string testPoint2DtoChunkID()
{
std::cout << "\nTesting point2DtoChunkID()" << std::endl;
std::string results = "";
std::vector<Point2D> input;
std::vector<int> exp;
input.push_back({0,0});
exp.push_back(0);
input.push_back({-1,0});
exp.push_back(1);
input.push_back({-1,-1});
exp.push_back(2);
input.push_back({0,-1});
exp.push_back(3);
input.push_back({1,-1});
exp.push_back(4);
input.push_back({1,0});
exp.push_back(5);
input.push_back({1,1});
exp.push_back(6);
input.push_back({0,1});
exp.push_back(7);
input.push_back({-1,1});
exp.push_back(8);
input.push_back({-2,1});
exp.push_back(9);
input.push_back({-2,0});
exp.push_back(10);
input.push_back({-2,-1});
exp.push_back(11);
input.push_back({-2,-2});
exp.push_back(12);
input.push_back({-1,-2});
exp.push_back(13);
input.push_back({0,-2});
exp.push_back(14);
input.push_back({2,-3});
exp.push_back(35);
input.push_back({-4,3});
exp.push_back(49);
for(int i = 0; i < input.size(); i++)
{
int obs = point2DtoChunkID(input[i]);
if(obs != exp[i])
{
results += "F";
std::cout << "Test FAILED on input = " << input[i].x << "," << input[i].z << std::endl;
std::cout << "Expected " << exp[i] << ", got " << obs << std::endl;
}
else
{
results += ".";
}
}
return results;
}
std::string testDistanceFormula()
{
std::cout << "\nTesting distanceFormula()" << std::endl;
std::string results = "";
double x1, z1, x2, z2, exp, obs;
double tolerance = 0.001;
// The same point
x1 = 0, z1 = 0, x2 = 0, z2 = 0;
exp = 0;
obs = distanceFormula(x1, z1, x2, z2);
if(abs(exp - obs) > tolerance)
{
results += "F";
std::cout << "Test FAILED on input = " << x1 << "," << z1 << "," << x2 << "," << z2 << std::endl;
std::cout << "Expected " << exp << ", got " << obs << std::endl;
}
else
{
results += ".";
}
// Different points
x1 = 2, z1 = 2, x2 = -1, z2 = 5.6;
exp = 4.68614980554399;
obs = distanceFormula(x1, z1, x2, z2);
if(abs(exp - obs) > tolerance)
{
results += "F";
std::cout << "Test FAILED on input = " << x1 << "," << z1 << "," << x2 << "," << z2 << std::endl;
std::cout << "Expected " << exp << ", got " << obs << std::endl;
}
else
{
results += ".";
}
return results;
}
std::string testDistance2d()
{
std::cout << "\nTesting distance2d()" << std::endl;
std::string results = "";
Point p1, p2;
double exp, obs;
double tolerance = 0.001;
// Different y-value
p1 = {5, 128, 6};
p2 = {4, -3, 2};
exp = 4.123105625617661;
obs = distance2d(p1, p2);
if(abs(exp - obs) > tolerance)
{
results += "F";
std::cout << "Test FAILED on different y-coordinate case." << std::endl;
std::cout << "Expected " << exp << ", got " << obs << std::endl;
}
else
{
results += ".";
}
p1 = {5, 0, 6};
p2 = {4, 0, 2};
exp = 4.123105625617661;
obs = distance2d(p1, p2);
if(abs(exp - obs) > tolerance)
{
results += "F";
std::cout << "Test FAILED on same y-coordinate case." << std::endl;
std::cout << "Expected " << exp << ", got " << obs << std::endl;
}
else
{
results += ".";
}
return results;
}
std::string testGetChunkIDsAroundPoint()
{
std::cout << "\nTesting getChunkIDsAroundPoint()" << std::endl;
std::string results = "";
Point2D input;
double radius;
std::vector<int> exp, obs;
// Centered at (0,0), radius = 1
input = {0, 0};
radius = 1;
exp = {7,1,0,5,3};
obs = getChunkIDsAroundPoint(input, radius);
if(exp.size() != obs.size())
{
results += "F";
std::cout << "Test FAILED when radius = 1" << std::endl;
std::cout << "Expected vector of size " << exp.size() << ", got size " << obs.size() << std::endl;
}
else
{
bool passed = true;
for(int i = 0; i < exp.size(); i++)
{
if(exp[i] != obs[i])
{
results += "F";
passed = false;
std::cout << "Test FAILED when radius = 1" << std::endl;
std::cout << "Expected entry " << exp[i] << ", got " << obs[i] << std::endl;
break;
}
}
if(passed)
{
results += ".";
}
}
// Centered at (-1,0), radius = 2
input = {-1, 0};
radius = 2;
exp = {23,9,8,7,27,10,1,0,5,11,2,3,13};
obs = getChunkIDsAroundPoint(input, radius);
if(exp.size() != obs.size())
{
results += "F";
std::cout << "Test FAILED when radius = 2" << std::endl;
std::cout << "Expected vector of size " << exp.size() << ", got size " << obs.size() << std::endl;
}
else
{
bool passed = true;
for(int i = 0; i < exp.size(); i++)
{
if(exp[i] != obs[i])
{
results += "F";
passed = false;
std::cout << "Test FAILED when radius = 2" << std::endl;
std::cout << "Expected entry " << exp[i] << ", got " << obs[i] << std::endl;
break;
}
}
if(passed)
{
results += ".";
}
}
return results;
}
std::string testGetChunkTopLeftCornersAroundPoint()
{
std::cout << "\nTesting getChunkTopLeftCornersAroundPoint()" << std::endl;
std::string results = "";
Point2D input;
double radius;
std::vector<Point2D> exp, obs;
// Centered at (0,0), radius = 1
input = {0, 0};
radius = 1;
exp = {{0,1},{-1,0},{0,0},{1,0},{0,-1}};
obs = getChunkTopLeftCornersAroundPoint(input, radius);
if(exp.size() != obs.size())
{
results += "F";
std::cout << "Test FAILED when radius = 1" << std::endl;
std::cout << "Expected vector of size " << exp.size() << ", got size " << obs.size() << std::endl;
}
else
{
bool passed = true;
for(int i = 0; i < exp.size(); i++)
{
if(exp[i] != obs[i])
{
results += "F";
passed = false;
std::cout << "Test FAILED when radius = 1" << std::endl;
std::cout << "Expected entry " << exp[i].x<<","<< exp[i].z<< ", got " <<obs[i].x<<","<<obs[i].z<< std::endl;
break;
}
}
if(passed)
{
results += ".";
}
}
// Centered at (-1,0), radius = 2
input = {-1, 0};
radius = 2;
exp = {{-1,2},{-2,1},{-1,1},{0,1},{-3,0},{-2,0},{-1,0},{0,0},{1,0},{-2,-1},{-1,-1},{0,-1},{-1,-2}};
obs = getChunkTopLeftCornersAroundPoint(input, radius);
if(exp.size() != obs.size())
{
results += "F";
std::cout << "Test FAILED when radius = 2" << std::endl;
std::cout << "Expected vector of size " << exp.size() << ", got size " << obs.size() << std::endl;
}
else
{
bool passed = true;
for(int i = 0; i < exp.size(); i++)
{
if(exp[i] != obs[i])
{
results += "F";
passed = false;
std::cout << "Test FAILED when radius = 2" << std::endl;
std::cout << "Expected entry " << exp[i].x<<","<< exp[i].z<< ", got " <<obs[i].x<<","<<obs[i].z<< std::endl;
break;
}
}
if(passed)
{
results += ".";
}
}
return results;
}
std::string testGetChunkIDContainingPoint()
{
std::cout << "\nTesting getChunkIDContainingPoint()" << std::endl;
std::string results = "";
std::vector<Point> input {{10, 0, 10}, {500, -20, 500}, {2,7,500}, {500, 0, 2},
{20, 0, -758}};
std::vector<int> exp {0, 0, 0, 0, 14};
int chunkSize = 512;
for(int i = 0; i < input.size(); i++)
{
int obs = getChunkIDContainingPoint(input[i], chunkSize);
if(exp[i] != obs)
{
results += "F";
std::cout << "Test FAILED." << std::endl;
std::cout << "Expected " << exp[i] << ", got " << obs << std::endl;
}
}
return results;
}
std::string testTrueAngleDifference()
{
std::cout << "\nTesting trueAngleDifference()" << std::endl;
std::string results = "";
std::vector<std::string> descriptions;
std::vector<double> angle1s;
std::vector<double> angle2s;
std::vector<double> exp;
double tolerance = 0.01;
double obs;
descriptions.emplace_back("Q1 - Q1");
angle1s.push_back(PI/4);
angle2s.push_back(PI/4);
exp.push_back(0.0);
descriptions.emplace_back("Q2 - Q1");
angle1s.push_back(PI/4);
angle2s.push_back(3*PI/4);
exp.push_back(PI/2);
descriptions.emplace_back("Q1 - Q2");
angle1s.push_back(3*PI/4);
angle2s.push_back(PI/4);
exp.push_back(PI/2);
descriptions.emplace_back("Q3 - Q1");
angle1s.push_back(PI/4);
angle2s.push_back(5*PI/4);
exp.push_back(PI);
descriptions.emplace_back("Q1 - Q3");
angle1s.push_back(5*PI/4);
angle2s.push_back(PI/4);
exp.push_back(PI);
descriptions.emplace_back("Q4 - Q1");
angle1s.push_back(PI/4);
angle2s.push_back(7*PI/4);
exp.push_back(PI/2);
descriptions.emplace_back("Q1 - Q4");
angle1s.push_back(7*PI/4);
angle2s.push_back(PI/4);
exp.push_back(PI/2);
for(int i = 0; i < descriptions.size(); i++)
{
obs = trueAngleDifference(angle1s[i], angle2s[i]);
if(std::abs(exp[i] - obs) > tolerance)
{
results += "F";
std::cout << "Test FAILED for " + descriptions[i] << std::endl;
std::cout << "Expected " << exp[i] << ", got " << obs << std::endl;
}
else
{
results += ".";
}
}
return results;
}
std::string testIsInFieldOfView()
{
std::cout << "\nTesting isInFieldOfView()" << std::endl;
std::string results = "";
Point location = {0, 10, 0};
Point target;
double xzAngle, yAngle, fov;
// In field of view
target = {0, 10, -10};
xzAngle = 3*PI/2;
yAngle = 0;
fov = PI/4;
if(!isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for in field of view" << std::endl;
}
else
{
results += ".";
}
// Wrong on the xz plane
target = {10, 10, 0};
xzAngle = 3*PI/2;
yAngle = 0;
fov = PI/4;
if(isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for wrong on xz plane" << std::endl;
}
else
{
results += ".";
}
// Wrong in the y axis
target = {0, 100, -10};
xzAngle = 3*PI/2;
yAngle = 0;
fov = PI/4;
if(isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for wrong in the y axis" << std::endl;
}
else
{
results += ".";
}
// On ground
target = {0, 0, -50};
xzAngle = 3*PI/2;
yAngle = 0;
fov = PI/6;
if(!isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for on ground" << std::endl;
}
else
{
results += ".";
}
// Far away on ground
target = {0, 0, -1024};
xzAngle = 3*PI/2;
yAngle = 0;
fov = PI/6;
if(!isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for far away on ground" << std::endl;
}
else
{
results += ".";
}
// 360 degree view
target = {1024, 0, 4096};
xzAngle = 3*PI/2;
yAngle = 0;
fov = 2*PI;
if(!isInFieldOfView(target, location, xzAngle, yAngle, fov))
{
results += "F";
std::cout << "Test FAILED for 360 degree view" << std::endl;
}
else
{
results += ".";
}
return results;
}
std::string testCorrectAlignedRectangularCrossSection()
{
std::cout << "\nTesting correctAlignedRectangularCrossSection()" << std::endl;
std::string results = "";
const double TOLERANCE = 0.01;
Point c;
double xw, zw;
int buffer;
std::vector<std::string> cases;
std::vector<Point> inputs;
std::vector<std::experimental::optional<Point>> exp;
std::vector<std::experimental::optional<Point>> obs;
// Fixed parameters
c = {0, 0, 0};
xw = 10;
zw = 20;
buffer = 2;
// When the Point does not need to be corrected
cases.push_back("Way too far left");
inputs.push_back({-30, 0, 0});
exp.push_back(std::experimental::nullopt);
cases.push_back("On the left buffer");
inputs.push_back({-7, 0, 0});
exp.push_back(std::experimental::nullopt);
cases.push_back("Way too far right");
inputs.push_back({30, 0, 0});
exp.push_back(std::experimental::nullopt);
cases.push_back("On the right buffer");
inputs.push_back({7, 0, 0});
exp.push_back(std::experimental::nullopt);
cases.push_back("Way too far up");
inputs.push_back({0, 0, -30});
exp.push_back(std::experimental::nullopt);
cases.push_back("On the top buffer");
inputs.push_back({0, 0, -12});
exp.push_back(std::experimental::nullopt);
cases.push_back("Way too far down");
inputs.push_back({0, 0, 30});
exp.push_back(std::experimental::nullopt);
cases.push_back("On the bottom buffer");
inputs.push_back({0, 0, 12});
exp.push_back(std::experimental::nullopt);
// When the Point does need to be corrected
cases.push_back("Inside zone 1");
inputs.push_back({0, 0, -2});
exp.push_back(std::experimental::optional<Point>({0, 0, -12}));
cases.push_back("Inside zone 2");
inputs.push_back({2, 0, 0});
exp.push_back(std::experimental::optional<Point>({7, 0, 0}));
cases.push_back("Inside zone 3");
inputs.push_back({0, 0, 2});
exp.push_back(std::experimental::optional<Point>({0, 0, 12}));
cases.push_back("Inside zone 4");
inputs.push_back({-2, 0, 0});
exp.push_back(std::experimental::optional<Point>({-7, 0, 0}));
// Diagonal points outside
cases.push_back("Point slightly N of NW and outside");
inputs.push_back({-7, 0, -13});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly W of NW and outside");
inputs.push_back({-8, 0, -12});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly N of NE and outside");
inputs.push_back({7, 0, -13});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly E of NE and outside");
inputs.push_back({8, 0, -12});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly S of SE and outside");
inputs.push_back({7, 0, 13});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly E of SE and outside");
inputs.push_back({8, 0, 12});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly S of SW and outside");
inputs.push_back({-7, 0, 13});
exp.push_back(std::experimental::nullopt);
cases.push_back("Point slightly W of SW and outside");
inputs.push_back({-8, 0, 12});
exp.push_back(std::experimental::nullopt);
// Diagonal points inside
cases.push_back(" Point slightly N of NW and inside buffer");
inputs.push_back({-5.2, 0, -10.5});
exp.push_back(std::experimental::optional<Point>({-5.2, 0, -12}));
for(int i = 0; i < cases.size(); i++)
{
std::experimental::optional<Point> obs = correctAlignedRectangularCrossSection(inputs[i], buffer, c, xw, zw);
if(exp[i])
{
if(!obs || distance2d(*exp[i], *obs) > TOLERANCE)
{
std::cout << "Test FAILED for " + cases[i] << std::endl;
results += "F";
}
else
{
results += ".";
}
}
else
{
if(obs)
{
std::cout << "Test FAILED for " + cases[i] << std::endl;
results += "F";
}
else
{
results += ".";
}
}
}
return results;
}
std::string testCorrectRectangularCrossSection()
{
std::cout << "\nTesting correctRectangularCrossSection()" << std::endl;
std::string results = "";
const double TOLERANCE = 0.01;
Point c;
double xw, zw;
int buffer;
std::vector<std::string> cases;
std::vector<Point> points;
std::vector<double> angles;
std::vector<std::experimental::optional<Point>> exp;
std::vector<std::experimental::optional<Point>> obs;
// Fixed parameters
c = {0, 0, 0};
xw = 10;
zw = 20;
buffer = 2;
cases.push_back("Would have been in, but out due to 45 deg angle");
angles.push_back(PI/4);
points.push_back({6, 0, 11});
exp.push_back(std::experimental::nullopt);
cases.push_back("Would have been out, but in due to 45 deg angle");
angles.push_back(PI/4);
points.push_back({11.313708498984761, 0, -2.8284271247461903});
exp.push_back(std::experimental::optional<Point>({12.020815280171309, 0, -2.121320343559643}));
cases.push_back("Would have been out, but in due to 90 deg angle");
angles.push_back(PI/2);
points.push_back({10, 0, 6});
exp.push_back(std::experimental::optional<Point>({10, 0, 7}));
for(int i = 0; i < cases.size(); i++)
{
std::experimental::optional<Point> obs = correctRectangularCrossSection(points[i], buffer, c, xw, zw, angles[i]);
if(exp[i])
{
if(!obs || distance2d(*exp[i], *obs) > TOLERANCE)
{
std::cout << "Test FAILED for " + cases[i] << std::endl;
results += "F";
}
else
{
results += ".";
}
}
else
{
if(obs)
{
std::cout << "Test FAILED for " + cases[i] << std::endl;
results += "F";
}
else
{
results += ".";
}
}
}
return results;
}<file_sep>#ifndef FPS_TEMPLATE_GAMEMANAGER_H
#define FPS_TEMPLATE_GAMEMANAGER_H
#include <vector>
#include <memory>
#include <iostream>
#include <unordered_map>
#include "player.h"
#include "structs.h"
#include "chunk.h"
#include "mathHelper.h"
#include "button.h"
#include "lampPost.h"
#include "train.h"
#include "coin.h"
enum GameStatus {Intro, Playing, End, Paused};
class GameManager
{
private:
Player player;
int playerHealth;
int playerScore;
// Controls
bool wKey, aKey, sKey, dKey, spacebar;
// Chunks
int chunkSize;
int renderRadius;
std::unordered_map<int, std::shared_ptr<Chunk>> allSeenChunks;
std::vector<std::shared_ptr<Chunk>> currentChunks;
int currentPlayerChunkID;
// Trains
Train train;
// Coins
std::vector<std::shared_ptr<Coin>> coins;
GameStatus currentStatus;
int viewDistance;
// UI
int screenWidth, screenHeight;
Button playButton;
Button playAgainButton;
Button quitButton;
Button continueButton;
std::vector<std::string> instructions;
bool closeWindow = false;
bool showMouse = true;
// Lighting
LightSource playerLight;
std::vector<LightSource> lightSources;
std::unordered_map<std::shared_ptr<LampPost>, bool> lampPosts; // bool determines if it is close or not
// Game parameters
double PLAYER_HEIGHT = 20;
double PLAYER_RADIUS = 5;
RGBAcolor CHUNK_GROUND_COLOR = {0.4, 0.4, 0.4, 1};
double PLAYER_SPEED = 2;
double MOUSE_SENSITIVITY = 0.03;
int MAX_DISTANCE_FROM_SPAWN = 10240;
double GRAVITY = -0.3;
double PLAYER_JUMP_AMOUNT = 4;
int BUTTON_WIDTH = 128;
int BUTTON_HEIGHT = 64;
int BUTTON_RADIUS = 16;
RGBAcolor PLAY_BUTTON_COLOR = {0.0, 0.0, 0.7, 1.0}; // Slightly Dark Blue
RGBAcolor QUIT_BUTTON_COLOR = {0.7, 0.0, 0.0, 1.0}; // Slightly Dark Red
RGBAcolor PLAY_BUTTON_COLOR_H = {0.0, 0.2, 1.0, 1.0}; // Lighter Blue
RGBAcolor QUIT_BUTTON_COLOR_H = {1.0, 0.2, 0.0, 1.0}; // Lighter Red
RGBAcolor BUTTON_TEXT_COLOR = {1.0,1.0,1.0,1.0}; // White
RGBAcolor CURSOR_COLOR = {0.3, 0.3, 0.3, 1.0}; // Dark Gray
RGBAcolor BLACK = {0.0, 0.0, 0.0, 1.0};
double LIGHT_FADE_FACTOR = 0.001;
double PLAYER_LIGHT_FOV = PI/4;
int MAX_LIGHT_LEVEL = 10;
double LAMP_POST_HEIGHT = 30;
double LAMP_POST_RADIUS = 0.5;
RGBAcolor LAMP_POST_COLOR = {0, 0.3, 0.1, 1.0};
RGBAcolor LIGHT_COLOR = {1.0, 1.0, 0.5, 1.0};
double TRAIN_SPEED = 3.0;
double TRAIN_WIDTH = 20;
double TRAIN_HEIGHT = 30;
double TRAIN_LENGTH = 60;
RGBAcolor TRAIN_COLOR = {0.0, 0.0, 0.2, 1.0};
int TRAIN_DAMAGE_PER_TICK = 1;
int MAX_PLAYER_HEALTH = 100;
int HEALTH_BAR_HEIGHT = 30;
int HEALTH_BAR_LENGTH = 256;
RGBAcolor HEALTH_BAR_HEALTH = {0.0, 0.6, 1.0, 1.0};
RGBAcolor HEALTH_BAR_VOID = {1.0, 0.0, 0.2, 1.0};
double COIN_RADIUS = 5;
double COIN_FLOAT_HEIGHT = 7;
double COIN_THICKNESS = 1.5;
double COIN_ROTATION_SPEED = 0.01;
RGBAcolor COIN_COLOR = {1.0, 0.8, 0.1, 1.0};
int MAX_NUM_COINS = 8;
double COIN_ATTRACTION_DISTANCE = 30;
double COIN_ATTRACTION_FORCE = 1;
int COIN_HOVER_PERIOD = 60;
int COIN_HOVER_AMPLITUDE = 3;
public:
GameManager();
GameManager(int inputScreenWidth, int inputScreenHeight, int inputChunkSize, int inputRenderRadius);
// Helper functions for the constructors
void initializePlayer();
void initializeButtons();
void makeInstructions();
void initializePlayerLight();
// Getters
Player getPlayer() const;
bool getWKey() const;
bool getAKey() const;
bool getSKey() const;
bool getDKey() const;
bool getSpacebar() const;
GameStatus getCurrentStatus() const;
bool getCloseWindow() const;
bool getShowMouse() const;
// Setters
void setWKey(bool input);
void setAKey(bool input);
void setSKey(bool input);
void setDKey(bool input);
void setSpacebar(bool input);
void setCurrentStatus(GameStatus input);
// Chunks
void updateCurrentChunks();
// Player
void correctPlayerCollisions();
// Trains
void makeTrain();
// Coins
void spawnRandomlyLocatedCoin();
void checkCoins();
// Camera
Point getCameraLocation() const;
Point getCameraLookingAt() const;
Point getCameraUp() const;
// Mouse
void reactToMouseMovement(int mx, int my, double theta);
void reactToMouseClick(int mx, int my);
// Lighting
double determineOverallLightLevelAt(Point p) const;
double determineChunkLightLevel(Point p) const;
void createRandomLampPost(Point chunkCenter, int chunkSize);
void updateLampPostCloseness();
// Draw
void draw() const;
void drawLampPosts() const;
void drawChunks() const;
void drawTrain() const;
void drawCoins() const;
// Tick helper functions
void tick();
void playerTick();
void trainTick();
void coinsTick();
// Game Management
void checkForGameEnd();
void resetGame();
void togglePaused();
// UI
void drawUI() const;
void drawCursor() const;
void displayInstructions() const;
void drawHealthBar() const;
void displayPlayerScore() const;
void displayFinalScore() const;
};
#endif //FPS_TEMPLATE_GAMEMANAGER_H
<file_sep>#include "ellipticCyl.h"
EllipticCyl::EllipticCyl() : Solid()
{
topXWidth = xWidth;
topZWidth = zWidth;
initializeCorners();
initializeLinePoints();
}
EllipticCyl::EllipticCyl(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
linesDrawnEnum inputLinesDrawn) :
Solid(inputCenter, inputColor, inputXWidth, inputYWidth, inputZWidth, inputLineColor, inputLinesDrawn)
{
topXWidth = xWidth;
topZWidth = zWidth;
initializeCorners();
initializeLinePoints();
}
EllipticCyl::EllipticCyl(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
double inputTopXWidth, double inputTopZWidth,
linesDrawnEnum inputLinesDrawn) :
Solid(inputCenter, inputColor, inputXWidth, inputYWidth, inputZWidth, inputLineColor, inputLinesDrawn)
{
topXWidth = inputTopXWidth;
topZWidth = inputTopZWidth;
initializeCorners();
initializeLinePoints();
}
void EllipticCyl::initializeCorners()
{
double x, z, xTop, zTop;
for(int i = 0; i < smoothness; i++)
{
x = xWidth/2 * cos(2*PI* i / smoothness);
z = zWidth/2 * sin(2*PI* i / smoothness);
xTop = topXWidth/2 * cos(2*PI* i / smoothness);
zTop = topZWidth/2 * sin(2*PI* i / smoothness);
corners.push_back({center.x + xTop, center.y + yWidth/2, center.z + zTop}); // upper face
corners.push_back({center.x + x, center.y - yWidth/2, center.z + z}); // lower face
}
topCenter = {center.x, center.y + yWidth/2, center.z};
bottomCenter = {center.x, center.y - yWidth/2, center.z};
}
void EllipticCyl::initializeLinePoints()
{
int numPoints;
double x,y,z;
// Decide how far apart to make the lines
if(linesDrawn == Low)
{
numPoints = floor(yWidth / distanceBetweenLowLines);
}
else if(linesDrawn == Medium)
{
numPoints = floor(yWidth / distanceBetweenMediumLines);
}
else if(linesDrawn == High)
{
numPoints = floor(yWidth / distanceBetweenHighLines);
}
else // If linesDrawn = Normal or NoLines, do not add any gridlines on the planes
{
return;
}
double distanceBetweenPoints = yWidth / numPoints;
// Iterate through the bottom of the ellipse and add points above it
for(int i = 1; i < corners.size(); i += 2)
{
y = 0;
double theta = 2*PI* (i+1)/2 / smoothness;
linePoints.emplace_back();
for(int j = 0; j < numPoints - 1; j++)
{
y += distanceBetweenPoints;
linePoints.back().push_back(getPointAtHeight(y, theta));
}
}
}
// =============================
//
// Geometry
//
// =============================
double EllipticCyl::getXRadiusAtHeight(double y) const
{
double slope = (topXWidth - xWidth) / 2 / yWidth;
return xWidth/2 + slope*y;
}
double EllipticCyl::getZRadiusAtHeight(double y) const
{
double slope = (topZWidth - zWidth) / 2 / yWidth;
return zWidth/2 + slope*y;
}
Point EllipticCyl::getPointAtHeight(double y, double theta) const
{
double xRad = getXRadiusAtHeight(y);
double zRad = getZRadiusAtHeight(y);
return {center.x + xRad*cos(theta), center.y - yWidth/2 + y, center.z + zRad*sin(theta)};
}
void EllipticCyl::draw(double lightLevel) const
{
drawLines(lightLevel);
drawFaces(lightLevel);
}
void EllipticCyl::drawLines(double lightLevel) const
{
if(linesDrawn == NoLines)
{
return;
}
setGLColorLightLevel(lineColor, lightLevel);
glBegin(GL_LINES);
for(int i = 0; i < 2*smoothness - 3; i += 2)
{
// Upper face
drawPoint(corners[i]);
drawPoint(corners[i + 2]);
// Lower face
drawPoint(corners[i + 1]);
drawPoint(corners[i + 3]);
// Verticals
if(((linesDrawn == Low || linesDrawn == Normal) && i % 12 == 0) || (linesDrawn == Medium && i % 6 == 0) ||
linesDrawn == High)
{
drawPoint(corners[i]);
drawPoint(corners[i+1]);
}
}
// Connect the end to the start
drawPoint(corners[2*smoothness-2]);
drawPoint(corners[0]);
drawPoint(corners[2*smoothness-1]);
drawPoint(corners[1]);
// Vertical
if(linesDrawn == High)
{
drawPoint(corners[2*smoothness-2]);
drawPoint(corners[2*smoothness-1]);
}
glEnd();
if(linesDrawn != Normal)
{
drawGridLines(lightLevel);
}
}
void EllipticCyl::drawFaces(double lightLevel) const
{
setGLColorLightLevel(color, lightLevel);
glDisable(GL_CULL_FACE);
// Draw the top and bottom circles
glBegin(GL_TRIANGLE_FAN);
// center
drawPoint(topCenter);
// top circumference
for(int i = 0; i < smoothness; i++)
{
drawPoint(corners[2*i]);
}
drawPoint(corners[0]);
glEnd();
glBegin(GL_TRIANGLE_FAN);
// center
drawPoint(bottomCenter);
// bottom circumference
for(int i = 0; i < smoothness; i++)
{
drawPoint(corners[2*i + 1]);
}
drawPoint(corners[1]);
glEnd();
// Draw the cylinder part
glBegin(GL_TRIANGLE_STRIP);
for(int i = 0; i < 2*smoothness; i++)
{
drawPoint(corners[i]);
}
// Connect the end to the start
drawPoint(corners[0]);
drawPoint(corners[1]);
glEnd();
glEnable(GL_CULL_FACE);
}
void EllipticCyl::drawGridLines(double lightLevel) const
{
setGLColorLightLevel(lineColor, lightLevel);
glBegin(GL_LINES);
int pointsPerSide;
pointsPerSide = linePoints[0].size();
for(int i = 0; i < pointsPerSide; i++)
{
drawPoint(linePoints[0][i]);
for(int j = 1; j < smoothness; j++)
{
drawPoint(linePoints[j][i]);
drawPoint(linePoints[j][i]);
}
drawPoint(linePoints[0][i]);
}
glEnd();
}
void EllipticCyl::move(double deltaX, double deltaY, double deltaZ)
{
Solid::move(deltaX, deltaY, deltaZ);
movePoint(topCenter, deltaX, deltaY, deltaZ);
movePoint(bottomCenter, deltaX, deltaY, deltaZ);
}
void EllipticCyl::rotate(double deltaX, double deltaY, double deltaZ)
{
Solid::rotate(deltaX, deltaY, deltaZ);
rotatePointAroundPoint(topCenter, center, deltaX, deltaY, deltaZ);
rotatePointAroundPoint(bottomCenter, center, deltaX, deltaY, deltaZ);
}
void EllipticCyl::rotateAroundPoint(const Point &p, double deltaX, double deltaY, double deltaZ)
{
Solid::rotateAroundPoint(p, deltaX, deltaY, deltaZ);
rotatePointAroundPoint(topCenter, p, deltaX, deltaY, deltaZ);
rotatePointAroundPoint(bottomCenter, p, deltaX, deltaY, deltaZ);
}<file_sep>#ifndef STREETNIGHT_LAMPPOST_H
#define STREETNIGHT_LAMPPOST_H
#include "recPrism.h"
#include "ellipticCyl.h"
#include "frustum.h"
#include <vector>
#include <memory>
class LampPost
{
private:
Point location; // location.y is halfway up the pole
double poleRadius;
double poleHeight;
double lightRadius;
double lightHeight;
double baseHeight;
RGBAcolor poleColor;
RGBAcolor lightColor;
double lightIntensity;
std::vector<std::shared_ptr<Solid>> solids;
public:
LampPost();
LampPost(Point inputLocation, double inputPoleRadius, double inputPoleHeight, double inputLightRadius,
double inputLightHeight, RGBAcolor inputPoleColor, RGBAcolor inputLightColor, double inputLightIntensity);
void initializeSolids();
// Getters
Point getLocation() const;
double getLightIntensity() const;
Point getLightLocation() const;
void draw(double lightLevel) const;
};
#endif //STREETNIGHT_LAMPPOST_H
<file_sep>#include "recPrism.h"
RecPrism::RecPrism() : Solid()
{
initializeCorners();
initializeLinePoints();
}
RecPrism::RecPrism(Point inputCenter, RGBAcolor inputColor,
double inputXWidth, double inputYWidth, double inputZWidth, RGBAcolor inputLineColor,
linesDrawnEnum inputLinesDrawn) :
Solid(inputCenter, inputColor, inputXWidth, inputYWidth, inputZWidth, inputLineColor, inputLinesDrawn)
{
initializeCorners();
initializeLinePoints();
}
void RecPrism::initializeCorners()
{
corners.push_back({center.x + xWidth/2, center.y + yWidth/2, center.z + zWidth/2});
corners.push_back({center.x - xWidth/2, center.y + yWidth/2, center.z + zWidth/2});
corners.push_back({center.x + xWidth/2, center.y - yWidth/2, center.z + zWidth/2});
corners.push_back({center.x - xWidth/2, center.y - yWidth/2, center.z + zWidth/2});
corners.push_back({center.x + xWidth/2, center.y + yWidth/2, center.z - zWidth/2});
corners.push_back({center.x - xWidth/2, center.y + yWidth/2, center.z - zWidth/2});
corners.push_back({center.x + xWidth/2, center.y - yWidth/2, center.z - zWidth/2});
corners.push_back({center.x - xWidth/2, center.y - yWidth/2, center.z - zWidth/2});
}
void RecPrism::initializeLinePoints()
{
initializeXLinePoints();
initializeYLinePoints();
initializeZLinePoints();
}
void RecPrism::initializeXLinePoints()
{
int numPoints;
double x,y,z;
// Decide how far apart to make the lines
if(linesDrawn == Low)
{
numPoints = floor(xWidth / distanceBetweenLowLines);
}
else if(linesDrawn == Medium)
{
numPoints = floor(xWidth / distanceBetweenMediumLines);
}
else if(linesDrawn == High)
{
numPoints = floor(xWidth / distanceBetweenHighLines);
}
else // If linesDrawn = Normal or NoLines, do not add any gridlines on the planes
{
return;
}
// The x lines (circling around the x-axis)
double distanceBetweenPointsX = xWidth / numPoints;
// Top front line
x = corners[1].x;
y = corners[1].y + lineOffset;
z = corners[1].z + lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
x += distanceBetweenPointsX;
xLinePoints.push_back({x, y, z});
}
// Bottom Front line
x = corners[3].x;
y = corners[3].y - lineOffset;
z = corners[3].z + lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
x += distanceBetweenPointsX;
xLinePoints.push_back({x, y, z});
}
// Bottom back line
x = corners[7].x;
y = corners[7].y - lineOffset;
z = corners[7].z - lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
x += distanceBetweenPointsX;
xLinePoints.push_back({x, y, z});
}
// Top Back line
x = corners[5].x;
y = corners[5].y + lineOffset;
z = corners[5].z - lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
x += distanceBetweenPointsX;
xLinePoints.push_back({x, y, z});
}
}
void RecPrism::initializeYLinePoints()
{
int numPoints;
double x,y,z;
// Decide how far apart to make the lines
if(linesDrawn == Low)
{
numPoints = floor(yWidth / distanceBetweenLowLines);
}
else if(linesDrawn == Medium)
{
numPoints = floor(yWidth / distanceBetweenMediumLines);
}
else if(linesDrawn == High)
{
numPoints = floor(yWidth / distanceBetweenHighLines);
}
else // If linesDrawn = Normal or NoLines, do not add any gridlines on the planes
{
return;
}
// The y lines (circling around the y-axis)
double distanceBetweenPointsY = yWidth / numPoints;
// Front left line
x = corners[3].x - lineOffset;
y = corners[3].y;
z = corners[3].z + lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
y += distanceBetweenPointsY;
yLinePoints.push_back({x, y, z});
}
// Front Right line
x = corners[2].x + lineOffset;
y = corners[2].y;
z = corners[2].z + lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
y += distanceBetweenPointsY;
yLinePoints.push_back({x, y, z});
}
// Back right line
x = corners[6].x + lineOffset;
y = corners[6].y;
z = corners[6].z - lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
y += distanceBetweenPointsY;
yLinePoints.push_back({x, y, z});
}
// Back Left line
x = corners[7].x - lineOffset;
y = corners[7].y;
z = corners[7].z - lineOffset;
for(int i = 0; i < numPoints - 1; i++)
{
y += distanceBetweenPointsY;
yLinePoints.push_back({x, y, z});
}
}
void RecPrism::initializeZLinePoints()
{
int numPoints;
double x,y,z;
// Decide how far apart to make the lines
if(linesDrawn == Low)
{
numPoints = floor(zWidth / distanceBetweenLowLines);
}
else if(linesDrawn == Medium)
{
numPoints = floor(zWidth / distanceBetweenMediumLines);
}
else if(linesDrawn == High)
{
numPoints = floor(zWidth / distanceBetweenHighLines);
}
else // If linesDrawn = Normal or NoLines, do not add any gridlines on the planes
{
return;
}
// The z lines (circling around the z-axis)
double distanceBetweenPointsZ = zWidth / numPoints;
// Top Right line
x = corners[4].x + lineOffset;
y = corners[4].y + lineOffset;
z = corners[4].z;
for(int i = 0; i < numPoints - 1; i++)
{
z += distanceBetweenPointsZ;
zLinePoints.push_back({x, y, z});
}
// Bottom right line
x = corners[6].x + lineOffset;
y = corners[6].y - lineOffset;
z = corners[6].z;
for(int i = 0; i < numPoints - 1; i++)
{
z += distanceBetweenPointsZ;
zLinePoints.push_back({x, y, z});
}
// Bottom Left line
x = corners[7].x - lineOffset;
y = corners[7].y - lineOffset;
z = corners[7].z;
for(int i = 0; i < numPoints - 1; i++)
{
z += distanceBetweenPointsZ;
zLinePoints.push_back({x, y, z});
}
// Top Left line
x = corners[5].x - lineOffset;
y = corners[5].y + lineOffset;
z = corners[5].z;
for(int i = 0; i < numPoints - 1; i++)
{
z += distanceBetweenPointsZ;
zLinePoints.push_back({x, y, z});
}
}
void RecPrism::draw(double lightLevel) const
{
glDisable(GL_CULL_FACE);
drawLines(lightLevel);
drawFaces(lightLevel);
glEnable(GL_CULL_FACE);
}
void RecPrism::drawLines(double lightLevel) const
{
if(linesDrawn == NoLines)
{
return;
}
setGLColorLightLevel(lineColor, lightLevel);
glBegin(GL_LINES);
drawPoint(corners[1]);
drawPoint(corners[0]);
drawPoint(corners[1]);
drawPoint(corners[3]);
drawPoint(corners[3]);
drawPoint(corners[2]);
drawPoint(corners[2]);
drawPoint(corners[0]);
drawPoint(corners[4]);
drawPoint(corners[5]);
drawPoint(corners[5]);
drawPoint(corners[7]);
drawPoint(corners[7]);
drawPoint(corners[6]);
drawPoint(corners[6]);
drawPoint(corners[4]);
drawPoint(corners[0]);
drawPoint(corners[4]);
drawPoint(corners[2]);
drawPoint(corners[6]);
drawPoint(corners[3]);
drawPoint(corners[7]);
drawPoint(corners[1]);
drawPoint(corners[5]);
glEnd();
if(linesDrawn != Normal)
{
drawGridLines(lightLevel);
}
}
void RecPrism::drawFaces(double lightLevel) const
{
glBegin(GL_QUADS);
setGLColorLightLevel(color, lightLevel);
drawPoint(corners[0]);
drawPoint(corners[1]);
drawPoint(corners[3]);
drawPoint(corners[2]);
drawPoint(corners[5]);
drawPoint(corners[4]);
drawPoint(corners[6]);
drawPoint(corners[7]);
drawPoint(corners[6]);
drawPoint(corners[4]);
drawPoint(corners[0]);
drawPoint(corners[2]);
drawPoint(corners[4]);
drawPoint(corners[5]);
drawPoint(corners[1]);
drawPoint(corners[0]);
drawPoint(corners[6]);
drawPoint(corners[2]);
drawPoint(corners[3]);
drawPoint(corners[7]);
drawPoint(corners[3]);
drawPoint(corners[1]);
drawPoint(corners[5]);
drawPoint(corners[7]);
glEnd();
}
void RecPrism::drawGridLines(double lightLevel) const
{
setGLColorLightLevel(lineColor, lightLevel);
glBegin(GL_LINES);
int pointsPerSide;
// x lines
pointsPerSide = xLinePoints.size()/4;
for(int i = 0; i < pointsPerSide; i++)
{
drawPoint(xLinePoints[i]);
drawPoint(xLinePoints[i + pointsPerSide]);
drawPoint(xLinePoints[i + pointsPerSide]);
drawPoint(xLinePoints[i + 2*pointsPerSide]);
drawPoint(xLinePoints[i + 2*pointsPerSide]);
drawPoint(xLinePoints[i + 3*pointsPerSide]);
drawPoint(xLinePoints[i + 3*pointsPerSide]);
drawPoint(xLinePoints[i]);
}
// y lines
pointsPerSide = yLinePoints.size()/4;
for(int i = 0; i < pointsPerSide; i++)
{
drawPoint(yLinePoints[i]);
drawPoint(yLinePoints[i + pointsPerSide]);
drawPoint(yLinePoints[i + pointsPerSide]);
drawPoint(yLinePoints[i + 2*pointsPerSide]);
drawPoint(yLinePoints[i + 2*pointsPerSide]);
drawPoint(yLinePoints[i + 3*pointsPerSide]);
drawPoint(yLinePoints[i + 3*pointsPerSide]);
drawPoint(yLinePoints[i]);
}
// z lines
pointsPerSide = zLinePoints.size()/4;
for(int i = 0; i < pointsPerSide; i++)
{
drawPoint(zLinePoints[i]);
drawPoint(zLinePoints[i + pointsPerSide]);
drawPoint(zLinePoints[i + pointsPerSide]);
drawPoint(zLinePoints[i + 2*pointsPerSide]);
drawPoint(zLinePoints[i + 2*pointsPerSide]);
drawPoint(zLinePoints[i + 3*pointsPerSide]);
drawPoint(zLinePoints[i + 3*pointsPerSide]);
drawPoint(zLinePoints[i]);
}
}
<file_sep>#ifndef STREETNIGHT_TRAIN_H
#define STREETNIGHT_TRAIN_H
#include "recPrism.h"
#include "ellipticCyl.h"
#include "mathHelper.h"
#include <vector>
#include <memory>
class Train
{
private:
Point location;
RGBAcolor color;
double xWidth, yWidth, zWidth;
double speed;
Point velocity;
double xzAngle;
std::vector<std::shared_ptr<Solid>> solids;
RecPrism hitbox;
public:
Train();
Train(Point inputLocation, RGBAcolor inputColor, double inputXWidth, double inputYWidth, double inputZWidth,
double inputSpeed, double inputXZAngle);
void initializeVelocity();
void initializeSolids();
void initializeHitbox();
// Getters
Point getLocation() const;
Point getVelocity() const;
void draw(double lightLevel) const;
void tick();
void move();
std::experimental::optional<Point> correctCollision(Point p, double buffer) const;
};
#endif //STREETNIGHT_TRAIN_H
| 66d83f5b5df0d9d6650b5145dae324ad7f72a531 | [
"Markdown",
"C",
"CMake",
"C++"
]
| 23 | C++ | marcus-elia/streetnight | 3d99e623ce35c3ec6c722e46168b0bc65aeef301 | 7e9a3a2798f17a89956f118fd890e9b841a33a53 |
refs/heads/master | <file_sep>
<?php
header("Location: /html/register.php");
die();
?>
<file_sep><!-- TODO: watch, games, campus -->
<?php
session_start();
if($_SESSION["id"]==null) {
header('Location: register.php');
// console_log("PENIA");
}
// console_log($_SESSION["bday"]);
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Facebook</title>
<link rel="shortcut icon" href="https://cdn.iconscout.com/icon/free/png-512/facebook-logo-2019-1597680-1350125.png">
<link rel="stylesheet" href="../css/zhi_redesign_style.css">
</head>
<body>
<div class = "navbar">
<img id = "fbicon" src = "https://cdn.iconscout.com/icon/free/png-512/facebook-logo-2019-1597680-1350125.png" width="40px" onclick="gotohome()" height="40px">
<div class="searchbox">
<input type="text" name="searchfb" id= "searchfb" placeholder="Search Facebook">
</div>
<img id="fbtext" src = "../images/fbtitle.png">
<div class="profileicons">
<p id="profilename" style="float: right;">Larry</p>
<img id="profilepic"style="float: right;" src="../images/profilepicimg.png" width="25px" height="25px">
</div>
<div class="righticonbuttons">
<div class="tooltip">
<img src="../images/add.png" width="45px" height="45px">
<span class="tooltiptext">Create</span>
</div>
<div class="tooltip">
<img src="../images/messageicon.png" width="45px" height="45px">
<span class="tooltiptext">Messaging</span>
</div>
<div class="tooltip">
<img src="../images/notif.png" width="45px" height="45px">
<span class="tooltiptext">Notifications</span>
</div>
<div class="tooltip">
<img src="../images/trinagle.png" width="45px" height="45px" onclick="showpop()">
<span class="tooltiptext">Account</span>
</div>
</div>
</div>
<div class="popout" id= "popout">
<div class="popouticons">
<img id="profilepic"style="float: left;" src="../images/profilepicimg.png" width="55px" height="55px">
<div class= "description">
<p><b><NAME></b></p>
<a href="https://www.facebook.com/larry.zhi.58/" target="blank">See Your Profile</a>
<p id = "logout"><a href="logout.php">Logout</a></p>
</div>
</div>
</div>
<div id = "table" class = "table">
<h1>Shortcuts</h1>
<div class="horizontal">
<div class="vertically" onclick="gotocampus()">
<p>Campus</p>
</div>
<div class="vertically">
<p>Marketplace</p>
</div>
</div>
<div class="horizontal">
<div class="vertically">
<p>Friends</p>
</div>
<div class="vertically">
<p>Games</p>
</div>
</div>
<div class="horizontal">
<div class="vertically">
<p>Pages</p>
</div>
<div class="vertically">
<p>Movies</p>
</div>
</div>
<div class="horizontal">
<div class="vertically">
<p>Your Pages</p>
</div>
<div class="vertically">
<p>Rooms</p>
</div>
</div>
<div class="horizontal">
<div class="vertically">
<p>Your Pages</p>
</div>
<div class="vertically">
<p>Rooms</p>
</div>
</div>
</div>
<!-- <img src="../images/open.png" width="45px" height="45px" id="open" onclick="showmore()"> -->
<img src="../images/cancel.png" width="45px" height="25px" id="close" onclick="showless()">
<div class = "midcontainer">
<div class = "stories">
<img src="https://ipt.imgix.net/201447/x/0/how-and-why-you-should-shoot-vertical-landscape-photos-6.jpg?auto=compress%2Cformat&ch=Width%2CDPR&dpr=1&ixlib=php-3.3.0&w=1300" width="130px" height=250px">
<img src="https://static.photocdn.pt/images/articles/2018/05/07/articles/2017_8/landscape_photography_tips.jpg" width="130px" height=250px">
<img src="https://images.unsplash.com/photo-1444041103143-1d0586b9c0b8?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9" width="130px" height=250px">
<img src="https://danbaileyphoto.com/blog/wp-content/uploads/2018/03/AK-NATWT-ANC-05061-e1520967426417.jpg" width="130px" height=250px">
<img src="https://ipt.imgix.net/201446/x/0/how-and-why-you-should-shoot-vertical-landscape-photos-7.jpg?auto=compress%2Cformat&ch=Width%2CDPR&dpr=1&ixlib=php-3.3.0&w=1300" width="130px" height=250px">
</div>
<div class = "status">
<div class="topstatus">
<img src="../images/profilepicimg.png" width="44px" height="44px">
<input class="statustext" type="text" name="statustext" placeholder="What's on your mind Larry?" id="statusinput">
</div>
<hr class="break">
<div class="bottomstatus">
<div class="subdivstatus">
<img src="../images/add.png" width="35px" height="35px">
<p>Live Video</p>
</div>
<div class="subdivstatus">
<img src="../images/add.png" width="35px" height="35px">
<p>Photo/Video</p>
</div>
<div class="subdivstatus">
<img src="../images/add.png" width="35px" height="35px">
<p>Feeling/Activities</p>
</div>
</div>
</div>
<div class = "rooms">
<div class="toproom">
<img src="../images/profilepicimg.png" width="30px" height="30px">
<p><b>Rooms</b> - Video Chat With Friends</p>
</div>
<div class="bottomroom">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
<img src="../images/profilepicimg.png" width="35px" height="35px">
</div>
</div>
<div class = "postcontain">
<div class = "post">
<div class="toppost">
<img src="../images/profilepicimg.png" width="40px" height="40px">
<div class="postheader">
<p><NAME> -> Web Design Memes</p>
<p class="timestamp">1 hr 9 min ago</p>
</div>
</div>
<img class="postcontent" src="https://www.siliconrepublic.com/wp-content/uploads/2014/12/img/web-designer-meme-2.jpg" width="100%">
<p>Likes: 39</p>
<hr>
<div class="likecomment">
<div class="imgp">
<img src="https://facebookbrand.com/wp-content/uploads/2018/09/thumb.png?w=420&h=421"
width="25px" height="25px">
<p>Like</p>
</div>
<div class="imgp">
<img src="https://img.pngio.com/comment-icon-transparent-184635-free-icons-library-comment-icon-png-1600_1600.jpg"
id= "commentimg"
width=" 25px" height="25px">
<p>Comment</p>
</div>
</div>
<hr>
<div id="commm"></div>
<div class="writecomment">
<img src="../images/profilepicimg.png"
id= "commentimg"
width="30px" height="30 px">
<input class="commenttext" type="text" name="statustext" placeholder="Write a comment" id ="comment123">
</div>
</div>
<div class = "post">
<div class="toppost">
<img src="../images/profilepicimg.png" width="40px" height="40px">
<div class="postheader">
<p><NAME> -> Web Design Memes</p>
<p class="timestamp">1 hr 9 min ago</p>
</div>
</div>
<img class="postcontent" src="https://www.siliconrepublic.com/wp-content/uploads/2014/12/img/web-designer-meme-2.jpg" width="100%">
<p>Likes: 39</p>
<hr>
<div class="likecomment">
<div class="imgp">
<img src="https://facebookbrand.com/wp-content/uploads/2018/09/thumb.png?w=420&h=421"
width="25px" height="25px">
<p>Like</p>
</div>
<div class="imgp">
<img src="https://img.pngio.com/comment-icon-transparent-184635-free-icons-library-comment-icon-png-1600_1600.jpg"
id= "commentimg"
width=" 25px" height="25px">
<p>Comment</p>
</div>
</div>
<hr>
<div id="commm"></div>
<div class="writecomment">
<img src="../images/profilepicimg.png"
id= "commentimg"
width="30px" height="30 px">
<input class="commenttext" type="text" name="statustext" placeholder="Write a comment" id ="comment1234">
</div>
</div>
</div>
</div>
<div class = "rightdrawer">
<p>Birthdays</p>
<ul>
<li>
<img src="https://i.pinimg.com/originals/3f/2f/48/3f2f48437d350bff3effd49a9d8bc351.png" width="40px" height="40px">
<p>Happy Birthday Andrew!</p>
</li>
<li>
<img src="https://i.pinimg.com/originals/3f/2f/48/3f2f48437d350bff3effd49a9d8bc351.png" width="40px" height="40px">
<p>Happy Birthday Andrew!</p>
</li>
</ul>
<hr>
<p>Contacts</p>
<ul>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
<li>
<img src="../images/profilepicimg.png" width="40px" height="40px">
<p><NAME></p>
</li>
</ul>
</div>
<!-- <img src="../images/add.png" id="friends"> -->
<img src="../images/menu.png" id="menu" onclick="showmore()">
<p id="privacy" style="font-size: 12px; font-weight: 200;">Privacy · Terms · Advertising · Ad Choices · Cookies · · Facebook © 2020
We definitely do not steal your data :))</p>
<script>
var passedArray =
<?php echo json_encode($_SESSION); ?>;
console.log(passedArray);
var fname = passedArray.fname;
console.log(fname);
document.getElementById("profilename").innerHTML= fname;
</script>
<script src="../script/zhi_redesign_script.js" defer=""></script>
</body>
</html><file_sep>document.getElementById('nav').style.opacity="0.5";
function unblur(){
document.getElementById('nav').style.opacity="1";
document.getElementById('popup').style.display="none";
}
function gotohome(){
window.location="home.php"
// console.log("campus.html");
console.log("hello");
}
| cf2a5b9e46fe718f433f3e54610b5dc4b5221c83 | [
"JavaScript",
"PHP"
]
| 3 | PHP | larryz1230/webredesign | b2ec9632d7dd8ea8cc415b8259f947bffe757f00 | e990fbbdddfe3c45a07285b95eff170571d27d8f |
refs/heads/master | <repo_name>meeoh/CSGO-Wallpaper-Downloader<file_sep>/README.md
# CSGO-Wallpaper-Downloader
downloads all the pictures from every page from http://www.mossawi.nl/csgo/
Run imagescraper.exe in windows folder or run imagescraper.py, a folder in where the script is being ran named csgoBackgrounds will be created, and all the pictures will be in there
<file_sep>/imagescraper.py
from bs4 import BeautifulSoup
import requests
import urllib
import os
def download(soup):
for link in soup.find_all("img"):
global counter
dl = "http://www.mossawi.nl/csgo/" + link['src'].replace('thumbnails','original')
urllib.urlretrieve(dl,"csgoBackgrounds/csgoBackground" + str(counter) + ".png")
counter += 1
#counter for pic nubmer
counter = 1
#this is the folder that the pics will be saved in
newpath = os.getcwd() + "\csgoBackgrounds"
#if it doesnt exist, make it
if not os.path.exists(newpath):
os.makedirs(newpath)
#make one initial call to find how many pages there are
url = "http://www.mossawi.nl/csgo/"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
#set the number of pages
numPages = len(soup.find_all("a", class_="pagination-item"))
#loop through amount of pages
i = 1
while(i <= numPages):
#first page link doesnt have a part in the url
if (i == 1):
url = "http://www.mossawi.nl/csgo/"
else :
url = "http://www.mossawi.nl/csgo/?page=" + str(i)
#download all the pics on that page
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "html.parser")
download(soup)
#increment to next page
i += 1<file_sep>/setup.py
from distutils.core import setup
import py2exe
setup(
console=['imagescraper.py'],
options = {
'py2exe': {
'packages': ['BeautifulSoup','requests','urllib','os']
}
}
) | c86778dea1df95ed03b02d7e6dbff7f6f5651e6c | [
"Markdown",
"Python"
]
| 3 | Markdown | meeoh/CSGO-Wallpaper-Downloader | 5428689785d887ecc17df0575735382fdea4e13a | bccbe5c094a33a799c1ee8127b598e42bb3ed14e |
refs/heads/master | <repo_name>denBot/dmenu_nordvpn<file_sep>/nord.sh
#!/bin/bash
typeset -A menu
menu=()
show_status () {
# Show the nordvpn status info if available
while read -r line; do
menu+=([$line]="nord")
done <<< $(nordvpn status)
}
show_settings () {
# Show current settings and allow user to toggle
# auto-connect, cybersec, obfuscate, killswitch and notifications.
menu+=([Select option to toggle it:]="echo")
while read -r line; do
if [ ! -z "${line// }" ]; then
if [ -z "$(echo $line | grep 'enabled')" ]; then
toggle="true"
else
toggle="false"
fi
if grep -q "Auto-connect" <<< "$line"; then cmd="autoconnect"
elif grep -q "CyberSec" <<< "$line"; then cmd="cybersec"
elif grep -q "Obfuscate" <<< "$line"; then cmd="obfuscate"
elif grep -q "Kill Switch" <<< "$line"; then cmd="killswitch"
elif grep -q "Notify" <<< "$line"; then cmd="notify"
fi
menu+=([$line]="nordvpn set $cmd $toggle && nord settings")
fi
done <<< $(nordvpn settings)
}
show_menu () {
# The general nordvpn menu that allows for connect/disconnect and submenu navigation
vermsg=$(nordvpn countries | grep 'new version')
if [ -z vermsg ]; then
countries=$(nordvpn countries)
else
countries=$(nordvpn countries | tail -n +2)
fi
if nordvpn status | grep -q 'Disconnected'; then
menu+=([1 - Connect to NordVPN]="nordvpn connect")
for country in $countries; do
if [ ! -z "${country// }" ]; then
menu+=([$country]="nordvpn connect $country")
fi
done
else
menu+=(
[1 - Disconnect from NordVPN]="nordvpn disconnect"
[3 - View Status]="nord status"
)
fi
menu+=([2 - Settings]="nord settings")
}
# Checks script argument for status or settings options
if [[ $1 == "status" ]]; then
show_status
elif [[ $1 == "settings" ]]; then
show_settings
else
show_menu
fi
# Displays country if connected to one
country=$(nordvpn status | grep "Country" | cut -c 10-)
if [[ -z "$country" ]]; then
RTEXT="NordVPN (Disconnected)"
else
RTEXT="NordVPN ($country)"
fi
# Section from rofigen by losoliveirasilva
# URL: https://github.com/losoliveirasilva/rofigen
launcher=(rofi -dmenu -i -lines 10 -p "${RTEXT}" -width 30 -location 0 -bw 1)
selection="$(printf '%s\n' "${!menu[@]}" | sort | "${launcher[@]}")"
if [[ -n $selection ]]; then
exec ${menu[${selection}]}
fi
<file_sep>/README.md
# dmenu_nordvpn
This is a very basic rofi interface for interacting the NordVPN client installed on a linux system.

For now, you just need to be logged into NordVPN for the menu system to work properly.
This rofi menu script allows you to:
- toggle basic settings
- connect and disconnect from the vpn service
- quickly view the nordvpn status information
- connect to a specific country
**Requirements:**
- [NordVPN](https://aur.archlinux.org/packages/nordvpn-bin/) for linux
- [rofi](https://aur.archlinux.org/packages/rofi-git/) application launcher
**TODO List:**
- Implement login feature
- Re-open settings panel on toggle
- Change country when already connected go ond
| 5c8ab631cfc0c8efb6cb3f1d37980c1c0879425a | [
"Markdown",
"Shell"
]
| 2 | Shell | denBot/dmenu_nordvpn | 5940641770f7f52ea49e62762ba96c59b0a3fdf0 | 5394cb917184494e3a465cadd7fc7008d035d6fd |
refs/heads/master | <file_sep>package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
String name;
String roll_no;
String phone_number;
String schoolname;
String saikat;
String saikat34;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
| f3eeb36b70f6e0f2a9b8b308f89799f550a7cf76 | [
"Java"
]
| 1 | Java | sakky16/SampleGit | 3702a63f61fc2f82b1e5bdea4036903f5d8f70e2 | 99d877c893b7e7ae597c06bb0f196512aecb564d |
refs/heads/master | <file_sep>import React, { useContext } from 'react';
import { AuthContext } from '../Authentication/Firebase/Context';
import Authorized from './Authorized';
import NonAuthorized from './NonAuthorized';
import Private from '../Authentication/Private';
const Navigation = () => {
const { currentUser } = useContext(AuthContext);
return currentUser ? <Private component={Authorized} /> : <NonAuthorized />;
};
export default Navigation;
<file_sep>import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import Account from '../../pages/Account';
import Admin from '../../pages/Admin';
import Home from '../../pages/Home';
import Landing from '../../pages/Landing';
import PasswordForget from '../../pages/PasswordForget';
import SignIn from '../../pages/SignIn';
import SignUp from '../../pages/SignUp';
import PrivateRoute from '../Authentication/Private';
import Navigation from '../Navigation';
const NoMatch = () => (
<>
<div>- 404 -</div>
</>
);
const App = () => (
<>
<Router>
<div>
<Navigation />
<hr />
<Switch>
<Route exact path={ROUTES.LANDING} component={Landing} />
<Route exact path={ROUTES.SIGN_UP} component={SignUp} />
<Route exact path={ROUTES.SIGN_IN} component={SignIn} />
<Route exact path={ROUTES.PASSWORD_FORGET} component={PasswordForget} />
<PrivateRoute exact path={ROUTES.HOME} component={Home} />
<PrivateRoute exact path={ROUTES.ACCOUNT} component={Account} />
<PrivateRoute exact path={ROUTES.ADMIN} component={Admin} />
<Route path='*' component={NoMatch} />
</Switch>
</div>
</Router>
</>
);
export default App;
| 2b2e6eb82fe2c8fccc9e4c4b869046179ffde3c8 | [
"JavaScript"
]
| 2 | JavaScript | 415CA/react-redux-toolkit | c44a2247d23cca882c80170df33e264a301623c8 | 6205789e3525b64c89cf956caf3cf534da3baea8 |
refs/heads/master | <file_sep>/**
* @author Rube
* @date 15/12/15
*/
var http = require('http');
var mq = require('mq');
var connect = require('./lib/connect');
var request = require('./lib/request');
var response = require('./lib/response');
var cookies = require('./lib/cookies');
var app = Application.prototype;
var methodCollection = {};
module.exports = Application;
function Application() {
if (!(this instanceof Application)) return new Application();
this.middlewares = {'__all__': []};
this.connected = {};
this.routing = {};
request.init.call(methodCollection);
cookies.init.call(methodCollection);
response.init.call(methodCollection);
}
app.listen = function(port) {
var that = this;
for (var route in this.middlewares) {
(function(route) {
that.connected[route] = function(cxt) {
return connect.call(cxt, that.middlewares['__all__'].concat(that.middlewares[route]));
};
that.routing[route] = function(r) {
that.handler.call(that, r, route);
}
})(route);
}
var svr = new http.Server(port, new mq.Routing(that.routing));
svr.run();
};
app.use = function(middleware) {
if (typeof middleware === 'function') {
this.middlewares['__all__'].push(middleware);
} else {
var argv = Array.prototype.slice.apply(arguments);
if (argv[1].toString().toLocaleLowerCase() === 'handler') {
this.routing[argv[0]] = argv[1];
return;
}
this.middlewares[argv[0]] = this.middlewares[argv[0]] || [];
this.middlewares[argv[0]].push(argv[1]);
}
};
app.handler = function(r, route) {
var _r = Object.create({});
Object.assign(_r, methodCollection);
_r.r = r;
_r.key = app.key;
request.run.call(_r, r);
cookies.run.call(_r, r);
this.connected[route](_r).call(_r);
response.run.call(_r, r);
};
app.key = 'fibx';<file_sep>var test = require('test');
var http = require('http');
var coroutine = require('coroutine');
var fs = require('fs');
var md5 = require('hash').md5;
var app = require('../index')();
coroutine.start(function() {
/** fibx request **/
app.use('^/request/basic$', function() {
this.body = {
method: this.method,
keepAlive: this.keepAlive,
path: this.path,
protocol: this.protocol,
ip: this.ip,
port: this.port,
length: this.length,
type: this.type,
host: this.host
};
});
app.use('^/request/query$', function() {
this.body = this.query;
});
app.use('^/request/form$', function() {
this.body = this.form;
});
app.use('^/request/type$', function() {
this.body = this.is('^text/xm[a-z]+$');
});
/** fibx cookies **/
app.use('^/cookies/signed$', function() {
if (this.query.c === 'get') {
console.log(this.r.cookies.all('b'));
console.log(this.r.cookies.all('b.sig'));
this.body = this.cookies.get('b');
}
if (this.query.c === 'set') {
this.cookies.set('b', 'papapa');
this.body = 'papapa';
}
});
app.use('^/cookies/nosigned$', function() {
if (this.query.c === 'get') {
this.body = this.cookies.get('a', {signed: false});
}
if (this.query.c === 'set') {
this.cookies.set('a', 'papapa', {signed: false});
this.body = 'papapa';
}
});
/** fibx response **/
app.use('^/response/number$', function() {
this.body = 1;
});
app.use('^/response/string$', function() {
this.body = 'hello';
});
app.use('^/response/object2json$', function() {
this.body = {a: 1};
});
app.use('^/response/boolean$', function() {
this.body = false;
});
app.use('^/response/stream$', function() {
this.body = fs.open('./index.js');
});
app.use('^/response/status$', function() {
this.status = 500;
this.type = 'text/xml';
});
app.use('^/response/redirect$', function() {
this.redirect('http://localhost:5210/response/number');
});
/** fibx middleware **/
app.use('^/next$', function(next) {
this.state = {};
this.state.number = 1;
next && next();
this.body = 'number:' + this.state.number;
});
app.use('^/next$', function() {
this.state.number++;
});
app.use('^/nextr$', function(next) {
this.state = {};
this.state.number = 1;
this.body = next();
});
app.use('^/nextr$', function() {
this.state.number += 10;
return 'number:' + this.state.number;
});
app.use('^/nextp$', function(next) {
this.state = {};
this.body = next('hello Rube');
});
app.use('^/nextp$', function(value) {
return value;
});
/** fibx basic **/
app.use(function(next) {
this.body = 'hello world';
next && next();
});
app.use('^/fibx$', function() {
this.body = 'hello a';
});
app.use('^/fileHandle/(.*)$', http.fileHandler('./'));
app.use('/', function() {
this.body = 'hello b';
});
app.listen(5210);
});
coroutine.sleep(100);
test.setup();
describe('-----------------------fibx----------------------\r\n', function() {
describe('fibx basic', function() {
it('fibx start and listen the port', function() {
var r = http.request('get', 'http://127.0.0.1:5210/');
assert.equal(r.read().toString(), 'hello b');
});
it('fibx __all__ middleware execute', function() {
var r = http.request('get', 'http://127.0.0.1:5210/__all__');
assert.equal(r.read().toString(), 'hello world');
});
it('fibx route middleware execute', function() {
var r = http.request('get', 'http://127.0.0.1:5210/fibx');
assert.equal(r.read().toString(), 'hello a');
});
it('fibx fileHandler can be used', function() {
var r = http.request('get', 'http://127.0.0.1:5210/fileHandle/index.js');
var text = fs.open('./index.js').read().toString();
assert.equal(text, r.read().toString());
});
it('request is independent', function() {
var r = http.request('get', 'http://127.0.0.1:5210/response/status');
assert.equal(r.headers.first('Content-Type'), 'text/xml');
assert.equal(r.status, 500);
var r = http.request('get', 'http://127.0.0.1:5210/response/number');
assert.equal(r.status, 200);
});
});
describe('fibx middleware', function() {
it('multi middlewares', function() {
var r = http.request('get', 'http://127.0.0.1:5210/next');
assert.equal(r.read().toString(), 'number:2');
});
it('fibx can receive post,get,and more', function() {
var r1 = http.request('post', 'http://127.0.0.1:5210/next');
var r2 = http.request('delete', 'http://127.0.0.1:5210/next');
var r3 = http.request('put', 'http://127.0.0.1:5210/next');
var r4 = http.request('get', 'http://127.0.0.1:5210/next');
assert.equal(r1.read().toString(), 'number:2');
assert.equal(r2.read().toString(), 'number:2');
assert.equal(r3.read().toString(), 'number:2');
assert.equal(r4.read().toString(), 'number:2');
});
it('next return value', function() {
var r = http.request('get', 'http://127.0.0.1:5210/nextr');
assert.equal(r.read().toString(), 'number:11');
});
it('next pass value', function() {
var r = http.request('get', 'http://127.0.0.1:5210/nextp');
assert.equal(r.read().toString(), 'hello Rube');
});
});
describe('fibx request', function() {
it('request basic', function() {
var r = http.request('get', 'http://127.0.0.1:5210/request/basic');
var res = {
"method": "get",
"keepAlive": true,
"path": "/request/basic",
"protocol": "HTTP/1.1",
"ip": "127.0.0.1",
"length": 0,
"host": "127.0.0.1:5210"
};
var sure = JSON.parse(r.read().toString());
assert.equal(typeof sure.port, 'number');
delete sure.port;
assert.equal(JSON.stringify(res), JSON.stringify(sure));
});
it('request query', function() {
var r = http.request('get', 'http://127.0.0.1:5210/request/query?hello=1&world=2');
assert.equal(r.read().toString(), JSON.stringify({hello: "1", world: "2"}));
});
it('request form', function() {
var r = http.post('http://127.0.0.1:5210/request/form', "hello=a&world=b", {"Content-Type": "application/x-www-form-urlencoded"});
assert.equal(r.read().toString(), JSON.stringify({hello: "a", world: "b"}));
});
it('request type is/get', function() {
var r = http.request('get', 'http://127.0.0.1:5210/request/type', {"Content-Type": "text/xml"});
var r1 = http.request('get', 'http://127.0.0.1:5210/request/type', {"Content-Type": "text/xm1"});
assert.equal('false', r1.read().toString());
assert.equal('true', r.read().toString());
});
});
describe('fibx response', function() {
function handler(resData, type, path) {
app.handler({
response: {
write: function(data) {
assert.equal(data, resData);
},
headers: {
set: function(k, v) {
if (typeof type === 'string') {
assert.equal(v, type);
} else {
assert.ok((v === type[0] || v === type[1]));
}
}
}
},
stream: {},
headers: {}
}, path);
}
it('response number', function() {
handler(1, 'text/html', '^/response/number$');
});
it('response boolean', function() {
handler('false', 'text/html', '^/response/boolean$');
});
it('response string', function() {
handler('hello', 'text/html', '^/response/string$');
});
it('response object2json', function() {
handler(JSON.stringify({a: 1}), ['text/html', 'text/json'], '^/response/object2json$');
});
it('response stream', function() {
var r = http.request('get', 'http://127.0.0.1:5210/response/stream');
assert.equal(r.read().toString(), fs.open('./index.js').readAll().toString());
});
it('response redirect', function() {
var r = http.request('get', 'http://127.0.0.1:5210/response/redirect');
assert.equal(r.read().toString(), 1);
});
it('response status and content-type', function() {
var r = http.request('get', 'http://127.0.0.1:5210/response/status');
assert.equal(r.headers.first('Content-Type'), 'text/xml');
assert.equal(r.status, 500);
});
});
describe('fibx cookies', function() {
it('set signed cookie', function() {
var value = 'Rube';
var value_hex =md5(md5('bRube').digest().hex() + app.key).digest().hex();
var r = http.get('http://127.0.0.1:5210/cookies/signed?c=get',{"cookie":"b=" + value + "; path=/; b.sig=" + value_hex + "; path=/;"});
assert.equal(value, r.read().toString());
});
it('get signed cookie', function() {
var r = http.get('http://127.0.0.1:5210/cookies/signed?c=set');
assert.equal(r.cookies[0].value, r.read().toString());
});
it('set nosigned cookie', function() {
var value = 'Rube';
var r = http.get('http://127.0.0.1:5210/cookies/nosigned?c=get',{"cookie":"a=" + value + "; path=/;"});
assert.equal(value, r.read().toString());
});
it('get nosigned cookie', function() {
var r = http.get('http://127.0.0.1:5210/cookies/nosigned?c=set');
assert.equal(r.cookies[0].value, r.read().toString());
});
});
});
test.run();<file_sep>##app
###app.use( [route,] handler)
**设置一个中间件**
中间件可以分 2 种形式
* 全局的中间件,每次请求都会经过
* 根据路由来执行的中间件 ('尽量量避免使用')
全局的中间件
```javascript
app.use(function(next){
console.log('global middleware');
next && next();
});
```
根据路由的中间件,路由规则为一个 **正则表达式**
```javascript
app.use('^/go(/.*)$', function(next){
console.log('route middleware');
next && next();
});
```
**next的问题**
next 可以控制下一个中间件的执行
一直在考虑是不是要加这个 next 上去, 最终决定还是加上去, 这样的话可以比较 easy 地控制流程.
在不确定后面有没有中间件的情况下请使用 ``` next && next() ```,来确保不报错,但fibjs 报错也不会退出,这一点不错.
**中间件传参**
中间件之间传参有两种形式
* 利用 next 传参
* 利用上下文传参
利用next
```javascript
app.use(function(next){
console.log('a');
next && next('b');
});
app.use(function(b, next){
console.log(b);
next && next();
});
```
利用上下文
```javascript
app.use(function(next){
this.state = {};
this.state.happy = 'yes';
next && next();
});
app.use(function(next){
console.log(this.state.happy) //yes
next && next();
});
```
###app.listen( port )
可以监听 port 启动一个服务器
###app.key =
给你的服务器加个特殊的标识
cookie 加密就有用到这个 key,默认是 fibx
##request
**this.method**
请求的方式
**this.query**
带在 url 上的参数
```
127.0.0.1:12306/post/Rube/?a=1&b=2;
this.query // {a : 1 , b : 2}
```
**this.queryString**
请求的那串参数 ```?a=1&b=2```
**this.path**
请求的路径 ```/post/Rube```
**this.form**
请求的表单参数
**this.header**
请求头一个 json 对象
**this.get( key )**
获取请求头的一个字段
```this.get( 'X-Powered-By' )```
**this.protocol**
请求使用的协议
**this.ip**
请求的来源 ip, 不怎么可靠哦
**this.port**
请求过来的端口
**this.host**
请求的主机
**this.length**
请求 body 长度
**this.type**
请求的类型 = this.get( 'Content-Type' )
**this.is( reg )**
是否为所对应的请求类型
reg 是一个正在表达式
```javascript
this.is(/text\/javascript/);
this.is(/text\/.*/)
```
##response
**this.redirect( url )**
跳转到相应的 url
**this.body =**
设置相应返回的内容,fibx 会自动将对象转换为 json 串,也能够对 stream 进行 输出
**this.type =**
设置相应的 Content-Type,默认为 text/html
**this.status =**
设置相应的返回状态
**this.set( obj )**
**this.set( filed, value )**
设置返回头
```javascript
this.set( 'lastModified', new Date() );
this.set({
'lastModified': new Date(),
'Content-Type': 'text/javascript'
});
```
**this.remove( filed )**
移除返回头字段
```this.remove( 'Content-Type' )```
##cookies
**this.cookies.set( name, value [, option])**
设置 cookies 的值 ,默认是加密且 httpOnly = true 的
```javascript
option = {
signed: boolean, //默认为 true
httpOnly: boolean, //默认为 true
path: String,
domain: String,
expires: Date //默认为当前时间
}
```
```javascript
this.cookies.set( 'rube', 'hello',{
path:'/',
domain: '.taobao.com',
expires: new Date(Date.now() + 3600)
});
```
**this.cookies.get( name [, option] )**
获取 cookies 值,默认获取的是通过加密的 cookie
要获取非加密的值 ```option.signed = false```
<file_sep>#FibX
***
**fibx** 是 fibjs 的一个 web 框架,提供了中间件安装以及请求接受和应答的功能
##Installation
```
npm install fibjs-fibx
```
##Example
```javascript
var app = require('fibjs-fibx')();
var http = require('http');
app.use(function(next) {
this.cookies.set('hello', 'me');
this.state = {};
this.state.number = 1;
this.state['back'] = 'fibx';
next();
this.body = 'hello world! ------' + this.state['back'] + 'number:' + this.state.number;
});
//设置1000个中间件
for (var i = 0; i < 1000; i++) {
app.use(function(next) {
this.state.number++;
next && next();
});
}
//app.use 的用法详见 Api Doc
app.use('^/go(/.*)$', http.fileHandler('./'));
app.use('^/a(/.*)$', function(next) {
this.state.number = -1;
next();
});
app.use('^/a(/.*)$', function() {
this.state.number = -2;
});
app.use('^(/.*)$', function() {
this.state.number++;
});
app.listen(10023);
```
##Api
[API Doc](https://github.com/fibx/fibx/blob/master/doc/api.md)
##Other
如果你想写一个 fibjs 模块上传到 npm,必须像本项目在目录下放如 fibjs-install.js 的文件.
```javascript
var fs = require('fs');
var os = require('os');
var process = require('process');
var modulesPath = '../../.modules';
var moduleName = JSON.parse(fs.readFile('package.json').toString()).name;
var isExists = fs.exists(modulesPath);
!isExists && fs.mkdir(modulesPath);
switch (os.type) {
case 'Darwin':
process.exec('ln -s ../node_modules/' + moduleName + ' ' + modulesPath + '/' + moduleName);
break;
default :
process.exec('ln -s ../node_modules/' + moduleName + ' ' + modulesPath + '/' + moduleName);
}
```
然后在 package.json 中添加
```json
"scripts": {
"install": "fibjs fibjs-install.js",
}
```
##Next
more 中间件 :
* session
* static
* body parse
* and more ...<file_sep>/**
* @module
* @author Rube
* @date 15/12/16
* @desc
*/
var response = {
set: function(field, value) {
if (typeof field == 'string') {
this.r.response.headers.set(field, value);
} else {
for (var f in field) {
this.r.response.headers.set(f, field[f]);
}
}
},
remove: function(field) {
this.r.response.headers.remove(field);
},
redirect: function(url) {
this.status = 302;
this.r.response.redirect(url);
}
};
exports.init = function() {
Object.assign(this, response);
};
exports.run = function(r) {
if (this.body === false) {
this.body = 'false'
}
this.body = this.body || '';
this.status = this.status || 200;
this.type = this.type || '';
var res = r.response;
res.status = this.status;
if (this.type) {
this.set('Content-Type', this.type);
} else {
this.set('Content-Type', 'text/html');
}
if (this.body.toString().toLowerCase().indexOf('stream') != -1 ||
this.body.toString().toLowerCase().indexOf('file') != -1) {
res.body = this.body;
return;
}
switch (typeof this.body) {
case 'number':
this.body += '';
break;
case 'object':
this.body = JSON.stringify(this.body);
this.set('Content-Type', 'text/json');
break;
case 'boolean':
this.body += '';
break;
}
res.write(this.body);
};<file_sep>/**
* @author Rube
* @date 15/12/16
*/
var request = {
get: function(field) {
return this.r.headers[field];
},
is: function(type) {
var reg = new RegExp(type);
return reg.test(this.get('Content-Type'));
}
};
exports.init = function() {
Object.assign(this, request);
};
exports.run = function(r) {
this.request = {};
this.method = r.method;
this.keepAlive = r.keepAlive;
this.query = {};
this.form = {};
this.queryString = r.queryString;
this.path = r.address;
this.header = r.headers;
this.protocol = r.protocol;
this.ip = r.stream.remoteAddress;
this.port = r.stream.remotePort;
this.length = r.length;
this.type = this.get('Content-Type');
this.host = this.get('Host');
for (var key in r.query) {
if (!(typeof r.query[key] == 'function')) {
this.query[key] = r.query[key];
}
}
for (var key in r.form) {
if (!(typeof r.form[key] == 'function')) {
this.form[key] = r.form[key];
}
}
}; | 30497ca5ded06b1144e30051c71123e1130176b7 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | treejames/fibx | 143b1077d59ee2907d6c58a456d4787403944bad | 499195cce777a50fe3b82a89d399add803963d77 |
refs/heads/master | <file_sep>// Package parser transforms a raw request into map[string]interface{} or []interface{}.
// Loosely based on github.com/martini-contrib/binding.
package parser
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"strings"
"github.com/go-martini/martini"
)
type (
// Request parameters object parsed from Form, JSON, etc.
// We wrap interface{} in struct, because if we map bare interface{}, it
// matches random object ;)
Params struct {
Ptr interface{}
}
// Error handler function.
ErrorHandler func(error) martini.Handler
// Parser options.
Options struct {
// Error handler middleware.
// Defaults to parser.DefaultErrorHandler.
ErrorHandler ErrorHandler
// Maximum amount of memory to use when parsing a multipart form.
// Defaults to parser.DefaultMaxMemory.
MaxMemory int64
// Limit allowed requests to given content types.
// Requests with content type not present in list will be ignored.
ContentType []string
}
)
const (
// DefaultMaxMemory is default parser memory limit (10 MB).
DefaultMaxMemory = int64(1024 * 1024 * 10)
)
// DefaultErrorHandler simply writes 422 status and error message text.
func DefaultErrorHandler(e error) martini.Handler {
const (
contentType = "text/plain; charset=utf-8"
errorCode = 422
)
return func(resp http.ResponseWriter) {
resp.Header().Set("Content-Type", contentType)
resp.WriteHeader(errorCode)
resp.Write([]byte(fmt.Sprintf("%d %s", errorCode, e.Error())))
}
}
// Parse wraps up the functionality of the Form, MultipartForm and Json
// middleware according to the Content-Type and verb of the request.
// A Content-Type is required for POST and PUT requests.
// Parse invokes the options.ErrorHandler callback to bail out if error
// occurred.
func Parse(options ...Options) martini.Handler {
return doParse(prepareOptions(options))
}
// Form is middleware to deserialize form-urlencoded data from the request.
// It gets data from the form-urlencoded body, if present, or from the
// query string. It uses the http.Request.ParseForm() method to perform
// deserialization. Repeated form keys are stored into the map[string]interface{}
// as []string values, other keys are stored as single string values.
func Form(options ...Options) martini.Handler {
return doForm(prepareOptions(options))
}
// MultipartForm works much like Form, except it can parse multipart forms
// and handle file uploads. In addition to string and []string values,
// resulting map may contain multipart.FileHeader values.
func MultipartForm(options ...Options) martini.Handler {
return doMultipartForm(prepareOptions(options))
}
// Json is middleware to deserialize a JSON payload from the request into
// the map[string]interface{} for objects or []interface{} for arrays.
func Json(options ...Options) martini.Handler {
return doJson(prepareOptions(options))
}
func doParse(opts Options) martini.Handler {
return func(context martini.Context, req *http.Request) {
contentType := req.Header.Get("Content-Type")
if req.Method == "POST" || req.Method == "PUT" || contentType != "" {
if strings.Contains(contentType, "form-urlencoded") {
context.Invoke(doForm(opts))
} else if strings.Contains(contentType, "multipart/form-data") {
context.Invoke(doMultipartForm(opts))
} else if strings.Contains(contentType, "json") {
context.Invoke(doJson(opts))
} else {
if contentType == "" {
context.Invoke(opts.ErrorHandler(errors.New("empty Content-Type")))
} else {
context.Invoke(opts.ErrorHandler(errors.New("unsupported Content-Type")))
}
}
} else {
context.Invoke(doForm(opts))
}
}
}
func doForm(opts Options) martini.Handler {
return makeHandler(opts, func(context martini.Context, req *http.Request) {
if err := req.ParseForm(); err != nil {
context.Invoke(opts.ErrorHandler(err))
} else {
mapForm(context, req.Form, nil)
}
})
}
func doMultipartForm(opts Options) martini.Handler {
return makeHandler(opts, func(context martini.Context, req *http.Request) {
// This if check is necessary due to https://github.com/martini-contrib/csrf/issues/6
if req.MultipartForm == nil {
// Workaround for multipart forms returning nil instead of an error
// when content is not multipart; see https://code.google.com/p/go/issues/detail?id=6334
if reader, err := req.MultipartReader(); err != nil {
context.Invoke(opts.ErrorHandler(err))
} else {
form, err := reader.ReadForm(opts.MaxMemory)
if err != nil {
context.Invoke(opts.ErrorHandler(err))
}
req.MultipartForm = form
}
}
if req.MultipartForm != nil {
mapForm(context, req.MultipartForm.Value, &req.MultipartForm.File)
}
})
}
func doJson(opts Options) martini.Handler {
return makeHandler(opts, func(context martini.Context, req *http.Request) {
if req.Body != nil {
defer req.Body.Close()
var params interface{}
err := json.NewDecoder(req.Body).Decode(¶ms)
if err != nil && err != io.EOF {
context.Invoke(opts.ErrorHandler(err))
} else {
context.Map(Params{params})
}
}
})
}
func makeHandler(opts Options, next func(martini.Context, *http.Request)) martini.Handler {
return func(context martini.Context, req *http.Request) {
if checkContentType(opts, req) {
next(context, req)
} else {
context.Invoke(opts.ErrorHandler(errors.New("unsupported Content-Type")))
}
}
}
func checkContentType(opts Options, req *http.Request) bool {
if len(opts.ContentType) == 0 {
return true
} else {
ct := req.Header.Get("Content-Type")
for _, c := range opts.ContentType {
if c == ct {
return true
}
}
return false
}
}
func mapForm(context martini.Context, form map[string][]string,
formfile *map[string][]*multipart.FileHeader) {
params := make(map[string]interface{})
for key, value := range form {
if len(value) == 1 {
params[key] = value[0]
} else if len(value) > 1 {
params[key] = value
}
}
if formfile != nil {
for key, value := range *formfile {
if len(value) == 1 {
params[key] = value[0]
} else if len(value) > 1 {
params[key] = value
}
}
}
context.Map(Params{params})
}
func prepareOptions(options []Options) (out Options) {
if len(options) > 0 {
out = options[0]
}
if out.ErrorHandler == nil {
out.ErrorHandler = DefaultErrorHandler
}
if out.MaxMemory == 0 {
out.MaxMemory = DefaultMaxMemory
}
return
}
| a49cf50481874f102e5d6efd57203c6a03d0e722 | [
"Go"
]
| 1 | Go | gavv/martini-parser | bb4bd01e45aabdc3e851108c47b4de1a2b6425c1 | 978a61129947483140d5bf96c781584c69d54cdd |
refs/heads/master | <repo_name>mikiasgv/realtimeApp<file_sep>/app/Http/Controllers/LikeController.php
<?php
namespace App\Http\Controllers;
use App\Model\Like;
use Illuminate\Http\Request;
use App\Model\Reply;
use App\Events\NewLike;
class LikeController extends Controller
{
public function likeIt(Reply $reply) {
$reply->likes()->create([
'user_id' => auth()->id()
]);
event(new NewLike($reply->id, 1));
}
public function unLikeIt(Reply $reply) {
$reply->likes()->where('user_id', auth()->id())->first()->delete();
event(new NewLike($reply->id, 0));
}
}
<file_sep>/resources/js/Helpers/User.js
import Token from "./Token";
import AppStorage from './AppStorage';
class User {
login(data) {
axios.post('/api/auth/login', data)
.then(response => {
this.validateAndStore(response);
})
.catch(err => console.log(err));
}
validateAndStore(response) {
const accessToken = response.data.access_token;
const userName = response.data.user;
if(Token.isValid(accessToken)) {
AppStorage.store(userName, accessToken);
window.location = '/forum';
}
}
hasToken() {
const storedToken = AppStorage.getToken();
if(storedToken) {
return Token.isValid(storedToken);
}
return false;
}
loggedIn() {
return this.hasToken();
}
logout() {
if(this.loggedIn()) {
AppStorage.clear();
window.location = '/forum';
}
}
name() {
if(this.loggedIn()) {
AppStorage.getUser();
}
}
id() {
if(this.loggedIn()) {
const payload = Token.payload(AppStorage.getToken());
return payload.sub;
}
}
own(id) {
return this.id() == id;
}
isAdmin(id) {
return this.id() == 14;
}
}
export default User = new User();
<file_sep>/resources/js/Helpers/Exception.js
class Exception {
handle(exception) {
this.isExpierd(exception.response.error);
}
isExpierd(error) {
if(error == 'Token is not valid') {
URLSearchParams.logout()
}
}
}
export default Exception = new Exception();
| 0c764dd6707fb9e7d175ab4e53fa94f27d967d9f | [
"JavaScript",
"PHP"
]
| 3 | PHP | mikiasgv/realtimeApp | 77fc5747c13c04a6e24d2dffbc95d0311d5d8c05 | 838011961522a3b862f601ab4c0d80c884f23283 |
refs/heads/master | <repo_name>NiNJAxFREEZu/Organizator-nut<file_sep>/funkcje.h
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define DATA_FILE "database.dat"
#define ID_FILE "id.dat"
#define CAT_FILE "category.dat"
#define CATID_FILE "catid.dat"
#define MAX_SIZE 51
#define AND &&
#define OR ||
#define WORK printf("YES");
/*
REMINDER
<NAME> CZYSZCZONY NA POCZ¥TKU WYWO£YWANYCH FUNKCJI DO WPROWADZANIA, WYSZUKIWANIA DANYCH
DLA PORZ¥DKU I USYSTEMATYZOWANIA
*/
struct record{ //Deklaracja podstawowej struktury bazy
int ID;
char title[MAX_SIZE];
char autor[MAX_SIZE];
char signature[MAX_SIZE];
};
struct category{ //Deklaracja struktury sygnatur i ich numeracji
char fullname[MAX_SIZE];
char shortname[MAX_SIZE];
int counter;
};
char charConvert(int n) //Funkcja rzutuj¹ca int na char
{
switch(n)
{
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
default:
printf("%i", n);
}
}
void resetID() //Procedura resetuj¹ca numer ID w pliku ID.cdata
{
FILE *ID = fopen(ID_FILE , "w");
fprintf(ID, "0");
fclose(ID);
}
int getID() //Funkcja pobieraj¹ca numer ID z pliku, zwracaj¹ca wartoœæ obecnego ID
{
auto int n;
FILE *ID = fopen(ID_FILE , "r"); //Pobieranie ID
fscanf(ID, "%i", &n);
fclose(ID);
return n;
}
void addID() //Funkcja inkrementuj¹ca ID o 1
{
auto int n;
FILE *ID = fopen(ID_FILE , "r"); //Pobieranie ID
fscanf(ID, "%i", &n);
fclose(ID);
ID = fopen(ID_FILE, "w"); //Nadpisanie ID
fprintf(ID, "%i", ++n);
fclose(ID);
}
void resetCAT() //Funkcja resetuj¹ca numer CATID w pliku catid.cdata
{
FILE *ID = fopen(CATID_FILE , "w");
fprintf(ID, "0");
fclose(ID);
}
int getCAT() //Funkcja zwracaj¹ca iloœæ kategorii w pliku catid.cdata
{
auto int n;
FILE *ID = fopen(CATID_FILE , "r"); //Pobieranie ID
fscanf(ID, "%i", &n);
fclose(ID);
return n;
}
void addCAT() //Funkcja inkrementuj¹ca CATID o 1
{
auto int n;
FILE *ID = fopen(CATID_FILE , "r"); //Pobieranie ID
fscanf(ID, "%i", &n);
fclose(ID);
ID = fopen(CATID_FILE, "w"); //Nadpisanie ID
fprintf(ID, "%i", ++n);
fclose(ID);
}
void createBaseFile() //Procedura tworz¹ca nowy plik z nag³ówkami kolumn USUWA WSZYTKIE DANE
{
FILE *output = fopen(DATA_FILE, "w");
fprintf(output, "ID TYTUL AUTOR SYGNATURA\n");
fclose(output);
}
void createCatFile() //Procedura tworz¹ca nowy plik z kategoriami
{
FILE *output = fopen(CAT_FILE, "w");
fprintf(output, "NAZWA SKROT ILOSC\n");
fclose(output);
}
void structPrint(struct record data) //Proceruda wyœwietlaj¹ca strukturê "rekord" w KONSOLI bez numeru ID
{
printf("TYTUL: %s\n AUTOR: %s\n SYGNATURA: %s\n\n", data.title, data.autor, data.signature);
}
void categoryPrint(struct category data) //Procedura wyœwietlaj¹ca srtukturê kategorii w KONSOLI bez licznika kategorii
{
printf("NAZWA KATEGORII: %s\n SKROT: %s\n\n", data.fullname, data.shortname);
}
void debugPrint(struct record data) //Procedura która s³u¿y mi do debugowania silnika wyszukiwania
{
printf("%i %s %s %s\n", data.ID, data.title, data.autor, data.signature);
}
void fstructPrint(struct record data) //Proceduta zapisuj¹ca nowy rekord na koñcu pliku z numerem ID
{
addID();
FILE *output = fopen(DATA_FILE , "r+");
fseek(output, 0, SEEK_END); //Przesuniêcie kursora na koniec pliku
fprintf(output, "%i %s %s %s\n", getID(), data.title, data.autor, data.signature);
fclose(output);
}
void fcategoryPrint(struct category data) //Procedura zapisuj¹ca now¹ kategoriê na koñcu pliku z domyœlnym licznikiem = 0
{
FILE *output = fopen(CAT_FILE , "r+");
fseek(output, 0, SEEK_END); //Przesuniêcie kursora na koniec pliku
fprintf(output, "%s %s %i\n", data.fullname, data.shortname, data.counter);
fclose(output);
}
void loadCategories(struct category array[], const int arraySize) //Wczytuje do schowka (tablica struktur) dane z pliku
{
FILE *input = fopen(CAT_FILE, "r");
auto char dump;
auto int i, j;
for(i = 0; i < arraySize; ++i) //Czyszczenie tablic znakowych z artefaktów
for(j = 0; j < MAX_SIZE; ++j)
{
array[i].fullname[j] = '\0';
array[i].shortname[j] = '\0';
}
while(dump != '\n') //Pominiêcie nag³ówków kategorii
fscanf(input, "%c", &dump);
for(i = 0; i < arraySize; ++i) //Wype³nianie tablic
{
for(j = 0 ;; ++j) //Pobieranie pe³nej nazwy kategorii
{
fscanf(input, "%c", &array[i].fullname[j]);
if(array[i].fullname[j] == ' ')
{
array[i].fullname[j] = '\0';
break;
}
}
for(j = 0 ;; ++j) //Pobieranie skrótowej nazwy kategorii
{
fscanf(input, "%c", &array[i].shortname[j]);
if(array[i].shortname[j] == ' ')
{
array[i].shortname[j] = '\0';
break;
}
}
fscanf(input, "%i\n", &array[i].counter); //Pobranie liczby rekordów danej kategorii
}
fclose(input);
}
void displayCategories() //Procedura wyœwietlaj¹ca wszystkie kategorie w konsoli
{
auto const int arraySize = getCAT();
auto struct category array[arraySize];
loadCategories(array, arraySize); //Wczytanie kategorii
auto int i;
for(i = 0; i < arraySize; ++i)
{
categoryPrint(array[i]);
printf("\n");
}
}
void updateCategories(char data[]) //Procedura aktualizuj¹ca plik z kategoriami po dodaniu nowego rekordu
{
auto int i, j;
auto const int arraySize = getCAT();
auto struct category array[arraySize];
loadCategories(array, arraySize);
for(i = 0; i < arraySize; ++i) //Sprawdzanie, czy ³añcuchy shcatname i shortname s¹ równe
{
for(j = 0;;)
{
if(data[j] == '\0' OR array[i].shortname[j] == '\0')
break;
else if(data[j] == array[i].shortname[j])
{
++j;
continue;
}
else break;
}
if(data[j] == '\0' AND array[i].shortname[j] == '\0')
{
++array[i].counter;
break;
}
}
createCatFile(); //Nadpisywanie pliku
for(i = 0; i < arraySize; ++i)
fcategoryPrint(array[i]);
}
void getSignature(char shcatname[]) //Funkcja zwracaj¹ca sygnaturê do nowego rekordu lub tablicê pust¹ w przypadku nie znalezienia podanej kategorii
{
auto int i, j;
auto const int arraySize = getCAT();
auto struct category array[arraySize];
auto char signatureID[] = "00000";
loadCategories(array, arraySize); //Wczytanie kategorii
for(i = 0; i < arraySize; ++i) //Sprawdzanie, czy ³añcuchy shcatname i shortname s¹ równe
{
for(j = 0;;)
{
if(shcatname[j] == '\0' OR array[i].shortname[j] == '\0')
break;
else if(shcatname[j] == array[i].shortname[j])
{
++j;
continue;
}
else break;
}
if(shcatname[j] == '\0' AND array[i].shortname[j] == '\0') //Konkatenacja shcatname i sygnatury z³o¿onej z cyfr DZIA£A !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{
signatureID[0] = charConvert( (int) ++array[i].counter / 10000 ); //Inkrementacja ma na celu poprawn¹ numeracje zapisu w bazie
signatureID[1] = charConvert( (int) array[i].counter / 1000 % 10);
signatureID[2] = charConvert( (int) array[i].counter / 100 % 100);
signatureID[3] = charConvert( (int) array[i].counter / 10 % 1000);
signatureID[4] = charConvert( (int) array[i].counter % 10 );
shcatname[j++] = signatureID[0];
shcatname[j++] = signatureID[1];
shcatname[j++] = signatureID[2]; //Pêtle s¹ dla s³abych...
shcatname[j++] = signatureID[3];
shcatname[j++] = signatureID[4];
return;
}
}
shcatname[0] = '\0'; //Je¿eli pêtla nie zosta³a wczeœniej zakoñczona (nie znaleziono kategorii) funkcja "zwraca" znak pusty
}
void loadDatabase(struct record array[], const int arraySize) //Wczytuje do schowka (tablica struktur) dane z pliku
{
FILE *input = fopen(DATA_FILE, "r");
auto char dump;
auto int i, j;
for(i = 0; i < arraySize; ++i) //Czyszczenie tablic znakowych z artefaktów
for(j = 0; j < MAX_SIZE; ++j)
{
array[i].title[j] = '\0';
array[i].autor[j] = '\0';
array[i].signature[j] = '\0';
}
while(dump != '\n') //Pominiêcie nag³ówków bazy
fscanf(input, "%c", &dump);
for(i = 0; i < arraySize; ++i) //Wype³nianie tablic
{
fscanf(input, "%i%c", &array[i].ID, &dump); //Pobranie numeru ID
for(j = 0 ;; ++j) //Pobieranie tytu³u
{
fscanf(input, "%c", &array[i].title[j]);
if(array[i].title[j] == ' ')
{
array[i].title[j] = '\0';
break;
}
}
for(j = 0 ;; ++j) //Pobieranie autora
{
fscanf(input, "%c", &array[i].autor[j]);
if(array[i].autor[j] == ' ')
{
array[i].autor[j] = '\0';
break;
}
}
for(j = 0 ;; ++j) //Pobieranie sygnatury
{
fscanf(input, "%c", &array[i].signature[j]);
if(array[i].signature[j] == '\n')
{
array[i].signature[j] = '\0';
break;
}
}
}
fclose(input);
}
void displayAll() //Wyœwietlanie wszystkich rekordów w bazie SORTUJ WED£UG TYTU£ÓW
{
getchar();
system("cls");
const int arraySize = getID();
auto struct record array[arraySize];
loadDatabase(array, arraySize); //Wczytanie bazy
auto int i;
for(i = 0; i < arraySize; ++i)
{
structPrint(array[i]);
printf("\n");
}
system("pause");
system("cls");
}
void addEntry() //Procedura pobieraj¹ca nowy wpis i przekazuj¹ca go dalej do funkcji fstructPrint
{
getchar();
auto char select;
auto int i;
auto struct record temp;
auto char shcatname[MAX_SIZE], copy[MAX_SIZE]; //Deklaracja tablicy COPY u³atwi mi póŸniej zwiêkszenie liczby rekordów z dan¹ kategori¹ w pliku.
for(i = 0; i < MAX_SIZE; ++i) //Czyszczenie tablic z artefaktów
{
temp.signature[i] = '\0';
temp.autor[i] = '\0';
temp.signature[i] = '\0';
shcatname[i] = '\0';
copy[i] = '\0';
}
system("cls");
printf("Podaj skrot kategorii dla nowego rekordu\nWielkosc liter ma znaczenie!!\n\n");
displayCategories();
for(i = 0;; ++i) //Wprowadzenie krótkiej nazwy kategorii
{
shcatname[i] = getchar();
if(shcatname[i] == ' ')
shcatname[i] = '_';
else if(shcatname[i] == '\n')
break;
}
shcatname[i] = '\0';
for(i = 0;; ++i) //Kopia tablicy shcatname
{
copy[i] = shcatname[i];
if(copy[i] == '\0')
break;
}
getSignature(shcatname);
if(shcatname[0] == '\0')
{
system("cls");
printf("Nie ma takiej kategorii!\n");
return;
}
system("cls");
printf("Podaj tytul utworu: "); //Wczytywanie tytu³u
for(i = 0;; ++i)
{
temp.title[i] = getchar();
if(temp.title[i] == ' ')
temp.title[i] = '_';
else if(temp.title[i] == '\n')
break;
}
temp.title[i] = '\0';
printf("Podaj autora utworu: "); //Wczytywanie autora
for(i = 0;; ++i)
{
temp.autor[i] = getchar();
if(temp.autor[i] == ' ')
temp.autor[i] = '_';
else if(temp.autor[i] == '\n')
break;
}
temp.autor[i] = '\0';
system("cls");
for(i = 0; shcatname[i] != '\0'; ++i) //Wczytanie sygnatury
temp.signature[i] = shcatname[i];
printf("Czy chcesz dodac rekord o tych danych? T/N\n\n");
structPrint(temp);
for(;;)
{
scanf("%c", &select);
if(select == 'T' OR select == 't')
{
system("cls");
fstructPrint(temp);
updateCategories(copy);
printf("Dodano nowy rekord!\n");
getchar();
break;
}
else if(select == 'N' OR select == 'n')
{
system("cls");
printf("Anulowano operacje\n");
getchar();
break;
}
}
}
void addCategory() //Procedura dodaj¹ca now¹ kategoriê
{
getchar();
auto char select;
auto int i;
auto struct category temp;
temp.counter = 0; //Ustawienie pocz¹tkowej wartoœci do sygnatury
for(i = 0; i < MAX_SIZE; ++i) //Czyszczenie tablic z artefaktów
{
temp.fullname[i] = '\0';
temp.shortname[i] = '\0';
}
system("cls");
printf("Podaj nazwe kategorii: "); //Wczytywanie nazwy nowej kategorii
for(i = 0;; ++i)
{
temp.fullname[i] = getchar();
if(temp.fullname[i] == ' ')
temp.fullname[i] = '_';
else if(temp.fullname[i] == '\n')
break;
}
temp.fullname[i] = '\0';
printf("Podaj skrocona nazwe kategorii: "); //Wczytywanie nazwy nowej kategorii
for(i = 0;; ++i)
{
temp.shortname[i] = getchar();
if(temp.shortname[i] == ' ')
temp.shortname[i] = '_';
else if(temp.shortname[i] == '\n')
break;
}
temp.shortname[i] = '\0';
system("cls");
printf("Czy chcesz dodac kategorie o tych danych? T/N\n\n"); //Zatwierdzanie wyboru
categoryPrint(temp);
for(;;)
{
scanf("%c", &select);
if(select == 'T' OR select == 't')
{
system("cls");
fcategoryPrint(temp);
printf("Dodano nowa kategorie!\n");
getchar();
addCAT();
break;
}
else if(select == 'N' OR select == 'n')
{
system("cls");
printf("Anulowano operacje\n");
getchar();
break;
}
}
}
void sortByTitle(struct record array[], const int arraySize) //Funckja sortuj¹ca tablice rekordów alfabetycznie wzglêdem tytu³ów
{
}
void searchRecords(int searchNumber) //Funkcja wyszukuj¹ca w rekordach dane pole, gdzie parametr, liczba ca³kowita, okreœla numer pola z koleji (1 - tytu³, 2 - autor, 3 - sygnatura)
{
system("cls");
getchar();
auto char string[51]; //Tablica znakowa do przechowania ³añcucha do póŸniejszego wyszukania w bazie
auto int i;
for(i = 0; i < 51; ++i) //Czyszczenie tablicy z artefaktów
string[i] == '\0';
printf("Podaj tekst do wyszukania:\t"); //Wprowadzenie z klawiatury tekstu
for(i = 0;; ++i)
{
string[i] = getchar();
if(string[i] == ' ')
string[i] = '_';
else if(string[i] == '\n')
{
string[i] = '\0';
break;
}
}
const int arraySize = getID();
struct record array[arraySize]; //Deklaracja tablicy struktur na dane z pliku
loadDatabase(array, arraySize); //Wczytanie danych z pliku do RAMu
bool whatToPrint[arraySize]; //Tablica przechowywujaca dane "które rekordy wyœwietliæ, które zosta³y znalezione".
for(i = 0; i < arraySize; ++i) //Zerowanie tablicy logicznej
{
whatToPrint[i] = false;
}
int recordCounter = 0; //Zmienna przechowywuj¹ca iloœæ znalezionych rekordów
int j; //Pomocnicza zmienna do poruszania siê po tablicach
switch(searchNumber) //Wed³ug czego szukamy?
{
case 1: //Tuty³
{
for(i = 0; i < arraySize; ++i)
{
for(j = 0;;)
{
if( array[i].title[j] == string[j] OR array[i].title[j] + 32 == string[j] OR array[i].title[j] == string[j] - 32 OR ( array[i].title[j] == '\0' AND string[j] == '\0' )) //Sprawdzanie równoœci znaków w tablicach uwzglêdniaj¹c równoœæ ma³ych liter z wielkimi
{
if(string[j + 1] == '\0'); //Sprawdzanie, czy nastêpny element "string" nie jest pustym znakiem kiedy poprzednie elementy 2 tablic s¹ równe
{
whatToPrint[i] = true;
++recordCounter;
break;
}
}
else break;
}
}
break;
}
case 2: //Autor
{
for(i = 0; i < arraySize; ++i)
{
for(j = 0;;)
{
if( array[i].autor[j] == string[j] OR array[i].autor[j] + 32 == string[j] OR array[i].autor[j] == string[j] - 32 OR ( array[i].autor[j] == '\0' AND string[j] == '\0' )) //Sprawdzanie równoœci znaków w tablicach uwzglêdniaj¹c równoœæ ma³ych liter z wielkimi
{
if(string[j + 1] == '\0'); //Sprawdzanie, czy nastêpny element "string" nie jest pustym znakiem kiedy poprzednie elementy 2 tablic s¹ równe
{
whatToPrint[i] = true;
++recordCounter;
break;
}
}
else break;
}
}
break;
}
case 3: //Sygnatura
{
for(i = 0; i < arraySize; ++i)
{
for(j = 0;;)
{
if( array[i].signature[j] == string[j] OR array[i].signature[j] + 32 == string[j] OR array[i].signature[j] == string[j] - 32 OR ( array[i].signature[j] == '\0' AND string[j] == '\0' )) //Sprawdzanie równoœci znaków w tablicach uwzglêdniaj¹c równoœæ ma³ych liter z wielkimi
{
if(string[j + 1] == '\0'); //Sprawdzanie, czy nastêpny element "string" nie jest pustym znakiem kiedy poprzednie elementy 2 tablic s¹ równe
{
whatToPrint[i] = true;
++recordCounter;
break;
}
}
else break;
}
}
break;
}
default:
{
break;
}
}
system("cls");
printf("Znalezionych rekordow -> %i\n\n", recordCounter);
for(i = 0; i < arraySize; ++i) //Wypisywanie znalezionych rekordów na ekran
{
if(whatToPrint[i])
structPrint(array[i]);
}
system("pause");
system("cls");
return;
}
void searchMenu() //Podmenu z opcjami wyszukiwania
{
auto char menuDigit = '\0'; //Zmienna znakowa do obsługi podmenu
system("cls");
printf("Opcje wyszukiwania\n\n");
for(;;) //Pêtla menu
{
printf("1. Wyswietl wszystkie rekordy\n"); //Odnonśik do procedury "displayAll"
printf(" 2. Wyszkukaj tytul\n");
printf(" 3. Wyszukaj autora\n");
printf(" 4. Wyszukaj sygnature\n");
printf(" 5. Wyswietl rekordy z kategorii... NIE ZAPROGRAMOWANE\n");
printf(" 6. Cofnij...\n"); //Powrót do menu g³ównego
menuDigit = getchar(); //Wybór opcji z menu i przypisanie jej do zmiennej
switch(menuDigit)
{
case '1':
{
displayAll();
return;
}
case '2':
{
searchRecords(1);
return;
}
case '3':
{
searchRecords(2);
return;
}
case '4':
{
searchRecords(3);
return;
}
case '6':
{
getchar(); //Pozbycie się entera
return;
}
default:
{
system("cls");
printf("Podano zly numer!\n");
break;
}
}
}
}
<file_sep>/main.c
#include <stdio.h>
#include "funkcje.h"
void checkFiles(bool display) //Procedura sprawdzająca czy pliki są poprawne
{
printf("Nacisnij enter..."); //Obejście tego cholernego znaku nowego wiersza na przy czwórce...
getchar();
system("cls");
auto fpos_t length;
auto char check;
FILE *output = fopen(DATA_FILE, "r"); //Sprawdzanie pliku bazy danych
fseek(output, 0, SEEK_END); //Sprawdzanie rozmiaru pliku
fgetpos(output, &length);
fseek(output, 0, SEEK_SET);
if(length <= 2 OR output == NULL) //Sprawdzanie poprawności pliku
{
createBaseFile();
printf("Baza danych jest pusta/uszkodzona, utworzono nowy plik\n");
}
fclose(output);
output = fopen(CAT_FILE, "r"); //Sprawdzenie pliku z kategoriami
if(output == NULL)
{
printf("Plik z kategoriami jest pusty, utworzono nowy plik\n");
createCatFile();
}
fclose(output);
output = fopen(ID_FILE, "r"); //Sprawdzanie pliku z numerem ID
if(output == NULL)
{
printf("Nie znaleziono pliku indetyfikacyjnego, plik ten zostal utworzony\n");
resetID();
}
fclose(output);
output = fopen(CATID_FILE, "r"); //Sprawdzanie pliku z numerem ID kategorii
if(output == NULL)
{
printf("Nie znaleziono pliku z licznikiem kategorii, plik ten zostal utworzony\n");
resetCAT();
}
fclose(output);
if(display == true) //Wyświetlanie ilości rekordów/kategorii
{
if(getID() == 1) //Gramatyka, ehhhhh....
printf("%i REKORD\n", getID());
else if(getID() <= 4 AND getID() > 1)
printf("%i REKORDY\n", getID());
else printf("%i REKORDOW\n", getID());
if(getCAT() == 1) //Gramatyka, ehhhhh....
printf("%i KATEGORIA\n", getCAT());
else if(getCAT() <= 4 AND getCAT() > 1)
printf("%i KATEGORIE\n", getCAT());
else printf("%i KATEGORII\n", getCAT());
}
}
int main(void)
{
bool display = false; //Zmienna logiczna dzięki której nie wyświetlam ilości rekordów i kategorii na początku programu
checkFiles(display);
display = true; //Przy następnum wywołaniu checkFile wyświetlimy ilość rekordów/kategorii
char menuDigit = '\0', select; //Deklaracja zmiennych znakowych do obsługi menu głównego
printf("Witaj w programie\n\n");
for(;;) //Główne menu
{
printf("Wybierz numer operacji:\n\n"); //Nagłówek
printf("1. Dodaj nowy rekord...\n"); //Dodawanie nowego rekordu
printf(" 2. Dodaj nowa kategorie...\n");
printf(" 3. Wyszukiwanie rekordow...\n");
printf(" 4. Wyswietl ilosc rekordow/kategorii\n"); //Sprawdzanie spoójnosci pliku i ilosci rekordów oraz kategorii
printf(" 5. Reset bazy danych\n"); //Utworzenie trzech plików od nowa
printf(" 6. Wyjscie\n"); //Zgaduje, że chodzi o wyjście z programu
menuDigit = getchar();
switch(menuDigit)
{
case '1':
{
if( getCAT() == 0 ) //Sprawdzanie, czy istnieje zadeklarowana kategoria rekordu
{
getchar();
system("cls");
printf("Przed dodaniem pierwszego rekordu, musisz dodac kategorie!\n");
break;
}
addEntry();
break;
}
case '2':
{
addCategory();
break;
}
case '3':
{
getchar();
searchMenu();
break;
}
case '4':
{
checkFiles(display);
break;
}
case '5':
{
getchar(); //Kolejny taktyczny dodge tego cholernego \n
system("cls");
printf("Jestes pewien? Usunie to wszystkie dane w bazie i zapisane kategorie T/N ");
for(;;)
{
select = getchar();
if(select == 'T' OR select == 't')
{
createBaseFile();
createCatFile();
resetID();
resetCAT();
system("cls");
printf("Baza danych zostala zresetowana\n");
break;
}
else if(select == 'N' OR select == 'n')
{
system("cls");
printf("Anulowano reset\n");
break;
}
}
getchar(); //Tak, zgadłeś...
continue;
}
case '6':
{
return 0;
break;
}
default:
{
system("cls");
printf("Podano zly numer\n");
break;
}
}
}
return 0;
}
<file_sep>/README.md
# Organizator-nut
Pierwsza aplikacja, którą napisałem w czasach wczesnego liceum.
Śmieci, ale za to ile nostalgii.
| 24a4f6f04f4ed147546fc5d716ad12e286c31d98 | [
"Markdown",
"C"
]
| 3 | C | NiNJAxFREEZu/Organizator-nut | d6f9fb7815e8e8074cfaacc2cc0cd680afbe0aa3 | 756b0431babe40760c7c832507d950f84e75aeae |
refs/heads/master | <file_sep>//
// GameScene.swift
// dbz
//
// Created by BM on 2019-03-14.
// Copyright © 2019 BM. All rights reserved.
//
import SpriteKit
import GameKit
let wallCategory: UInt32 = 0x00000001 << 0
let playerCategory: UInt32 = 0x00000001 << 1
let enemyCategory: UInt32 = 0x00000001 << 2
let attackGCategory: UInt32 = 0x00000001 << 3
let attackVCategory: UInt32 = 0x00000001 << 4
class GameScene: SKScene,SKPhysicsContactDelegate {
var background:SKSpriteNode! //Sprite
let screenSize: CGRect = UIScreen.main.bounds
let velocityMultiplier: CGFloat = 0.12
let fightMusic = SKAudioNode(fileNamed: "/music/fight.mp3")
//self.fightMusic.run(SKAction.stop())
var isTimeUp = false;
var gokuWon = false;
//AI ?
var vegetaUp = true;
var AIBlock = false;
var attackVegetaDelay = 1.0
var vegetaCanAttack = true;
var RandomNumber = 1
var gokuSprite:SKSpriteNode! //0
//idle
var gokuIdleAtlas: SKTextureAtlas! //Spritesheet //1
var gokuIdleFrames: [SKTexture]! //frames //2
var gokuIdle: SKAction! //Animation //3
//move
var gokuMoveAtlas: SKTextureAtlas! //Spritesheet //1
var gokuMoveFrames: [SKTexture]! //frames //2
var gokuMove: SKAction! //Animation //3
//attack
var gokuAttackAtlas: SKTextureAtlas! //Spritesheet //1
var gokuAttackFrames: [SKTexture]! //frames //2
var gokuAttack: SKAction! //Animation //3
//attack2
var gokuAttack2Atlas: SKTextureAtlas! //Spritesheet //1
var gokuAttack2Frames: [SKTexture]! //frames //2
var gokuAttack2: SKAction! //Animation //3
var vegetaSprite:SKSpriteNode! //0
//idle
var vegetaIdleAtlas: SKTextureAtlas! //Spritesheet //1
var vegetaIdleFrames: [SKTexture]! //frames //2
var vegetaIdle: SKAction! //Animation //3
//move
var vegetaMoveAtlas: SKTextureAtlas! //Spritesheet //1
var vegetaMoveFrames: [SKTexture]! //frames //2
var vegetaMove: SKAction! //Animation //3
//attack
var vegetaAttackAtlas: SKTextureAtlas! //Spritesheet //1
var vegetaAttackFrames: [SKTexture]! //frames //2
var vegetaAttack: SKAction! //Animation //3
//block
var vegetaBlockAtlas: SKTextureAtlas! //Spritesheet //1
var vegetaBlockFrames: [SKTexture]! //frames //2
var vegetaBlock: SKAction! //Animation //3
//SOUNDS
let attackSfx = SKAudioNode(fileNamed: "/sounds/attack.wav")
let attack2Sfx = SKAudioNode(fileNamed: "/sounds/attack1.wav")
let clashSfx = SKAudioNode(fileNamed: "/sounds/clash.wav")
let gokuAh = SKAudioNode(fileNamed: "/sounds/gokuAh.mp3")
let gokuDies = SKAudioNode(fileNamed: "/sounds/gokuDies.mp3")
let gokuPunch = SKAudioNode(fileNamed: "/sounds/punch.mp3")
let vegetaAh = SKAudioNode(fileNamed: "/sounds/vegetaAh.mp3")
let vegetaDamaged = SKAudioNode(fileNamed: "/sounds/vegetaDamaged.mp3")
let vegetaDies = SKAudioNode(fileNamed: "/sounds/vegetaDies.mp3")
//UI
let moveJoystick = 🕹(withDiameter: 80)
var redButton:SKSpriteNode!
var blueButton:SKSpriteNode!
var backButton:SKSpriteNode!
var vegetaAvatar:SKSpriteNode!
var gokuAvatar:SKSpriteNode!
var gokuBar:SKSpriteNode! //0
var vegetaBar:SKSpriteNode! //0
var redBar1:SKSpriteNode! //0
var redBar2:SKSpriteNode! //0
var gHealth = 140.0
var vHealth = 140.0
let myLabel = SKLabelNode(fontNamed:"Helvetica")
var timer = Timer()
var timerAI = Timer()
var timerDelay = Timer()
var time = 180
var moveBall:SKAction!
var moveBall2:SKAction!
var gDiedAudio = false;
var vDiedAudio = false;
var gameOver = false;
var coolDownAttack1 = 1.0
var coolDownAttack1passed = 0.0
var boolAttack1 = false;
override init(size: CGSize) {
super.init(size: size)
addChild(fightMusic)
attackSfx.autoplayLooped = false;
attack2Sfx.autoplayLooped = false;
clashSfx.autoplayLooped = false;
gokuAh.autoplayLooped = false;
gokuDies.autoplayLooped = false;
gokuPunch.autoplayLooped = false;
vegetaAh.autoplayLooped = false;
vegetaDamaged.autoplayLooped = false;
vegetaDies.autoplayLooped = false;
moveBall = SKAction.moveBy(x: screenSize.width, y: 0, duration: 1.6)
moveBall2 = SKAction.moveBy(x: -screenSize.width, y: 0, duration: 1.8)
myLabel.text = "\(time)"
myLabel.fontSize = 36
myLabel.position = CGPoint(x: screenSize.width/2, y:screenSize.height * 0.88)
myLabel.fontColor = UIColor.yellow
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fire(timer:)), userInfo: nil, repeats: true)
let timerAI = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(VegetaRandomAI(timer:)), userInfo: nil, repeats: true) //change behavior of AI every 2 seconds
let timerDelay = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(VegetaDeleayAttack(timer:)), userInfo: nil, repeats: true) //reset vegeta delay so he can attack again
background = SKSpriteNode(imageNamed: "background")
background.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
background.size = CGSize(width: screenSize.width, height: screenSize.height)
moveJoystick.position = CGPoint(x: screenSize.width * 0.15, y:screenSize.height * 0.2)
moveJoystick.zPosition = 4
gokuBar = SKSpriteNode(color: SKColor.green, size: CGSize(width: gHealth, height: 30))
gokuBar.position = CGPoint(x: screenSize.width * 0.12, y:screenSize.height * 0.90)
gokuBar.anchorPoint = CGPoint(x: 0, y: 0.5)
redBar1 = SKSpriteNode(color: SKColor.red, size: CGSize(width: gHealth, height: 32))
redBar1.position = CGPoint(x: screenSize.width * 0.12 - 1, y:screenSize.height * 0.90)
redBar1.anchorPoint = CGPoint(x: 0, y: 0.5)
vegetaBar = SKSpriteNode(color: SKColor.green, size: CGSize(width: vHealth, height: 30))
vegetaBar.position = CGPoint(x: screenSize.width * 0.85, y:screenSize.height * 0.90)
vegetaBar.anchorPoint = CGPoint(x: 1.0, y: 0.5)
redBar2 = SKSpriteNode(color: SKColor.red, size: CGSize(width: vHealth, height: 32))
redBar2.position = CGPoint(x: screenSize.width * 0.85 + 1, y:screenSize.height * 0.90)
redBar2.anchorPoint = CGPoint(x: 1.0, y: 0.5)
blueButton = SKSpriteNode(imageNamed: "blueButton")
blueButton.position = CGPoint(x: screenSize.width * 0.85, y:screenSize.height * 0.2)
blueButton.size = CGSize(width: screenSize.width * 0.06, height: screenSize.height * 0.08)
blueButton.name = "blue"
redButton = SKSpriteNode(imageNamed: "redButton")
redButton.position = CGPoint(x: screenSize.width * 0.75, y:screenSize.height * 0.15)
redButton.size = CGSize(width: screenSize.width * 0.06, height: screenSize.height * 0.08)
redButton.name = "red"
backButton = SKSpriteNode(imageNamed: "smallerback")
backButton.setScale(0.35)
backButton.position = CGPoint(x: screenSize.width * 0.98, y:screenSize.height * 0.95)
backButton.name = "back"
vegetaAvatar = SKSpriteNode(imageNamed: "vegetaPortrait")
vegetaAvatar.setScale(0.15)
vegetaAvatar.position = CGPoint(x: screenSize.width * 0.93, y:screenSize.height * 0.90)
gokuAvatar = SKSpriteNode(imageNamed: "gokuPortrait")
gokuAvatar.setScale(0.15)
gokuAvatar.position = CGPoint(x: screenSize.width * 0.07, y:screenSize.height * 0.90)
//GOKU
//idle
gokuIdleAtlas = SKTextureAtlas(named: "idle2.1") //0
gokuIdleFrames = [] //2. Initialize empty texture array
let gokuIdleImages = gokuIdleAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//move
gokuMoveAtlas = SKTextureAtlas(named: "move.1") //0
gokuMoveFrames = [] //2. Initialize empty texture array
let gokuMoveImages = gokuMoveAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//attack
gokuAttackAtlas = SKTextureAtlas(named: "attack.1") //0
gokuAttackFrames = [] //2. Initialize empty texture array
let gokuAttackImages = gokuAttackAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//attack2
gokuAttack2Atlas = SKTextureAtlas(named: "attack2.1") //0
gokuAttack2Frames = [] //2. Initialize empty texture array
let gokuAttack2Images = gokuAttack2Atlas.textureNames.count-1
//4. for loop
//idle
for i in 0...gokuIdleImages {
let texture = "idle_\(i)" //grab each frame in atlas
gokuIdleFrames.append(gokuIdleAtlas.textureNamed(texture))
}//add frame to texture array
gokuIdle = SKAction.animate(with: gokuIdleFrames, timePerFrame: 0.3, resize: true, restore: true)
//move
for i in 0...gokuMoveImages {
let texture = "move_\(i)" //grab each frame in atlas
gokuMoveFrames.append(gokuMoveAtlas.textureNamed(texture))
}
gokuMove = SKAction.animate(with: gokuMoveFrames, timePerFrame: 0.3, resize: true, restore: true)
//attack
for i in 0...gokuAttackImages {
let texture = "attack_\(i)" //grab each frame in atlas
gokuAttackFrames.append(gokuAttackAtlas.textureNamed(texture))
}
gokuAttack = SKAction.animate(with: gokuAttackFrames, timePerFrame: 0.2, resize: true, restore: true)
//attack2
for i in 0...gokuAttack2Images {
let texture = "attack2_\(i)" //grab each frame in atlas
gokuAttack2Frames.append(gokuAttack2Atlas.textureNamed(texture))
}
gokuAttack2 = SKAction.animate(with: gokuAttack2Frames, timePerFrame: 0.2, resize: true, restore: true)
gokuSprite = SKSpriteNode(texture: SKTexture(imageNamed: "idle_0.png"))
gokuSprite.setScale(0.6)
gokuSprite.position = CGPoint(x: screenSize.width * 0.2, y:screenSize.height/2)
gokuSprite?.physicsBody = SKPhysicsBody(rectangleOf: (gokuSprite?.frame.size)!)
gokuSprite?.physicsBody?.affectedByGravity = false;
gokuSprite?.physicsBody?.allowsRotation = false;
gokuSprite?.physicsBody?.mass = 2.0
gokuSprite?.physicsBody?.categoryBitMask = playerCategory
gokuSprite?.physicsBody?.contactTestBitMask = 00011111
gokuSprite?.physicsBody?.collisionBitMask = 00000101
//VEGETA
//idle
vegetaIdleAtlas = SKTextureAtlas(named: "vIddle.1") //0
vegetaIdleFrames = [] //2. Initialize empty texture array
let vegetaIdleImages = vegetaIdleAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//move
vegetaMoveAtlas = SKTextureAtlas(named: "vMove.1") //0
vegetaMoveFrames = [] //2. Initialize empty texture array
let vegetaMoveImages = vegetaMoveAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//attack
vegetaAttackAtlas = SKTextureAtlas(named: "vAttack.1") //0
vegetaAttackFrames = [] //2. Initialize empty texture array
let vegetaAttackImages = vegetaAttackAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//block
vegetaBlockAtlas = SKTextureAtlas(named: "vBlock.1") //0
vegetaBlockFrames = [] //2. Initialize empty texture array
let vegetaBlockImages = vegetaBlockAtlas.textureNames.count-1//3. count how many frames inside atlas (if this does not work do
//4. for loop
//idle
for i in 0...vegetaIdleImages {
let texture = "vidle_\(i)" //grab each frame in atlas
vegetaIdleFrames.append(vegetaIdleAtlas.textureNamed(texture))
}//add frame to texture array
vegetaIdle = SKAction.animate(with: vegetaIdleFrames, timePerFrame: 0.3, resize: true, restore: true)
//move
for i in 0...vegetaMoveImages {
let texture = "vMove_\(i)" //grab each frame in atlas
vegetaMoveFrames.append(vegetaMoveAtlas.textureNamed(texture))
}
vegetaMove = SKAction.animate(with: vegetaMoveFrames, timePerFrame: 0.3, resize: true, restore: true)
//attack
for i in 0...vegetaAttackImages {
let texture = "vAttack_\(i)" //grab each frame in atlas
vegetaAttackFrames.append(vegetaAttackAtlas.textureNamed(texture))
}
vegetaAttack = SKAction.animate(with: vegetaAttackFrames, timePerFrame: 0.3, resize: true, restore: true)
//block
for i in 0...vegetaBlockImages {
let texture = "vBlock_\(i)" //grab each frame in atlas
vegetaBlockFrames.append(vegetaBlockAtlas.textureNamed(texture))
}
vegetaBlock = SKAction.animate(with: vegetaBlockFrames, timePerFrame: 0.3, resize: true, restore: true)
vegetaSprite = SKSpriteNode(texture: SKTexture(imageNamed: "vidle_0.png"))
vegetaSprite.setScale(0.6)
vegetaSprite.position = CGPoint(x: screenSize.width * 0.8, y:screenSize.height/2)
vegetaSprite?.physicsBody = SKPhysicsBody(rectangleOf: (vegetaSprite?.frame.size)!)
vegetaSprite?.physicsBody?.affectedByGravity = false;
vegetaSprite?.physicsBody?.allowsRotation = false;
vegetaSprite?.physicsBody?.mass = 2.0
vegetaSprite?.physicsBody?.categoryBitMask = enemyCategory
vegetaSprite?.physicsBody?.contactTestBitMask = 00011111
vegetaSprite?.physicsBody?.collisionBitMask = 00001111;
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
self.physicsBody = borderBody
self.physicsBody?.categoryBitMask = wallCategory
self.physicsBody?.contactTestBitMask = playerCategory
self.physicsBody?.contactTestBitMask = enemyCategory
self.physicsWorld.contactDelegate = self
addChild(background)
addChild(gokuSprite)
addChild(vegetaSprite)
addChild(myLabel)
addChild(vegetaAvatar)
addChild(gokuAvatar)
addChild(moveJoystick)
addChild(blueButton)
addChild(redButton)
// addChild(backButton) added to debug AI
//add it back if you want to make vegeta attack with abutton that's on the top right corner
addChild(redBar1)
addChild(gokuBar)
addChild(redBar2)
addChild(vegetaBar)
addChild(attackSfx)
addChild(attack2Sfx)
addChild(clashSfx)
addChild(gokuAh)
addChild(gokuDies)
addChild(gokuPunch)
addChild(vegetaAh)
addChild(vegetaDamaged)
addChild(vegetaDies)
gokuSprite.run(SKAction.repeatForever(gokuIdle)) // this way the animation will keep playing for ever
// vegetaSprite.run(SKAction.repeatForever(vegetaIdle)) // this way the animation will keep playing for ever
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func didBegin(_ contact: SKPhysicsContact) {
if contact.bodyA.categoryBitMask == playerCategory && contact.bodyB.categoryBitMask == wallCategory {
print("player first")
}
if contact.bodyA.categoryBitMask == wallCategory && contact.bodyB.categoryBitMask == playerCategory {
}
if contact.bodyA.categoryBitMask == wallCategory && contact.bodyB.categoryBitMask == enemyCategory {
vegetaUp = !vegetaUp;
}
if contact.bodyA.categoryBitMask == wallCategory && contact.bodyB.categoryBitMask == attackGCategory {
contact.bodyB.node?.removeFromParent()
print("attackG removed")
}
if contact.bodyA.categoryBitMask == wallCategory && contact.bodyB.categoryBitMask == attackVCategory {
contact.bodyB.node?.removeFromParent()
print("attackV removed")
}
if contact.bodyA.categoryBitMask == enemyCategory && contact.bodyB.categoryBitMask == attackGCategory {
contact.bodyB.node?.removeFromParent()
if AIBlock {
vHealth -= 5
self.clashSfx.run(SKAction.play());
}
else {
vHealth -= 15
self.vegetaDamaged.run(SKAction.play());
}
}
if contact.bodyA.categoryBitMask == playerCategory && contact.bodyB.categoryBitMask == enemyCategory {
let moveBack = SKAction.moveBy(x: -10, y: 0, duration: 0.3)
gokuSprite.run(moveBack)
print("player collided enemy")
}
if contact.bodyA.categoryBitMask == playerCategory && contact.bodyB.categoryBitMask == attackVCategory {
contact.bodyB.node?.removeFromParent()
self.gokuAh.run(SKAction.play());
gHealth -= 35
print("player collided enemyBall")
}
if contact.bodyA.categoryBitMask == attackGCategory && contact.bodyB.categoryBitMask == attackVCategory {
print("attacks collided")
//if ki blasts collide they will destroy each other
contact.bodyA.node?.removeFromParent()
contact.bodyB.node?.removeFromParent()
self.clashSfx.run(SKAction.play());
}
}
@objc func fire(timer: Timer)
{
// print("I got called")
time -= 1
myLabel.text = String(time)
}
@objc func VegetaRandomAI(timer: Timer)
{
// print("I got called")
RandomNumber = Int(arc4random_uniform(UInt32(100)))
//RandomNumber = Int.random(in: 0 ..< 100) this worked at home, not at school
}
@objc func VegetaDeleayAttack(timer: Timer)
{
// print("I got called")
vegetaCanAttack = true;
}
@objc func VegetaRandomAI(){
RandomNumber = Int(arc4random_uniform(UInt32(100)))
//RandomNumber = Int.random(in: 0 ..< 100)
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
myLabel.text = "\(time)"
//AI?
if(vegetaSprite.position.x != screenSize.width * 0.8){
let moveOrigin = SKAction.moveTo(x: screenSize.width * 0.8, duration: 0.3)
vegetaSprite.run(moveOrigin)
}
moveJoystick.on(.move) { [unowned self] joystick in
guard let gokuSprite = self.gokuSprite else {
return
}
let pVelocity = joystick.velocity;
let speed = CGFloat(0.09)
self.gokuSprite.run(SKAction.repeat(self.gokuMove, count: 1))
gokuSprite.position = CGPoint(x: gokuSprite.position.x + (pVelocity.x * speed), y: gokuSprite.position.y + (pVelocity.y * speed))
// print(gokuSprite.position)
}
if time <= 0{
isTimeUp = true
myLabel.removeFromParent()
}
if(isTimeUp){
if gokuWon && !gameOver{
self.perform(#selector(self.changeScene), with: nil, afterDelay: 2.0)
gameOver = true
}
else if !gokuWon && !gameOver{
self.perform(#selector(self.changeScene2), with: nil, afterDelay: 2.0)
gameOver = true
}
}
self.gokuBar.size = self.CGSizeMake(CGFloat(self.gHealth), 30.0)
self.vegetaBar.size = self.CGSizeMake(CGFloat(self.vHealth), 30.0)
if(gHealth > vHealth){
gokuWon = true
}
else {
gokuWon = false
}
if(gHealth < 0){
gHealth = 0
}
if(vHealth < 0){
vHealth = 0
}
if vHealth == 0 {
if !vDiedAudio {
vegetaDies.run(SKAction.play());
vDiedAudio = true
isTimeUp = true
moveJoystick.removeFromParent()
redButton.removeFromParent()
blueButton.removeFromParent()
vegetaSprite.removeFromParent()
myLabel.removeFromParent()
}
}
if(gHealth == 0){
if !gDiedAudio {
gokuDies.run(SKAction.play());
gDiedAudio = true
isTimeUp = true
moveJoystick.removeFromParent()
redButton.removeFromParent()
blueButton.removeFromParent()
gokuSprite.removeFromParent()
vegetaSprite.removeFromParent()
myLabel.removeFromParent()
}
}
//AIVE
switch RandomNumber { // 0 to 99
case 0..<5:
self.AIBlock = true
self.vegetaSprite.run(SKAction.repeatForever(self.vegetaBlock), completion: {
print(self.RandomNumber)
})
case 5..<20:
self.AIBlock = false
self.vegetaSprite.run(SKAction.repeatForever(self.vegetaIdle))
case 20..<30:
self.AIBlock = false
if(self.vegetaUp){
self.vegetaSprite.run(SKAction.repeat(self.vegetaMove, count: 1))
vegetaSprite.position = CGPoint(x: vegetaSprite.position.x, y: vegetaSprite.position.y + 5)
}
else{
self.vegetaSprite.run(SKAction.repeat(self.vegetaMove, count: 1))
vegetaSprite.position = CGPoint(x: vegetaSprite.position.x, y: vegetaSprite.position.y - 5)
}
case 30..<70:
if self.vegetaCanAttack {
self.vegetaCanAttack = false
self.AIBlock = false
var vegetaBall:SKSpriteNode!
vegetaBall = SKSpriteNode(imageNamed: "ballVegeta")
vegetaBall.setScale(0.5)
vegetaBall.position = CGPoint(x: self.vegetaSprite.position.x - 30, y:self.vegetaSprite.position.y)
vegetaBall.run(self.moveBall2)
vegetaBall?.physicsBody = SKPhysicsBody(rectangleOf: (vegetaBall?.frame.size)!)
vegetaBall?.physicsBody?.affectedByGravity = false;
vegetaBall?.physicsBody?.allowsRotation = false;
vegetaBall?.physicsBody?.mass = 2.0
vegetaBall?.physicsBody?.categoryBitMask = attackVCategory
vegetaBall?.physicsBody?.contactTestBitMask = 00011111
vegetaBall?.physicsBody?.collisionBitMask = 00001011;
// vegetaBall.name = "ballV"
self.addChild(vegetaBall)
self.vegetaSprite.run(self.vegetaAttack, completion: {
print(self.RandomNumber)
self.vegetaCanAttack = false
})
}
else {
self.vegetaCanAttack = false
self.VegetaRandomAI()
}
case 70..<85:
self.AIBlock = false
self.vegetaSprite.run(SKAction.repeatForever(vegetaIdle))
case 85..<100:
self.AIBlock = true
self.vegetaSprite.run(SKAction.repeatForever(self.vegetaBlock), completion: {
print(self.RandomNumber)
})
default:
self.AIBlock = false
print(self.RandomNumber)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
enumerateChildNodes(withName: "//*", using: { ( node, stop) in
if node.name == "red" {
if node.contains(t.location(in:self))// do whatever here
{
self.gokuPunch.run(SKAction.play());
//self.gokuSprite.run(SKAction.repeat(self.gokuAttack, count: 1))
self.gokuSprite.run(self.gokuAttack, completion: {
self.boolAttack1 = true;
//self.AIBlock = !self.AIBlock
if self.gokuSprite.position.x < self.vegetaSprite.position.x - 38 &&
self.gokuSprite.position.x > 400 &&
self.gokuSprite.position.y < self.vegetaSprite.position.y + 80 &&
self.gokuSprite.position.y > self.vegetaSprite.position.y - 80
{
if self.AIBlock {
self.vHealth -= 5;
self.attack2Sfx.run(SKAction.play());
}
else{
self.vHealth -= 20;
self.vegetaDamaged.run(SKAction.play());
}
}
//("\(ship.position.x)")
/* print("goku x " + "\(self.gokuSprite.position.x)")
print("goku y " + "\(self.gokuSprite.position.y)")
print("veg x " + "\(self.vegetaSprite.position.x - 42)")
print("veg y + 80 " + "\(self.vegetaSprite.position.y + 80)")
print("veg y - 80 " + "\(self.vegetaSprite.position.y - 80)")*/
//print("RED Button Pressed")
})
}
}
if node.name == "blue" { //BLAST
if node.contains(t.location(in:self))// do whatever here
{
//self.vegetaSprite.position = CGPoint(x: self.vegetaSprite.position.x, y: self.vegetaSprite.position.y - 10)
self.attackSfx.run(SKAction.play());
var gokuBall:SKSpriteNode!
gokuBall = SKSpriteNode(imageNamed: "ballGoku")
gokuBall.setScale(0.5)
gokuBall.position = CGPoint(x: self.gokuSprite.position.x + 25, y:self.gokuSprite.position.y)
gokuBall.run(self.moveBall)
gokuBall?.physicsBody = SKPhysicsBody(rectangleOf: (gokuBall?.frame.size)!)
gokuBall?.physicsBody?.affectedByGravity = false;
gokuBall?.physicsBody?.allowsRotation = false;
gokuBall?.physicsBody?.mass = 2.0
gokuBall?.physicsBody?.categoryBitMask = attackGCategory
gokuBall.physicsBody?.contactTestBitMask = attackVCategory | enemyCategory | wallCategory
gokuBall.physicsBody?.collisionBitMask = attackVCategory | enemyCategory | wallCategory
//gokuBall?.physicsBody?.contactTestBitMask = 00011111
//gokuBall?.physicsBody?.collisionBitMask = 00010001;
self.addChild(gokuBall)
self.gokuSprite.run(self.gokuAttack2, completion: {
})
}
}
//back button only active for debuging AI
if node.name == "back" {
if node.contains(t.location(in:self))// do whatever here
{
self.attackSfx.run(SKAction.play());
self.vegetaSprite.run(SKAction.repeat(self.vegetaAttack, count: 1))
var vegetaBall:SKSpriteNode!
vegetaBall = SKSpriteNode(imageNamed: "ballVegeta")
vegetaBall.zPosition = 3
vegetaBall.setScale(0.5)
vegetaBall.position = CGPoint(x: self.vegetaSprite.position.x - 30, y:self.vegetaSprite.position.y)
vegetaBall.run(self.moveBall2)
vegetaBall?.physicsBody = SKPhysicsBody(rectangleOf: (vegetaBall?.frame.size)!)
vegetaBall?.physicsBody?.affectedByGravity = false;
vegetaBall?.physicsBody?.allowsRotation = false;
vegetaBall?.physicsBody?.mass = 2.0
vegetaBall?.physicsBody?.categoryBitMask = attackVCategory
vegetaBall?.physicsBody?.contactTestBitMask = 00011111
vegetaBall?.physicsBody?.collisionBitMask = 00001001;
self.addChild(vegetaBall)
// print("BACK Button Pressed")
}
}
})
}
}
@objc func changeScene(){ //change scene after 2 sec
fightMusic.run(SKAction.stop())
let reveal = SKTransition.reveal(with: .up, duration: 0.6)
let newScene = GameOverScene(size:self.size)
self.view?.presentScene(newScene, transition: reveal)
}
@objc func changeScene2(){ //change scene after 2 sec
fightMusic.run(SKAction.stop())
let reveal = SKTransition.reveal(with: .up, duration: 0.6)
let newScene = GameOverScene2(size:self.size)
self.view?.presentScene(newScene, transition: reveal)
}
func CGSizeMake(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
}
<file_sep>//
// DialoguesScene.swift
// dbz
//
// Created by BM on 2019-03-14.
// Copyright © 2019 BM. All rights reserved.
//
import Foundation
import SpriteKit
class DialoguesScene: SKScene {
//TODO: - Add label here to indicate game over
//TODO: - Add button to restart to menu
let dialogueMusic = SKAudioNode(fileNamed: "/music/dialogue.mp3")
let dialogue2File = SKAudioNode(fileNamed: "/sounds/vegetaDialog.mp3")
let dialogue3File = SKAudioNode(fileNamed: "/sounds/gokuDialog.mp3")
let dialogue4File = SKAudioNode(fileNamed: "/sounds/vegetaDialog2.mp3")
//TODO: - Use this to create a menu scene
var dialogue1:SKSpriteNode! //Sprite
var dialogue2:SKSpriteNode! //Sprite
var dialogue3:SKSpriteNode! //Sprite
var counter:Int!;
let screenSize: CGRect = UIScreen.main.bounds
override init(size: CGSize) {
super.init(size: size)
counter = 1;
dialogue2File.autoplayLooped = false;
dialogue3File.autoplayLooped = false;
dialogue4File.autoplayLooped = false;
dialogue1 = SKSpriteNode(imageNamed: "vegeta1")
dialogue1.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
dialogue1.size = CGSize(width: screenSize.width, height: screenSize.height)
dialogue1.name = "d1"
dialogue2 = SKSpriteNode(imageNamed: "goku1")
dialogue2.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
dialogue2.size = CGSize(width: screenSize.width, height: screenSize.height)
dialogue2.name = "d2"
dialogue3 = SKSpriteNode(imageNamed: "vegeta2")
dialogue3.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
dialogue3.size = CGSize(width: screenSize.width, height: screenSize.height)
dialogue3.name = "d3"
addChild(dialogue1)
addChild(dialogueMusic)
addChild(dialogue2File)
self.dialogue2File.run(SKAction.play());
addChild(dialogue3File)
addChild(dialogue4File)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
enumerateChildNodes(withName: "//*", using: { ( node, stop) in
if node.name == "d1" {
if node.contains(t.location(in:self))// do whatever here
{
self.dialogue2File.run(SKAction.stop());
self.dialogue3File.run(SKAction.play());
print("trying to remove d1")
self.addChild(self.dialogue2)
self.dialogue1.removeFromParent()
}
}
if node.name == "d2" {
if node.contains(t.location(in:self))
{
print("trying to remove d2")
self.addChild(self.dialogue3)
self.dialogue3File.run(SKAction.stop());
self.dialogue4File.run(SKAction.play());
self.dialogue2.removeFromParent()
}
}
if node.name == "d3" {
if node.contains(t.location(in:self))
{
print("trying to remove d3")
self.dialogue4File.run(SKAction.stop());
self.dialogueMusic.run(SKAction.stop());
//self.dialogue2.removeFromParent()
self.perform(#selector(self.changeScene), with: nil, afterDelay: 0.5)
}
}
})
}
}
override func update(_ currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
@objc func changeScene(){ //change scene after 1 sec
let reveal = SKTransition.reveal(with: .up, duration: 0.6)
//let newScene = DialoguesScene(size:self.size)
let newScene = GameScene(size:self.size)
self.view?.presentScene(newScene, transition: reveal)
}
}
<file_sep>//
// GameOverScene.swift
// SuperSpaceMan
//
// Created by Apptist Inc on 2019-03-11.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import SpriteKit
class GameOverScene: SKScene {
var background:SKSpriteNode! //Sprite
let screenSize: CGRect = UIScreen.main.bounds
var startBtn: SKSpriteNode!
var quitBtn: SKSpriteNode!
override init(size: CGSize) {
super.init(size: size)
background = SKSpriteNode(imageNamed: "gokuWon2")
background.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
background.size = CGSize(width: screenSize.width, height: screenSize.height)
background.name = "bg"
startBtn = SKSpriteNode(imageNamed: "Start")
startBtn.position = CGPoint(x: screenSize.width/2, y:screenSize.height * 0.7)
startBtn.name = "startButton"
quitBtn = SKSpriteNode(imageNamed: "Quit")
quitBtn.position = CGPoint(x: screenSize.width/2, y:screenSize.height * 0.5)
quitBtn.name = "quitButton"
addChild(background)
addChild(startBtn)
addChild(quitBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
enumerateChildNodes(withName: "//*", using: { ( node, stop) in
if node.name == "startButton" {
if node.contains(t.location(in:self))// do whatever here
{
print("Button Pressed")
self.perform(#selector(self.changeScene), with: nil, afterDelay: 0.5)
}
}
if node.name == "quitButton" {
if node.contains(t.location(in:self))// do whatever here
{
exit(0)
}
}
})
}
}
@objc func changeScene(){ //change scene after 1 sec
let reveal = SKTransition.reveal(with: .up, duration: 0.6)
//let newScene = DialoguesScene(size:self.size)
let newScene = MenuScene(size:self.size)
self.view?.presentScene(newScene, transition: reveal)
}
}
<file_sep>//
// MenuScene.swift
// SuperSpaceMan
//
// Created by Apptist Inc on 2019-03-11.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import SpriteKit
class MenuScene: SKScene {
//var music:AVAudioPlayer = AVAudioPlayer()
//TODO: - Use this to create a menu scene
var background:SKSpriteNode! //Sprite
var logo:SKSpriteNode!
let screenSize: CGRect = UIScreen.main.bounds
var startBtn: SKSpriteNode!
var quitBtn: SKSpriteNode!
//let startBtn = SKSpriteNode(imageNamed: "button_01")
let selectionSound = SKAudioNode(fileNamed: "/sounds/selectionSfx.mp3")
let backgroundMusic = SKAudioNode(fileNamed: "/music/menu.mp3")
//TODO: - Add a main menu and play button
override init(size: CGSize) {
super.init(size: size)
addChild(backgroundMusic)
/* let musicFile = Bundle.main.path(forResource: "music/menu", ofType: ".mp3")
do{
try music = AVAudioPlayer (contentsOf: URL (fileURLWithPath: musicFile!))
}
catch{
print(error)
}
music.play()*/
//
//other way to play music
selectionSound.autoplayLooped = false;
background = SKSpriteNode(imageNamed: "screenMenu")
background.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2)
background.size = CGSize(width: screenSize.width, height: screenSize.height)
background.name = "bg"
logo = SKSpriteNode(imageNamed: "logo")
logo.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2+80)
logo.size = CGSize(width: screenSize.width/4, height: screenSize.height/4)
startBtn = SKSpriteNode(imageNamed: "Start")
startBtn.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2-35)
startBtn.name = "startButton"
quitBtn = SKSpriteNode(imageNamed: "Quit")
quitBtn.position = CGPoint(x: screenSize.width/2, y:screenSize.height/2-90)
quitBtn.name = "quitButton"
addChild(background)
addChild(selectionSound)
addChild(logo)
addChild(startBtn)
addChild(quitBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
enumerateChildNodes(withName: "//*", using: { ( node, stop) in
if node.name == "startButton" {
if node.contains(t.location(in:self))// do whatever here
{
//self.music.stop()
self.backgroundMusic.run(SKAction.stop())
self.selectionSound.run(SKAction.play());
print("Button Pressed")
self.perform(#selector(self.changeScene), with: nil, afterDelay: 0.5)
}
}
if node.name == "quitButton" {
if node.contains(t.location(in:self))// do whatever here
{
exit(0)
//test area
//let newScene = GameScene(size:self.size)
}
}
})
}
}
@objc func changeScene(){ //change scene after 1 sec
let reveal = SKTransition.reveal(with: .up, duration: 0.6)
let newScene = DialoguesScene(size:self.size)
//let newScene = GameScene(size:self.size)
self.view?.presentScene(newScene, transition: reveal)
}
}
| eb822dee8c1f71eddeecd247cfefc46f9a7a8792 | [
"Swift"
]
| 4 | Swift | BMerlo/DBZiOS | 1b969c96765f42a9d1578900abb7c52e05a5423f | 6a4da817b64e86c7b255ad0229adae552b2ef5e1 |
refs/heads/master | <repo_name>nallerooth/packpub-downloader<file_sep>/main.go
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"packtpub-downloader/tagparser"
"regexp"
)
// packtPubBaseURL Base URL
const packtPubBaseURL string = "https://www.packtpub.com"
// packtPubFreeURL URL to public free books page
const packtPubFreeURL string = "https://www.packtpub.com/packt/offers/free-learning"
var cookies []*http.Cookie
func getFreeBookURL(body string) string {
pattern := regexp.MustCompile(`/freelearning-claim/\d+/\d+`)
return pattern.FindString(body)
}
func fetchHiddenLoginFormInputs(body string) {
}
func loginAndFetchPage() (string, error) {
resp, err := http.PostForm(packtPubFreeURL,
url.Values{
"email": {os.Getenv("PACKTPUB_EMAIL")},
"password": {<PASSWORD>("<PASSWORD>")},
})
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", errors.New("Login did not return HTTP 200. Aborting.")
}
cookies = resp.Cookies()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func claimBook(freeBookURL string) {
u, _ := url.Parse(packtPubBaseURL)
cookieJar, _ := cookiejar.New(nil)
cookieJar.SetCookies(u, cookies)
fmt.Printf("%v\n", cookieJar)
client := &http.Client{
Jar: cookieJar,
}
resp, err := client.Get(packtPubBaseURL + freeBookURL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
fmt.Println(packtPubBaseURL + freeBookURL)
if resp.StatusCode >= 400 {
e := errors.New("Claiming book resulted in status >= HTTP 400 response. Aborting")
fmt.Println("URL: ", packtPubBaseURL+freeBookURL)
fmt.Println("Status: ", resp.Status)
log.Fatal(e)
// TODO: Return e when doing more stuff after claiming
}
}
func getBody() (*bytes.Buffer, error) {
resp, err := http.Get(packtPubBaseURL)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(body)
return buf, nil
}
func main() {
//body, err := loginAndFetchPage()
//if err != nil {
//log.Fatal("Error logging in: ", err)
//}
//freeBookURL := getFreeBookURL(body)
//fmt.Println(freeBookURL)
//fmt.Println(cookies)
//claimBook(freeBookURL)
body, _ := getBody()
tagparser.GetTagsOfType(body, "input")
}
<file_sep>/tagparser/tagparser.go
package tagparser
import (
"bytes"
"fmt"
"golang.org/x/net/html"
// "net/http"
)
func GetTagsOfType(body *bytes.Buffer, tagName string) (map[string]string, error) {
tokenizer := html.NewTokenizer(body)
tags := make(map[string]string)
for {
token := tokenizer.Next()
switch {
case token == html.ErrorToken:
// End of document, we're done.
return tags, nil
case token == html.StartTagToken:
t := tokenizer.Token()
isInput := t.Data == tagName
if isInput {
fmt.Println("Found input")
}
}
// Process list of tags and return a map of name => value
}
}
| 471f596aa8bff1965020e31f719295b6a4ce6e77 | [
"Go"
]
| 2 | Go | nallerooth/packpub-downloader | d62f033c4b5485fe1b3bb3f5e0a147c171953465 | bb61f6de5b31af2406bb4603200337d455e9ac32 |
refs/heads/master | <file_sep>//
// Created by michal on 01.06.18.
//
#ifndef UNTITLED_GAMEOPTIONS_H
#define UNTITLED_GAMEOPTIONS_H
#endif //UNTITLED_GAMEOPTIONS_H
<file_sep>#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int board_size;
unsigned int winSize;
char oponent;
char player_sign;
char getOpposite_sign(char sign) {
if (sign == 'x') {
return 'o';
} else if (sign == 'o') {
return 'x';
}
}
void start_game(vector<vector<char>> &tab_symb) {
cout << "Wybierz swój pionek" << endl << "o lub x" << endl;
cin >> player_sign;
if (player_sign == 'X') player_sign = 'x';
if (player_sign == 'O') player_sign = 'o';
cout << "Wybierz wielkość kwadratowego pola do gry: " << endl;
cin >> board_size;
cout << "Wybierz ilość wygrywających znaków w rzędzie" << endl;
cin >> winSize;
while (winSize > board_size) {
cout << "Wybierz większy rozmiar lub zredukuj liczbę znaków w rzędzie" << endl;
cout << "Wybierz wielkość kwadratowego pola do gry: " << endl;
cin >> board_size;
cout << "Wybierz ilość wygrywających znaków w rzędzie" << endl;
cin >> winSize;
}
tab_symb.resize(board_size, vector<char>(board_size, 'e'));
oponent = getOpposite_sign(player_sign);
}
bool isEmpty(vector<vector<char>> tab) { // return true if empty
bool idx=1;
for (int a = 0; a < board_size; a++) {
for (int b = 0; b < board_size; b++) {
if(tab[a][b]=='e') idx=0;
}
}
return idx;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ZNAJDYWANIE ZWYCIESTWA
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool left_diagonals(char player_sign,vector<vector<char>> &tab_symb) { //SPRAWDZANIE OBECNOSCI ZNAKÓW W LINII PRZEKATNEJ Z LEWEGO GORNEGO ROGU
char opposite_sign = getOpposite_sign(player_sign);
for (int b = 0; b < board_size; b++) { //pętla dla zejscia w dół
int ok_1 = 0; // licznik znaków w rzędzie dla przekątnych poniżej i włącznie z środkową przekątna
int ok_2 = 0; // licznik znaków w rzędzie do wygranej powyżej środkowej przekątnej
for (int a = 0; a + b < board_size; a++) { // pętla chodzenia po kolumnach
///////////////////////////////////////////////////////////////////////////////
//////////// WŁĄCZNIE I POWYZEJ ŚRODKOWEJ PRZEKĄTNEJ ///////////////
if (tab_symb[a][a + b] == player_sign) {
ok_1 += 1;
if (ok_1 == winSize) { //sprawdzamy warunek za każdym nowym rzędem znakow
return true;
}
} else if (tab_symb[a][a + b] == 'e' || opposite_sign)
ok_1 = 0;
/////////////////////////////////////////////////////////////////////////////
///////////// PONIZEJ ŚRODKOWEJ PRZEKĄTNEJ ////////////////////////////
if (tab_symb[b + a][a] == player_sign) {
ok_2 += 1;
if (ok_2 == winSize) {
return true;
}
} else if (tab_symb[b + a][a] == 'e' || opposite_sign)
ok_2 = 0;
}
}
return false;
}
bool right_diagonals(char player_sign, vector<vector<char>> &tab_symb) { //SPRZAWDZANIE PRZEKATNEJ Z GORNEGO PRAWEGO ROGU
char opposite_sign = getOpposite_sign(player_sign);
for (int a = 0; a < board_size - 1; a++) {
int ok_1 = 0;
int ok_2 = 0;
int znak = -1;
for (int b = 0; znak < (board_size - 1 - b - a); b++) {
int x = board_size - 1 - b - a;
if (tab_symb[b][x] == player_sign) {
ok_1 += 1;
if (ok_1 == winSize) return true;
} else if (tab_symb[b][x] == 'e' || opposite_sign) ok_1 = 0;
/////////////////////////////////////////////////////////
int y = board_size - 1 - b;
if (tab_symb[a + b][y] == player_sign) {
ok_2 += 1;
if (ok_2 == winSize) return true;
} else if (tab_symb[a + b][y] == 'e' || opposite_sign) ok_2 = 0;
}
}
return false;
}
bool rows_and_columns(char player_sign,vector<vector<char>> &tab_symb) {
char opposite_sign = getOpposite_sign(player_sign);
for (int a = 0; a < board_size; a++) {
int ok_1 = 0; // dla kazdej kolumny/rzedu liczymy od nowa
int ok_2 = 0;
for (int b = 0; b < board_size; b++) {
//////////////////////////////////////////////////////
///////// KOLUMNY /////////////////////////
if (tab_symb[b][a] == player_sign) {
ok_1 += 1;
if (ok_1 == winSize)
return true;
} else if (tab_symb[b][a] == opposite_sign || 'e') {
ok_1 = 0;
}
//////////////////////////////////////////////////////
///////// RZĘDY //////////////////////////
if (tab_symb[a][b] == player_sign) {
ok_2 += 1;
if (ok_2 == winSize)
return true;
} else if (tab_symb[a][b] == opposite_sign || 'e')
ok_2 = 0;
}
}
return false;
}
bool isVictory(char player_sign, vector<vector<char>> &tab) {
bool left_diag = left_diagonals(player_sign, tab);
bool right_diag = right_diagonals(player_sign, tab);
bool rows_n_columns = rows_and_columns(player_sign, tab);
if ((right_diag || left_diag || rows_n_columns) == true)
return true;
else
return false;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//DZIAŁANIA NA GRZE
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void showBoard(vector<vector<char>>& tab) {
cout << "\033[1;46m \033[0m";
for (int a = 1; a <= board_size; a++) {
cout << "\033[1;46m " << a << "\033[0m";
}
cout << "\033[1;46m \033[0m";
cout << endl;
int znak = 65; // litera A
for (int x = 0; x < board_size; x++) {
cout << "\033[1;46m " << (char) znak << " \033[0m"; // rzutowanie i kolorowanie znaku wiersza
znak++;
for (int y = 0; y < board_size; y++) {
cout << "|";
if (tab[x][y] == 'x')
cout << "\033[1;34m x \033[0m";
if (tab[x][y] == 'o')
cout << "\033[1;33m o \033[0m";
if (tab[x][y] == 'e')
cout << " ";
}
cout << "|" << "\033[1;46m \033[0m" << endl;
}
cout << "\033[1;46m \033[0m";
for (int a = 0; a < board_size; a++) {
cout << "\033[1;46m \033[0m";
}
cout << "\033[1;46m \033[0m";
cout << endl;
}
enum indicator{A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,R,S,T,U,V,W,X,Y,Z};
istream& operator >> (istream& input,indicator& tmp) {
indicator tab[25] = {A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, R, S, T, U, V, W, X, Y, Z};
char znak='A';
input >> znak; // POPRAWIAC WPISYWANE ZNAKI NA WIELKIE
if (strchr("ABCDEFGHIJKLMNOPRSTUVWXYZ", znak))
tmp = tab[znak - 'A'];
return input;
}
void makeStep(char player_sign, vector<vector<char>> &tab_symb) {
char opposite_sign = getOpposite_sign(player_sign);
bool ok = 0;
while (ok != 1) {
cout << "Wybierz pole: " << endl;
indicator x;
int y;
cin >> x;
cin >> y;
y -= 1;
if ((x > board_size - 1) || (y > board_size - 1)) {
showBoard(tab_symb);
cout << "Wybrane pole jest poza polem gry" << endl;
ok = 0;
}
if ((x <= board_size - 1) && (y <= board_size - 1)) {
if (tab_symb[x][y] == 'e') {
tab_symb[x][y] = player_sign;
showBoard(tab_symb);
ok = 1;
} else if (tab_symb[x][y] == opposite_sign) {
showBoard(tab_symb);
cout << "Pole jest zajęte przez przeciwnika" << endl;
ok = 0;
} else {
showBoard(tab_symb);
cout << "Ruch w to miejsce jest niemożliwy" << endl;
ok = 0;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//OCENIANIE SYTUACJI NA PLANSZY
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// skanowanie POWYŻEJ I RAZEM Z ŚRODK. PRZEKĄTNĄ
double getLeftDiagGrade_1(const char& player_sign, vector<vector<char>>& tab_symb) {// skanowanie POWYŻEJ I RAZEM Z ŚRODK. PRZEKĄTNĄ
vector<double> marks;
marks.reserve(board_size);
char opposite_sign = getOpposite_sign(player_sign);
for (int b = 0; b < board_size; b++) {
int ok_1 = 0; // licznik znaków w rzędzie dla przekątnych poniżej i włącznie z środkową przekątna; // licznik znaków w rzędzie do wygranej powyżej środkowej przekątnej
int tmp_1 = 0;
for (int a = 0; a + b < board_size; a++) {
if (tab_symb[a][a + b] == 'e') tmp_1 += 1;
if (tab_symb[a][a + b] == player_sign) ok_1 += 1;
if (tab_symb[a][a + b] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if(isVictory(player_sign,tab_symb)){
marks.push_back(1);
}
if(isVictory(opposite_sign,tab_symb)){
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza
if (ok_1 + tmp_1 >= winSize)
marks.push_back(1 - ((winSize - ok_1) * 0.1));
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize)
marks.push_back(tmp_1 * 0.01);
}
}
if (tmp_1 + ok_1 < winSize)
marks.push_back(0.000000001);
// jesli nie ma miejsca na zwycięstwo daj duża wagę by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo,, tzn z konca tablicy
}
// poniżej środkowej przekątnej
double getLeftDiagGrade_2(const char& player_sign, vector<vector<char>>& tab_symb) {
vector<double> marks;
marks.reserve(board_size);
char opposite_sign = getOpposite_sign(player_sign);
for (int b = 0; b < board_size; b++) { //pętla dla zejscia w dół
int ok_1 = 0; // licznik znaków w rzędzie dla przekątnych poniżej i włącznie z środkową przekątna
int tmp_1 = 0;
for (int a = 0; a + b < board_size; a++) {
if (tab_symb[a + b][a] == 'e') tmp_1 += 1;
if (tab_symb[a + b][a] == player_sign) ok_1 += 1;
if (tab_symb[a + b][a] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if(isVictory(player_sign,tab_symb)){
marks.push_back(1);
}
if(isVictory(opposite_sign,tab_symb)){
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza
if (ok_1 + tmp_1 >= winSize)
marks.push_back(1-((winSize - ok_1) * 0.1));
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize)
marks.push_back(tmp_1 * 0.01);
}
}
if (tmp_1 + ok_1 < winSize)
marks.push_back(0.000000001);
// jesli nie ma miejsca na zwycięstwo daj duża wagę by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo
}
//WŁĄCZNIE I POWYZEJ ŚRODKOWEJ PRZEKĄTNEJ
double getRightDiagGrade_1(char& player_sign,vector<vector<char>>& tab_symb) {
char opposite_sign = getOpposite_sign(player_sign);
vector<double> marks;
marks.reserve(board_size);
for (int a = 0; a < board_size - 1; a++) { //pętla dla zejscia w dół
int ok_1 = 0;
int tmp_1 = 0;
int x = 0;
for (int b = 0; board_size - 1 - b - a > -1; b++) {
x = board_size - 1 - b - a;
if (tab_symb[b][x] == 'e')
tmp_1 += 1;
if (tab_symb[b][x] == player_sign)
ok_1 += 1;
if (tab_symb[b][x] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if(isVictory(player_sign,tab_symb)){
marks.push_back(1);
}
if(isVictory(opposite_sign,tab_symb)){
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza
if (ok_1 + tmp_1 >= winSize)
marks.push_back(1-((winSize - ok_1) * 0.1));
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize)
marks.push_back(tmp_1 * 0.01);
}
}
if (tmp_1 + ok_1 < winSize)
marks.push_back(0.000000001);
// jesli nie ma miejsca na zwycięstwo daj duża wagę by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo
}
// <NAME>
double getRightDiagGrade_2(char& player_sign, vector<vector<char>> tab_symb) {
char opposite_sign = getOpposite_sign(player_sign);
vector<double> marks;
marks.reserve(board_size);
for (int a = 0; a < board_size - 1; a++) { //pętla dla zejscia w dół
int ok_1 = 0;
int tmp_1 = 0;
for (int b = 0; board_size - 1 - b - a > -1; b++) {
int y = board_size - 1 - b;
if (tab_symb[a + b][y] == 'e') tmp_1 += 1;
if (tab_symb[a + b][y] == player_sign) ok_1 += 1;
if (tab_symb[a + b][y] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if(isVictory(player_sign,tab_symb)){
marks.push_back(1);
}
if(isVictory(opposite_sign,tab_symb)){
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza
if (ok_1 + tmp_1 >= winSize)
marks.push_back((winSize - ok_1)*0.1);
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize)
marks.push_back(1-((winSize - ok_1) * 0.1));
}
}
if (tmp_1 + ok_1 < winSize)
marks.push_back(0.000000001);
// jesli nie ma miejsca na zwycięstwo daj duża wagę by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo
}
double getRowsGrade(char& player_sign, vector<vector<char>> tab_symb) {
char opposite_sign = getOpposite_sign(player_sign);
vector<double> marks;
marks.reserve(board_size);
for (int a = 0; a < board_size; a++) {
int ok_1 = 0;
int tmp_1 = 0;
for (int b = 0; b < board_size; b++) {
if (tab_symb[a][b] == 'e') tmp_1 += 1;
if (tab_symb[a][b] == player_sign)ok_1 += 1;
if (tab_symb[a][b] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if (isVictory(player_sign, tab_symb)) {
marks.push_back(1);
}
if (isVictory(opposite_sign, tab_symb)) {
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza
if (ok_1 + tmp_1 >= winSize) {
marks.push_back(1-((winSize - ok_1) * 0.1));
}
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize) {
marks.push_back(tmp_1 * 0.01);
}
}
}
if (tmp_1 + ok_1 < winSize) {
marks.push_back(0.000000001);
}
// jesli nie ma miejsca na zwycięstwo daj duża wagę by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo
}
double getColumnsGrade(char& player_sign, vector<vector<char>> tab_symb) {
vector<double> marks;
marks.reserve(board_size);
char opposite_sign = getOpposite_sign(player_sign);
for (int a = 0; a < board_size; a++) {
int ok_1 = 0; // dla kazdej kolumny/rzedu liczymy od nowa
int tmp_1 = 0;
for (int b = 0; b < board_size; b++) {
if (tab_symb[b][a] == 'e') tmp_1 += 1;
if (tab_symb[b][a] == player_sign) ok_1 += 1;
if (tab_symb[b][a] == opposite_sign) {
ok_1 = 0;
tmp_1 = 0;
}
// co linie sprawdzamy stan
if (isVictory(player_sign, tab_symb)) {
marks.push_back(1);
}
if (isVictory(opposite_sign, tab_symb)) {
marks.push_back(-1);
}
if (ok_1) { // jesli wystąpił znak gracza i jest miejsce do grania
if (ok_1 + tmp_1 >= winSize)
marks.push_back(1-((winSize - ok_1) * 0.1));
}
if (!ok_1) { // jesli jest wystarczająca ilość miejsc do zwycięstwa załóż że jest to jakaś szansa na zwyciestwo
if (tmp_1 >= winSize)
marks.push_back(tmp_1 * 0.01);
}
}
if (tmp_1 + ok_1 < winSize)
marks.push_back(0.000000001);
// jesli nie ma miejsca na zwycięstwo daj małą wage by zminimalizować szanse wejscia w
}
sort(marks.begin(), marks.end());
return marks.back(); // zwróc najwyższą wartość czyli najbardziej prawdopodbne zwycięstwo
}
double situationMark(char sign, vector<vector<char>> symulacja) {
double l_g1 = getLeftDiagGrade_1(sign, symulacja);
double l_g2 = getLeftDiagGrade_2(sign, symulacja);
double r_g1 = getRightDiagGrade_1(sign, symulacja);
double r_g2 = getRightDiagGrade_2(sign, symulacja);
double rw_g = getRowsGrade(sign, symulacja);
double cl_g = getColumnsGrade(sign, symulacja);
/* cout << "OCENY WYPISANE ZE ZMIENNYCH: " << endl;
cout << "l_g1: " << l_g1 << endl;
cout << "l_g2: " << l_g2 << endl;
cout << "r_g2: " << r_g1 << endl;
cout << "r_g2: " << r_g2 << endl;
cout << "rw_g: " << rw_g << endl;
cout << "cl_g2: " << cl_g << endl;
*/
double marks[6] = {l_g1, l_g2, r_g1, r_g2, rw_g, cl_g};
sort(marks, marks + 6);
// cout<<"POSORTOWANA TABLICA OCEN: "<<endl;
// for(auto i:marks) cout<<i<<endl;
//cout<<"OCENA ZWRACANA: "<<marks[5]<<endl;
return marks[5];
}
class Situation {
public:
double alfa;
double beta;
int w;
int k;
double mark;
Situation() {
w = 1;
alfa=-999999;
beta=999999;
k = 1;
mark = 0;
}
Situation(int a, int b, double c,double d, double e) {
w = a;
k = b;
mark = c;
alfa = d;
beta = e;
}
Situation(const Situation &C
) : w(C.w), k(C.k), mark(C.mark){}
~Situation() {}
Situation operator = (const Situation & E){
this->w=E.w;
this->k=E.k;
this->mark=E.mark;
this->alfa=E.alfa;
this->beta=E.beta;
}
};
Situation minimax(char sign,vector<vector<char>> symulacja, int poziom,double& alfa, double& beta,double V) {
char oponent_sign = getOpposite_sign(sign);
if (isEmpty(symulacja)) {
Situation tmp;
tmp.mark = situationMark(oponent, symulacja);
return tmp;
}
if (poziom == 6) {
Situation tmp;
tmp.mark = situationMark(oponent, symulacja);
return tmp;
}
Situation val;
Situation var;
double vmax = winSize * 10000;
double vmin = 0;
//cout<<"PRZED PĘTLAMI "<<endl;
for (int a = 0; a < board_size; a++) {
for (int b = 0; b < board_size; b++) {
if (symulacja[a][b] == 'e') {
symulacja[a][b] = sign;
// showBoard(symulacja);
var = minimax(oponent_sign, symulacja, ++poziom, alfa, beta, V);
// cout<<val.mark<<endl;
//minimax & alfabeta
if (sign == oponent) { // maximiser, computer
///////// alfa beta pruninng
// bedziemy przerywać pętle lub nie w zależności od załóżeń algorytmu
// warunki algorytmu sprawdzane na poczatku i albo jedziemy dalej albo nie
/*
if (V > beta) {
cout << "PRUNNING" << sign << endl;
break;
}
if (var.mark > V) {
if (var.mark > alfa) alfa = var.mark;
V = alfa;
}
*/
if (var.mark > vmin) {
vmin = var.mark;
val.k = a;
val.w = b;
val.mark = vmin;
}
}
if (sign == player_sign) { // minimiser, human player
////////alfa beta prunning
/*
if (V < beta) {
cout << "PRUNNING" << sign << endl;
break;
}
if (B < alfa) {
cout << "PRUNNING" << sign << endl;
break;
}
if (var.mark < V) {
beta = var.mark;
V = beta;
}
*/
if (var.mark < vmax) { // sprawdzanie który węzeł dał najlepsze prawdopodobienstwo wygranej
vmax = var.mark;
val.k = a;
val.w = b;
val.mark = vmax;
}
}
symulacja[a][b] = 'e';
}
}
}
return val;
}
void computerMakeStep(Situation& x, vector<vector<char>> &tab_symb){
tab_symb[x.k][x.w]=oponent;
}
int main() {
Situation var;
vector<vector<char>> tab_symb;
start_game(tab_symb);
char your_sign = player_sign;
char oponent = getOpposite_sign(your_sign);
bool winning = false;
showBoard(tab_symb);
double infinity = 9999999;
double minus_infinity = -infinity;
while (!winning) {
makeStep(your_sign, tab_symb);
winning = isVictory(your_sign, tab_symb);
cout << "situationMark(): " << situationMark('x', tab_symb) << endl << "::::::::::::::::::::::::::::::" << endl;
if (isVictory(your_sign, tab_symb)) {
cout << "\033[1;32m Wygrałeś \033[0m" << endl;
return 0;
}
/////////// znak, ,stan gry, poziom, alfa, beta, V
var=minimax(oponent,tab_symb,0,minus_infinity,infinity,minus_infinity);
computerMakeStep(var,tab_symb);
//makeStep(oponent, tab_symb);
showBoard(tab_symb);
winning = isVictory(oponent, tab_symb);
if (isVictory(oponent, tab_symb)) {
cout << "\033[1;31m Przegrałeś \033[0m" << endl;
return 0;
}
}
}
| 7abbd075b776de32665a2b036f6911e311806331 | [
"C",
"C++"
]
| 2 | C | MBocian96/tictactoe | 2d9d609fdb7abdd68a71f0ba5804ade104b452e5 | 6a8f98d73aa9d4bc58802ca3c454dac1c73fc71d |
refs/heads/master | <repo_name>pangbo4cnic/ciomp_dataTrans<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ciomp</groupId>
<artifactId>ciomp-dataTrans</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.framework.version>4.0.3.RELEASE</spring.framework.version>
<cxf.version>3.1.1</cxf.version>
</properties>
<dependencies>
<dependency>
<!--cxf -->
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.3</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.38</version>
</dependency>
<dependency>
<groupId>velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.xml.stream</artifactId>
<version>10.0-b28</version>
</dependency>
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.38</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.6</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.9.2</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${basedir}/src/main/webapp</webappDirectory>
<warSourceDirectory>${basedir}/src/main/webapp</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.14.v20131031</version>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8088</port>
</connector>
</connectors>
</configuration>
</plugin>
</plugins>
<finalName>dataTrans</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
</project><file_sep>/src/main/java/cn/ciomp/ws/impl/DataReceiveServiceImpl.java
package cn.ciomp.ws.impl;
import cn.ciomp.ws.DataReceiveService;
import javax.jws.WebService;
/**
* Created by cnic on 15-7-24.
*/
@WebService(endpointInterface= "cn.ciomp.ws.DataReceiveService")
public class DataReceiveServiceImpl implements DataReceiveService {
@Override
public String FILENOFIY(String requriment) {
System.out.println(requriment);
return "ok";
}
}
<file_sep>/src/main/resources/config.properties
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://172.16.58.3:3306/ciomp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=<PASSWORD>
ws.filenofiy=http://127.0.0.1:8088/jbcm/ws?wsdl<file_sep>/src/main/java/cn/ciomp/dao/DataReceiveTaskDao.java
package cn.ciomp.dao;
/**
* Created by cnic on 15-7-24.
*/
public interface DataReceiveTaskDao {
}
| 7c92cffda94f8522e2e1d1cb055ceb223dc58b93 | [
"Java",
"Maven POM",
"INI"
]
| 4 | Maven POM | pangbo4cnic/ciomp_dataTrans | b1df2b667bec8f0b8f124581d52b59ee837655a5 | da9ff0de9bb57e2c77a0d951cc48289e162aadb1 |
refs/heads/master | <file_sep>'use strict';
var housingRegex = /housing\.com/gi;
chrome.tabs.query({
currentWindow: true,
active: true
}, function(tabs) {
var data = {};
console.log(tabs);
var url = tabs[0].url;
var queryString = {};
var searchString;
var domain;
function openVM(){
var path = domain.split('//')[1].split('.com/')[1] || '';
domain = 'http://'+data.user+'.housing.com:'+data.port+'/'+path;
var newUrl = processTab();
chrome.tabs.create({
'url': domain + newUrl
});
}
function openMain(){
var path = domain.split('//')[1].split('.com/')[1] || '';
domain = 'https://housing.com/'+path;
var newUrl = processTab();
chrome.tabs.create({
'url': domain + newUrl
});
}
function processTab() {
$bot.checked ? queryString.bot = true : delete queryString.bot;
$desktop.checked ? delete queryString.desktop : queryString.desktop = false;
var newUrl = '';
var keys = Object.keys(queryString);
if (keys.length) {
newUrl = '?';
for (var i = 0; i < keys.length; i++) {
newUrl += keys[i] + '=' + queryString[keys[i]] + ((i === keys.length - 1) ? '' : '&');
}
}
return newUrl;
}
if (url.match(housingRegex)) {
domain = url.split('?')[0];
var getParams;
if (url.split('?')[1]) {
searchString = url.split('?')[1];
getParams = searchString.split('&');
}
console.log(getParams);
if (getParams) {
for (var i = 0; i < getParams.length; i++) {
var y = getParams[i].split('=');
var key = y[0];
var value = y[1];
queryString[key] = value;
}
}
var $bot = document.getElementById('bot');
var $desktop = document.getElementById('desktop');
if (queryString.bot) {
$bot.checked = true;
} else {
$bot.checked = false;
}
if (!queryString.desktop) {
$desktop.checked = true;
} else {
$desktop.checked = false;
}
var $openvm = document.getElementById('openVm');
var $openmain = document.getElementById('openMain');
$openvm.onclick = openVM;
$openmain.onclick = openMain;
}
var $user = document.getElementById('user');
var $port = document.getElementById('port');
chrome.storage.sync.get('user', function(r) {
data.user = r.user || '';
$user.value = data.user;
});
chrome.storage.sync.get('port', function(r) {
data.port = r.port || '';
$port.value = data.port;
});
$user.onkeyup = function() {
console.log('a');
data.user = $user.value;
chrome.storage.sync.set(data, function() {
console.log('saved');
});
};
$port.onkeyup = function() {
data.port = $port.value;
chrome.storage.sync.set(data, function() {
console.log('port saved');
});
};
});
| 81d9c6f3c3371bcbe9e80fbcc266b3f9d6382f49 | [
"JavaScript"
]
| 1 | JavaScript | ritz078/housing-chrome-extension | b57c8695728596e4d4fc9e836fda36d78f6914c1 | 7fcc3a9499fee4c03a018b309ca8834ad76ce851 |
refs/heads/master | <repo_name>athanri/shortlink_neueda_pj<file_sep>/angularshortlink/Dockerfile
# # Pull the latest Node image from Docker
# FROM node:latest
# # Copy the current directory contents into the container at /app
# COPY ./ /app/
# # Set the working directory to /app
# WORKDIR /app
# # Install Node Modules
# RUN npm install
# # Make port 4200 available to the world outside this container
# EXPOSE 4200/tcp
# # Start Angular in Watch mode
# CMD ["npm", "start", "--", "--host", "0.0.0.0", "--poll", "500"]
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
COPY /dist/shortenedUrl /usr/share/nginx/html
EXPOSE 4200/tcp<file_sep>/angularshortlink/src/app/components/url-form/url-form.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { UrlService } from "../../services/url.service";
import { FormBuilder, FormGroup, Validators} from '@angular/forms';
//^^Import statements for component dependancies
@Component({
selector: 'app-url-form',
templateUrl: './url-form.component.html',
styleUrls: ['./url-form.component.css']
})
export class UrlFormComponent implements OnInit {
form: FormGroup = new FormGroup({});
// id: string;
// text: string;
// date: any;
// longLinkDesc: string;
serverError: boolean = false;
errorMsg:string;
constructor(
private http: HttpClient,
private fb: FormBuilder,
private urlService: UrlService) {
//basic url check
const reg = '(https?://)?([\\da-z.-]+)\\.([a-z.]{2,6})[/\\w .-]*/?';
this.form = fb.group({
//checks url is valid pattern and enables Add Url button if so
url: ['', [Validators.required, Validators.pattern(reg)]]
})
}
ngOnInit(): void {
}
get f(){
return this.form.controls;
}
onSubmit() {
// on submission of the form initialise a 'newUrl' object
const newUrl = {
id:'',
text:'',
date:'',
longLinkDesc:''
}
//subscribe to the observable and if server responds assign values as per below. otherwise if there are errors display to user.
this.sendPostRequest().subscribe(
res => {
newUrl.id = res._id;
newUrl.text = res.shortUrl;
newUrl.date = res.date;
newUrl.longLinkDesc = res.longUrl;
//add url to view and save to localStorage using the service
this.urlService.addUrl(newUrl);
}, (error) => {
if (error.statusText === "Unauthorized") {
this.serverError = true;
//the server will check if Url is a valid url and if not will return this message
this.errorMsg = `${error.error} - Please enter a valid working link`;
} else {
this.serverError = true;
this.errorMsg = `${error.statusText} - Server Error Please Try Again Later`;
}
}
);
//clear state
this.clearState();
}
// send post request to the serer with an object as the param
sendPostRequest(): Observable<any> {
return this.http.post<any>('http://localhost:5000/api/url/shorten', {longUrl: this.form.get('url').value});
}
//This function clears the input box
clearState() {
// this.id = '';
// this.text = '';
this.form.reset(); //get the for named url and empty
this.serverError = false;
// this.date = '';
// this.urlService.clearState;
}
}
<file_sep>/angularshortlink/src/app/components/url-log/url-log.component.ts
import { Component, OnInit } from '@angular/core';
import { UrlService } from "../../services/url.service";
import { Url } from "../../models/url";
@Component({
selector: 'app-url-log',
templateUrl: './url-log.component.html',
styleUrls: ['./url-log.component.css']
})
export class UrlLogComponent implements OnInit {
urls: Url[];
selectedUrl: Url;
loaded: boolean = false;
isCollapsed = true;
constructor(private urlService: UrlService) { }
//on creation of the component
ngOnInit(): void {
this.urlService.stateClear.subscribe(clear => {
if(clear) {
this.selectedUrl = {id: '', text: '', date: '', longLinkDesc: ''}
}
});
//load urls if they exist
this.urlService.getUrls().subscribe(urls => {
this.urls = urls;
this.loaded = true;
});
}
//select individual record(url)
onSelect(url: Url) {
this.urlService.setFormUrl(url);
this.selectedUrl = url;
}
//delete url from localStorage when button pressed
onDelete(url: Url){
if(confirm('Do you want to delete?')) {
this.urlService.deleteUrl(url);
}
}
}
<file_sep>/angularshortlink/src/app/services/url.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Observable } from 'rxjs';
import { of } from "rxjs";
import { Url } from "../models/url";
@Injectable({
providedIn: 'root'
})
export class UrlService {
urls: Url[];
private urlSource = new BehaviorSubject<Url>({id: null, text: null, date: null, longLinkDesc: null});
// selectedUrl = this.urlSource.asObservable();
private stateSource = new BehaviorSubject<boolean>(true);
stateClear = this.stateSource.asObservable();
constructor() {
// this.urls = [
// // {id: '1', text: 'galwaystaging', date: new Date('12/09/2020 12:34:22')},
// // {id: '2', text: 'tribes', date: new Date('10/09/2020 07:34:53')},
// // {id: '3', text: '4allour', date: new Date('08/09/2020 09:56:22')}
// ];
this.urls = [];
}
//if urls exist in localStorage retrieve them and sort by date otherwise set blank urls array
getUrls() : Observable<Url[]>{
if(localStorage.getItem('urls') === null) {
this.urls = [];
} else {
this.urls = JSON.parse(localStorage.getItem('urls'));
}
return of(this.urls.sort((a, b) => {
return b.date - a.date;
}));
}
setFormUrl(url: Url) {
this.urlSource.next(url);
}
//add url to localStorage and urls array
addUrl(url: Url) {
this.urls.unshift(url);
//Add to local storage
localStorage.setItem('urls', JSON.stringify(this.urls));
}
// delete from array and localStorage
deleteUrl(url: Url) {
this.urls.forEach((cur, index) => {
if(url.id === cur.id) {
this.urls.splice(index, 1);
}
})
//delete localStorage
localStorage.setItem('urls', JSON.stringify(this.urls));
}
clearState() {
this.stateSource.next(true);
}
}
<file_sep>/shortlinkserver/Dockerfile
# Pull the latest Node image from Docker
FROM node:latest
# Copy the current directory contents into the container at /app
COPY ./ /app/
# Set the working directory to /app
WORKDIR /app
# Install Node Modules
RUN npm install
# Make port 5000 available to the world outside this container
EXPOSE 5000/tcp
# Start Server
CMD ["npm", "start"]<file_sep>/docker-compose.yml
version: '3.0' # docker-compose engine version
# Define the services/containers to be run
services:
angularshortlink:
build: shortened-url-ui #specify directory of frontend service
ports:
- "4200:4200" #Ports to expose service
shortlinkserver: #server service
build: shortlinkserver #specify directory of server service
ports:
- "5000:5000" #Ports to expose server
links:
- database #links this service to db service (below)
database: #db service (mongoDB)
image: mongo #specify image to build container from
ports:
- "27017:27017" #Ports to expose mongoDB (default)
<file_sep>/angularshortlink/src/app/components/url-form/url-form.component.spec.ts
import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { UrlService } from '../../services/url.service'
import { UrlFormComponent } from './url-form.component';
import { ReactiveFormsModule } from '@angular/forms';
describe('UrlService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [UrlService]
}));
it('should be created', () => {
const service: UrlService = TestBed.inject(UrlService);
expect(service).toBeTruthy();
});
it('should have addUrls function', () => {
const service: UrlService = TestBed.inject(UrlService);
expect(service.addUrl).toBeTruthy();
});
});
describe('UrlFormComponent', () => {
let component: UrlFormComponent;
let fixture: ComponentFixture<UrlFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ UrlFormComponent ],
imports: [HttpClientTestingModule, ReactiveFormsModule],
providers: [UrlService]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(UrlFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it(`should be create`, () => {
expect(component).toBeTruthy();
});
// check if onSubmit function is available
it('should have onSubmit function', () => {
expect(component.onSubmit).toBeTruthy();
});
// check if sendPostRequest function is available
it('should have sendPostRequest function', () => {
expect(component.sendPostRequest).toBeTruthy();
});
});
<file_sep>/README.md
# ShortenedUrl Prerequisites
* Download and Install Docker / Docker Composer [Windows](https://hub.docker.com/editions/community/docker-ce-desktop-windows) `*`TESTED [MacOS](https://hub.docker.com/editions/community/docker-ce-desktop-mac) TESTED [Ubhuntu](https://docs.docker.com/engine/install/ubuntu/) NOT TESTED
`*` If you encounter the following ERROR on wndows - ERROR: error pulling image configuration: unexpected EOF please see [here](https://github.com/docker/for-mac/issues/3493#issuecomment-616338458)
## ShortLink Server UI and DB
This repo contains the source code for the shortlink server and source code along with the compiled version of the shortlinkUI
## Setup
Install docker / docker composer
Clone / Download this repo
Open CMD or Terminal window
Change Directory to cloned / downloaded repo you should notice a docker-compose.yml file in this dir (`ls`(Mac) or `dir`(Windows) to view files folders.
run `docker-compose build` allow command to complete, may take some time depending on Internet connection.
run `docker-compose up` once previous command finishes.
`*` If you encounter the following ERROR on wndows - ERROR: error pulling image configuration: unexpected EOF please see [here](https://github.com/docker/for-mac/issues/3493#issuecomment-616338458)
## View UI
To launch frontend ui, open browser of choice and enter following address `http://localhost:4200`
## Build
Open CMD or Terminal window
Change Directory to `angularshortlink` inside cloned / downloaded repo
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
There are a total of 10 Unit Tests. Some I have added but most were auto generated tests.
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Potential Enhancements
1. Stored url to DB. (Implemented)
2. Duplicate long links will be retrieved from DB. (Implemented)
3. Mobile Friendly (Implemented)
3. Provide Login and register functionality so end user can view stored links anywhere.(Not Implemented)
4. Admin and User Panels so users can change their name and password. Admins can delete / add users. (Not Implemented)
## Limitations
* App needs to run on Ports 4200(UI), 5000(Server) and 27017(DB) before app will work correctly.
* Only certain urls will be accepted by UI as I used a simple regex statement on UI.
## Known Issues
* Only certain urls will be accepted by UI as I used simple regex statement on FE.
* Flash Messages don't always clear nicely.
* User can input incorrect URLs and only the server will reject them.
* Viewing details of one item opens all itmes in view.
## Further help
App Usage Doc available [here](https://docs.google.com/document/d/1pSdtS-nAzei7vvHbSjhKG97F5Sc2tL49qcL7SqXqjnY/edit?usp=sharing).
| 24378e282d6a505ba56c9f6e574a62597aec15dc | [
"Markdown",
"TypeScript",
"Dockerfile",
"YAML"
]
| 8 | Dockerfile | athanri/shortlink_neueda_pj | 200194b81fe9f94b14eb3163dc7cdb1d3364212b | 064c1327a134c3a34f9fae4f1a8531d9e1fac811 |
refs/heads/master | <file_sep>package com.accenture.sfdc.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;
/**
* Clase para gestionar la codificación de los datos
*
*/
public class Encoding {
/**
* Método para obtener los bytes de una imagen
*
* @param image
* @param type
* @return Devuelve el conjunto de bytes que forman la imagen
* @throws IOException
*/
public static byte[] getBytes(BufferedImage image, String type) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
bos.close();
return imageBytes;
}
/**
* Método que condifica un conjunto de bytes en Base64
*
* @param bytes
* @return Devuelve los bytes recibidos tranformados en Base64
*/
public static String base64Encode(byte[] bytes) {
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(bytes);
}
}
<file_sep>package com.accenture.sfdc.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.glxn.qrgen.javase.QRCode;
/**
* Clase para generar códigos QR
*
*/
public class QRGenerator {
private String content;
private int width;
private int height;
/**
* Constructor que recibe el contenido, alto y ancho del código que se desea
* generar
*
* @param content
* @param width
* @param height
*/
public QRGenerator(String content, int width, int height) {
this.content = content;
this.width = width;
this.height = height;
}
/**
* Método que genera el código QR indicado al construir el objeto
*
* @return Devuelve una imagen con el código QR generado.
* @throws IOException
*/
public BufferedImage generate() throws IOException {
ByteArrayOutputStream stream = QRCode.from(content).withSize(width, height).stream();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stream.toByteArray());
BufferedImage result = ImageIO.read(byteArrayInputStream);
stream.close();
return result;
}
}
<file_sep>package com.accenture.sfdc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.TreeMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.accenture.sfdc.utils.CSVAnalizer;
import com.accenture.sfdc.utils.Encoding;
import com.accenture.sfdc.utils.FTPConnection;
import com.accenture.sfdc.utils.QRGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.zxing.WriterException;
/**
* Clase que controla las peticiones REST de la aplicación
*
*/
@RestController
@RequestMapping("/")
public class HackathonRest {
private static String FTP_HOST = "nclsistemas.ddns.net";
private static int FTP_PORT = 55536;
private static String FTP_USER = "FTPUser";
private static String FTP_PASS = "<PASSWORD>";
private static String FTP_WORKING_DIR = "/FTPTest";
private static String CSV_RESOURCE_FILE = "oms_export_suz58.csv";
/**
* Método para gestionar las peticiones entrantes de tipo GET a la URL /qrcode
*
* @param text
* @param width
* @param height
* @return Devuelve un String con la imagen del código QR codificada en Base64
* @throws WriterException
* @throws IOException
*/
@RequestMapping(value = "qrcode", method = RequestMethod.GET)
public static String generateQRCode(@RequestParam String text, @RequestParam int width, @RequestParam int height)
throws WriterException, IOException {
QRGenerator qrGenerator = new QRGenerator(text, width, height);
return Encoding.base64Encode(Encoding.getBytes(qrGenerator.generate(), "png"));
}
/**
* Método para gestionar la conexion con un servidor FTP. Obtiene un fichero CSV
* para analizarlo, obtener los datos y la imagen que se debe descargar.
*
* @return Se devuelve un objeto JSON con los datos del CSV y el contenido del
* fichero asociado en Base64
* @throws WriterException
* @throws IOException
*/
@RequestMapping(value = "ftpserver", method = RequestMethod.GET)
public static String ftpServerConnection() throws WriterException, IOException {
String response = "";
FTPConnection connection = null;
try {
connection = FTPConnection.getInstance(FTP_HOST, FTP_PORT);
connection.setCredentials(FTP_USER, FTP_PASS);
if (connection.connect()) {
connection.changeWorkingDirectory(FTP_WORKING_DIR);
byte[] csvBytes = connection.retrieveFile(CSV_RESOURCE_FILE);
if (csvBytes != null) {
ArrayList<TreeMap<String, String>> csvData = CSVAnalizer.analizeCSV(new String(csvBytes));
if (csvData.size() > 0) {
for (TreeMap<String, String> csvRow : csvData) {
String filePath = csvRow.get(CSVAnalizer.FILE);
byte[] fileBytes = connection.retrieveFile(filePath);
csvRow.put(CSVAnalizer.FILE, Encoding.base64Encode(fileBytes));
}
response = new ObjectMapper().writeValueAsString(csvData);
}
}
}
} catch (Exception ioe) {
ioe.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
return response;
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.accentrue.sfdc</groupId>
<artifactId>QRGenerator</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.0.RELEASE</version>
<relativePath />
</parent>
<name>QRGenerator</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<webjars-bootstrap.version>4.1.3</webjars-bootstrap.version>
<webjars-jquery-ui.version>1.12.1</webjars-jquery-ui.version>
<webjars-jquery.version>3.3.1-1</webjars-jquery.version>
</properties>
<dependencies>
<dependency>
<groupId>net.glxn.qrgen</groupId>
<artifactId>javase</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.jscience</groupId>
<artifactId>jscience</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<exclusions>
<exclusion>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>build-info</goal>
</goals>
<configuration>
<additionalProperties>
<encoding.source>${project.build.sourceEncoding}</encoding.source>
<encoding.reporting>${project.reporting.outputEncoding}</encoding.reporting>
<java.source>${maven.compiler.source}</java.source>
<java.target>${maven.compiler.target}</java.target>
</additionalProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep># IOhanathonHeroku
Heroku Application for I Ohanathon
| 12000b5d303ddcd69955125f0dbd3bba292e16e1 | [
"Markdown",
"Java",
"Maven POM"
]
| 5 | Java | mucori/IOhanathonHeroku | 95665ef602da586e0b6867575a774ffa8273abcd | c14e9394f8b0d302bf17bcf44d33c7d569832495 |
refs/heads/master | <file_sep>package pepinazo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import cucumber.annotation.After;
import cucumber.annotation.Before;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.runtime.PendingException;
import facebookPOM.pages.HomePage;
import facebookPOM.pages.LoginPage;
import facebookPOM.pages.SearchResultsPage;
import junit.framework.Assert;
import static junit.framework.Assert.*;
public class StepDefs {
public WebDriver driver;
LoginPage login;
HomePage home;
SearchResultsPage results;
@Before
public void setUpTest() {
ChromeOptions opt = new ChromeOptions();
opt.addArguments("--disable-notifications");
driver = new ChromeDriver(opt);
login = new LoginPage(driver);
home = new HomePage(driver);
results = new SearchResultsPage(driver);
}
@After
public void tearDownTest() {
driver.quit();
}
@Given("^I have open the browser$")
public void I_have_open_the_browser() {
assertNotNull(driver);
}
@When("^I open Facebook website$")
public void I_open_Facebook_website() {
driver.get("https://facebook.com");
}
@Then("^Login button should exist$")
public void Login_button_should_exist() {
assertTrue(login.at());
}
@Then("^Login button should be disabled$")
public void Login_button_should_be_disabled() {
assertTrue(login.loginButtonDisabled());
}
@When("^I click the login button$")
public void I_click_the_login_button() {
login.clickLoginButton();
}
@Then("^Facebook asks me to enter credentials$")
public void Facebook_asks_me_to_enter_credentials() {
// Express the Regexp above with the code you wish you had
System.out.println("");
}
@When("^I login using cell phone number$")
public void I_login_using_cell_phone_number() {
// Express the Regexp above with the code you wish you had
System.out.println("");
}
@Then("^Facebook Home Page must appear$")
public void Facebook_Home_Page_must_appear() {
assertTrue(home.at());
}
@When("^I login with ([^\"]*) and ([^\"]*)$")
public void I_login_with_user_and_pass(String username, String password) {
login.login(username, password);
}
@Then("^I can see Home Page$")
public void I_can_see_Home_Page() {
assertTrue(home.at());
}
}
| 8ae8ffe160169ab299bf2f5a727288b0d38675c6 | [
"Java"
]
| 1 | Java | SandraFloresB/pepinazo | 343e28d4016b44fd3418e391c15b5847a317059f | db93bbeb68a97dc1712fdbe136078630134dc953 |
refs/heads/master | <repo_name>paulwolo/Meditate<file_sep>/Meditate/ViewController.swift
//
// ViewController.swift
// Meditate
//
// Created by <NAME> on 4/30/18.
// Copyright © 2018 paulwolo. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, BWWalkthroughViewControllerDelegate {
// BAEEF5 light-blue color
// RGB: 186 238 245
// 44 46 58
// 87% grey scale
let myGrayBlue = UIColor(displayP3Red: (44.0/255.0), green: (46.0/255.0), blue: (58.0/255.0), alpha: 1.0)
let myBlue = UIColor(displayP3Red: (186.0/255.0), green: (238.0/255.0), blue: (245.0/255.0), alpha: 1.0)
// sets the intensity of the flashlight
var torchMode: Float = 0.0
// says whether variable is increasing
var increasing = true;
@IBOutlet weak var BeginMeditationButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBAction func beginMeditation(_ sender: UIButton) {
guard let currentButtonName = sender.currentTitle else {
print("error")
return
}
if currentButtonName == "Start" || currentButtonName == "Resume" {
resetButton.backgroundColor = myBlue
timeRemainingTimer = Timer.scheduledTimer(timeInterval: timeRemainingDuration, target: self, selector: (#selector(ViewController.updateThirdTimer)), userInfo: nil, repeats: true)
startTimer()
sender.setTitle("Pause", for: .normal)
UIApplication.shared.isIdleTimerDisabled = true
} else if currentButtonName == "Pause" {
timeRemainingTimer.invalidate()
pauseTimer()
sender.setTitle("Resume", for: .normal)
UIApplication.shared.isIdleTimerDisabled = false
}
}
// pauses the timer
func pauseTimer() {
timer.invalidate()
secondTimer.invalidate()
turnOffTorch()
}
// resets the timer
@IBAction func resetTimer(_ sender: UIButton) {
resetMeditation()
}
func resetMeditation() {
resetButton.backgroundColor = myGrayBlue
BeginMeditationButton.setTitle("Start", for: .normal)
torchMode = 0.0
increasing = true
timer.invalidate()
secondTimer.invalidate()
timeRemainingTimer.invalidate()
timerDisplayValue = 600
breathsPerMinute = 0.0625
turnOffTorch()
UIApplication.shared.isIdleTimerDisabled = false
}
// timer to adjust the brightness gradually
var timer = Timer()
// timer to adjust the speed at which the brightness adjusts
var secondTimer = Timer()
var timeRemainingTimer = Timer()
// rate at which the brightness adjusts
var breathsPerMinute = 0.0625
// rate at which the
let meditationDuration = 60.0
let timeRemainingDuration = 1.0
// starts the two timers
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: breathsPerMinute, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
secondTimer = Timer.scheduledTimer(timeInterval: meditationDuration, target: self, selector: (#selector(ViewController.updateSecondTimer)), userInfo: nil, repeats: true)
}
@IBOutlet weak var timeRemainingDisplay: UILabel!
var timerDisplayValue: Int {
get {
let displayText = timeRemainingDisplay.text!
if displayText.count == 5 {
let minutes = Int(displayText[0...1])
let seconds = Int(displayText[3...4])
return (minutes! * 60) + seconds!
} else if displayText.count == 4 {
let minutes = Int(displayText[0..<1])
let seconds = Int(displayText[2...3])
return (minutes! * 60) + seconds!
} else {
print("error in display")
return 0
}
}
set {
let minutes = newValue / 60
let seconds = newValue % 60
if seconds < 10 {
timeRemainingDisplay.text = "\(minutes):0\(seconds)"
} else {
timeRemainingDisplay.text = "\(minutes):\(seconds)"
}
}
}
@objc func updateThirdTimer() {
if timerDisplayValue >= 1 {
timerDisplayValue -= 1
} else {
timeRemainingTimer.invalidate()
timerDisplayValue = 600
}
}
// every 60 seconds, this is executed. Indicates the flashight to decrease the
// rate at which the brightness adjusts.
@objc func updateSecondTimer() {
if breathsPerMinute <= 0.125 {
timer.invalidate()
secondTimer.invalidate()
breathsPerMinute += 0.0078125
startTimer()
} else {
resetMeditation()
}
}
// each time this is executed, the brightness adjusts one increment
@objc func updateTimer() {
if increasing {
torchMode += 0.025
} else {
torchMode -= 0.025
}
if torchMode > 1 {
torchMode = 1
increasing = false
} else if torchMode < 0 {
torchMode = 0
increasing = true
}
updateTorch()
}
// function to update the flashlight
func updateTorch() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video) else {
return
}
if device.hasTorch && device.isTorchAvailable {
do {
try device.lockForConfiguration()
if torchMode == 0 {
device.torchMode = .off
} else {
try device.setTorchModeOn(level: torchMode)
}
device.unlockForConfiguration()
} catch {
print("Torch is not working.")
}
} else {
print("Torch not compatible with device.")
}
}
// turns off the torch
func turnOffTorch() {
guard let device = AVCaptureDevice.default(for: AVMediaType.video) else {
return
}
if device.hasTorch && device.isTorchAvailable {
do {
try device.lockForConfiguration()
device.torchMode = .off
device.unlockForConfiguration()
} catch {
print("Torch is not working.")
}
} else {
print("Torch not compatible with device.")
}
}
@IBAction func walkthroughButtonTouched() {
let stb = UIStoryboard(name: "Main", bundle: nil)
let walkthrough = stb.instantiateViewController(withIdentifier: "Master") as! BWWalkthroughViewController
let page_one = stb.instantiateViewController(withIdentifier: "page1") as UIViewController
let page_two = stb.instantiateViewController(withIdentifier: "page2") as UIViewController
let page_three = stb.instantiateViewController(withIdentifier: "page3") as UIViewController
let page_four = stb.instantiateViewController(withIdentifier: "page4") as UIViewController
// Attach the pages to the master
walkthrough.delegate = self
walkthrough.add(viewController:page_one)
walkthrough.add(viewController:page_two)
walkthrough.add(viewController:page_three)
walkthrough.add(viewController:page_four)
self.present(walkthrough, animated: true, completion: nil)
}
func walkthroughCloseButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Possible Background.jpg")!)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// restricts to portrait mode only
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
}
extension String {
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
| dd3ac35d91804daff2fcf18e294936393aec8120 | [
"Swift"
]
| 1 | Swift | paulwolo/Meditate | 41a4234959472930f86f3690071cc16369eef61e | f98562990e3de6d55c414e5cc0ef54daaef556e0 |
refs/heads/master | <repo_name>Fenimorkin/norsu<file_sep>/norsu/utils.py
import subprocess
from .exceptions import Error
def execute(args, cwd=None, output=True, error=True):
stdout = subprocess.PIPE if output else subprocess.DEVNULL
p = subprocess.Popen(args, cwd=cwd,
stdout=stdout,
stderr=subprocess.STDOUT)
if output:
out, _ = p.communicate()
out = out.decode('utf8')
else:
p.wait()
out = None
if p.returncode != 0:
if error:
raise Error('Failed to execute {}'.format(' '.join(args)))
else:
return out
<file_sep>/norsu/refs.py
import os
from functools import total_ordering
from .config import CONFIG
from .utils import execute
@total_ordering
class SortRefByVersion:
def __init__(self, ref):
# use lowercase for substr search
name = ref.name.lower()
# extract version numbers
ver = ''.join((c for c in name if c.isdigit() or c == '_'))
ver = (n for n in ver.split('_') if n)
ver = list(map(lambda n: int(n), ver))
types = [
('stable', float('+inf')),
('rc', -1),
('beta', -2),
('alpha', -3),
]
for t, num in types:
if t in name:
# example:
# REL_10_RC1 => (10, -1, 1)
# REL_9_6_STABLE => (9, 6, 'inf')
_, _, s = name.rpartition(t)
if s.isdigit():
ver.pop() # see ver extraction
ver.append(num)
ver.append(int(s))
else:
ver.append(num)
self.ref = ref
self.ver = ver
def __eq__(self, other):
return self.ver == other.ver
def __lt__(self, other):
return self.ver < other.ver
def __str__(self):
return self.ref
@total_ordering
class SortRefBySimilarity:
@staticmethod
def ngram(text, N=3):
ngrams = (text[i:i+N] for i in range(0, len(text) - N + 1))
return set(ngrams)
@staticmethod
def similarity(ng1, ng2):
return len(ng1 & ng2) / float(len(ng1 | ng2))
def __init__(self, ref, name_ngram):
ng1 = self.ngram(ref.name)
ng2 = name_ngram
self.similarity = self.similarity(ng1, ng2)
self.ref = ref
def __eq__(self, other):
return self.similarity == other.similarity
def __lt__(self, other):
return self.similarity < other.similarity
class GitRef:
def __init__(self, repo, name):
self.repo = repo
self.name = name
def __repr__(self):
return self.name
def find_relevant_refs(repos, patterns):
refs = []
for repo in repos:
args = ['git', 'ls-remote', '--heads', '--tags', repo]
args += patterns # search patterns
out = execute(args)
# list of matching branches and tags
refs += [
GitRef(repo, os.path.basename(r.split()[-1]))
for r in out.splitlines()
]
# should we stop after 1st match?
if refs and CONFIG['repos']['first_match']:
break
return refs
<file_sep>/norsu/instance.py
import os
import re
import shlex
from enum import Enum
from shutil import rmtree
from .config import NORSU_DIR, WORK_DIR, CONFIG
from .exceptions import Error
from .terminal import Style
from .utils import execute
from .refs import \
SortRefByVersion, \
SortRefBySimilarity, \
find_relevant_refs
def step(*args):
print(Style.green('\t=>'), *args)
def line(name, value=None):
print('\t', name, '\t{}'.format(value) if value is not None else '')
def sort_refs(refs, name):
# key function for sort
def to_key(x):
if name.type == InstanceNameType.Version:
return SortRefByVersion(x)
else:
# pre-calculated for better performance
name_ngram = SortRefBySimilarity.ngram(name.value)
return SortRefBySimilarity(x, name_ngram)
return sorted(refs, reverse=True, key=to_key)
class InstanceNameType(Enum):
Version = 1
Branch = 2
class InstanceName:
rx_is_ver = re.compile(r'\d+([._]\d+)*')
rx_sep = re.compile(r'(\.|_)')
def __init__(self, name):
for s in ['/']:
if s in name:
raise Error('Wrong name {}'.format(name))
self.value = name
if self.rx_is_ver.match(name):
self.type = InstanceNameType.Version
else:
self.type = InstanceNameType.Branch
def to_patterns(self):
pattern = self.value
result = [pattern]
if self.type == InstanceNameType.Version:
# replace version separators with a pattern
pattern = self.rx_sep.sub(lambda m: '[._]', pattern)
for fmt in ['REL_{}*', 'REL{}*']:
result.append(fmt.format(pattern))
else:
result.append('*{}*'.format(pattern))
return result
def __str__(self):
return self.value
class Instance:
def __init__(self, name):
self.name = InstanceName(name)
self.main_dir = os.path.join(NORSU_DIR, name)
self.work_dir = os.path.join(WORK_DIR, name)
self.commit_hash_file = os.path.join(self.main_dir, '.norsu_hash')
@property
def ignore(self):
ignore_file = os.path.join(self.main_dir, '.norsu_ignore')
return os.path.exists(ignore_file)
@property
def actual_commit_hash(self):
if os.path.exists(self.work_dir):
args = ['git', 'rev-parse', 'HEAD']
return execute(args, cwd=self.work_dir).strip()
@property
def installed_commit_hash(self):
if os.path.exists(self.commit_hash_file):
with open(self.commit_hash_file, 'r') as f:
return f.read().strip()
@property
def fresh_commit(self):
return self.installed_commit_hash == self.actual_commit_hash
@installed_commit_hash.setter
def installed_commit_hash(self, value):
with open(self.commit_hash_file, 'w') as f:
f.write(value)
@property
def branch(self):
if os.path.exists(self.work_dir):
args = ['git', 'symbolic-ref', '--short', 'HEAD']
out = execute(args, cwd=self.work_dir, error=False)
if out:
return out.strip()
@property
def tag(self):
if os.path.exists(self.work_dir):
args = ['git', 'tag', '--points-at', 'HEAD']
out = execute(args, cwd=self.work_dir, error=False)
if out:
return out.strip()
def pg_config(self, params=None):
pg_config = os.path.join(self.main_dir, 'bin', 'pg_config')
if os.path.exists(pg_config):
return execute([pg_config] + params)
def status(self):
postgres = os.path.join(self.main_dir, 'bin', 'postgres')
if os.path.exists(postgres):
if self.fresh_commit:
status = Style.green('Installed')
else:
status = Style.yellow('Installed (out of date)')
else:
status = Style.red('Not installed')
line('Status:', status)
if os.path.exists(self.main_dir):
line('Main dir:', self.main_dir)
else:
line('Main dir:', 'none')
if os.path.exists(self.work_dir):
line('Work dir:', self.work_dir)
branch = self.branch or self.tag
if branch:
line('Branch:', branch)
else:
line('Work dir:', 'none')
pg_config_out = self.pg_config(['--version'])
if pg_config_out:
line('Version:', pg_config_out.strip())
commit = self.installed_commit_hash
if commit:
line('Commit:', commit)
configure = self._configure_options()
line('CONFIGURE:', configure)
def pull(self):
self._prepare_work_dir()
def install(self):
if not self.ignore:
try:
self._prepare_work_dir()
self._make_distclean()
self._configure_project()
self._make_install()
except Error as e:
step(Style.red(str(e)))
else:
step(Style.yellow('Ignored due to .norsu_ignore'))
def remove(self):
if os.path.exists(self.main_dir):
rmtree(path=self.main_dir, ignore_errors=True)
step('Removed main dir')
if os.path.exists(self.work_dir):
rmtree(path=self.work_dir, ignore_errors=True)
step('Removed work dir')
def _configure_options(self):
norsu_file = os.path.join(self.main_dir, '.norsu_configure')
if os.path.exists(norsu_file):
with open(norsu_file, 'r') as f:
return shlex.split(f.read())
pg_config_out = self.pg_config(['--configure'])
if pg_config_out:
options = shlex.split(pg_config_out)
return [x for x in options if not x.startswith('--prefix')]
return CONFIG['build']['configure_options']
def _prepare_work_dir(self):
git_repo = os.path.join(self.work_dir, '.git')
if os.path.exists(git_repo):
branch = self.branch
if branch:
args = ['git', 'pull', 'origin', branch]
execute(args, cwd=self.work_dir, output=False)
if not self.fresh_commit:
step('Installed build is out of date')
else:
step('No work dir, choosing repo & branch')
patterns = self.name.to_patterns()
refs = find_relevant_refs(CONFIG['repos']['urls'], patterns)
if not refs:
raise Error('No branch found for {}'.format(self.name))
# select the most relevant branch
ref = sort_refs(refs, self.name)[0]
step('Selected repo', Style.bold(ref.repo))
step('Selected branch', Style.bold(ref.name))
args = [
'git',
'clone',
'--branch', ref.name,
'--depth', str(1),
ref.repo,
self.work_dir,
]
execute(args, output=False)
step('Cloned git repo to work dir')
def _configure_project(self):
makefile = os.path.join(self.work_dir, 'GNUmakefile')
if not os.path.exists(makefile):
args = [
'./configure',
'--prefix={}'.format(self.main_dir)
] + self._configure_options()
execute(args, cwd=self.work_dir, output=False)
step('Configured sources')
def _make_install(self):
if not self.fresh_commit:
jobs = int(CONFIG['build']['jobs'])
for args in [['make', '-j{}'.format(jobs)], ['make', 'install']]:
execute(args, cwd=self.work_dir, output=False)
# update installed commit hash
self.installed_commit_hash = self.actual_commit_hash
step('Built and installed to', Style.blue(self.main_dir))
def _make_distclean(self):
if os.path.exists(self.work_dir) and not self.fresh_commit:
args = ['make', 'distclean']
execute(args, cwd=self.work_dir, output=False, error=False)
step('Prepared work dir for a new build')
<file_sep>/norsu/main.py
import os
import sys
from shutil import rmtree
from .config import NORSU_DIR, WORK_DIR, CONFIG
from .exceptions import Error
from .instance import Instance, InstanceName, sort_refs
from .refs import find_relevant_refs
from .terminal import Style
def parse_args(args, dir=NORSU_DIR):
entries = args
if not entries:
entries = (
e for e in os.listdir(dir)
if not e.startswith('.')
)
# TODO: also return options
return (sorted(entries), None)
def cmd_instance(cmd, args):
entries, _ = parse_args(args)
# safety pin (see config)
if not args and cmd == 'remove' and \
CONFIG['commands']['remove']['require_args']:
raise Error('By default, this command requires arguments')
for entry in entries:
print('Selected instance:', Style.bold(entry))
instance = Instance(entry)
cmds = {
'install': lambda: instance.install(),
'remove': lambda: instance.remove(),
'status': lambda: instance.status(),
'pull': lambda: instance.pull(),
}
# execute command
cmds[cmd]()
print()
def cmd_search(_, args):
entries, _ = parse_args(args)
for entry in entries:
name = InstanceName(entry)
patterns = name.to_patterns()
print('Search query:', Style.bold(entry))
refs = find_relevant_refs(CONFIG['repos']['urls'], patterns)
for ref in sort_refs(refs, name):
print('\t', ref)
print()
def cmd_purge(_, args):
entries, _ = parse_args(args, WORK_DIR)
for entry in entries:
instance = os.path.join(NORSU_DIR, entry)
if not os.path.exists(instance):
path = os.path.join(WORK_DIR, entry)
rmtree(path=path, ignore_errors=True)
def cmd_path(_, args):
entries, _ = parse_args(args, NORSU_DIR)
for entry in entries:
print(os.path.join(NORSU_DIR, entry))
def cmd_help(*_):
name = os.path.basename(sys.argv[0])
print('{} -- PostgreSQL builds manager'.format(Style.blue(name)))
print()
print('Usage:')
print('\t{} <command> [options]'.format(name))
print()
print('Commands:')
for method in METHODS.keys():
print('\t{}'.format(method))
print()
print('Examples:')
print('\t{} install 9.6.5 10 master'.format(name))
print('\t{} pull REL_10_STABLE'.format(name))
print('\t{} remove 9.5'.format(name))
print('\t{} status'.format(name))
def main():
args = sys.argv[1:]
if len(args) == 0:
args = ['install']
command = args[0]
method = METHODS.get(command)
try:
if method is None:
raise Error('Unknown command {}'.format(command))
method(command, args[1:])
except KeyboardInterrupt:
pass
except Error as e:
print(Style.red(str(e)))
exit(1)
METHODS = {
'install': cmd_instance,
'remove': cmd_instance,
'status': cmd_instance,
'pull': cmd_instance,
'search': cmd_search,
'purge': cmd_purge,
'path': cmd_path,
'help': cmd_help,
}
<file_sep>/setup.py
#!/usr/bin/env python
from setuptools import setup
install_requires=['toml']
setup(
name='norsu',
version='0.1',
packages=['norsu'],
license='PostgreSQL',
install_requires=install_requires,
entry_points={
'console_scripts': ['norsu = norsu.main:main']
}
)
| ef229f17b1d23c78a0ec3e3eacf2abc0a4a20331 | [
"Python"
]
| 5 | Python | Fenimorkin/norsu | 64946db38cefdc7a4c49cfbae089048378dfda24 | 7290a248835d7bef4f78241f8d8456b25fbd441f |
refs/heads/main | <file_sep>// using recursive method
package main
import "fmt"
func binarySearch(datalist []int, target int) (result int, searchCount int) {
mid := len(datalist) / 2
switch {
case len(datalist) == 0:
result = -1 // not found
case datalist[mid] > target:
result, searchCount = binarySearch(datalist[:mid], target)
case datalist[mid] < target:
result, searchCount = binarySearch(datalist[mid+1:], target)
if result >= 0 { // if anything but the -1 "not found" result
result += mid + 1
}
default: // a[mid] == search
result = mid // found
}
searchCount++
return
}
func main() {
numbers := []int{1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
target := 37
result, searchCount := binarySearch(numbers, target)
fmt.Printf("The number %d is found in position %d after %d steps.", target, result, searchCount)
}
<file_sep>package main
import "fmt"
func linearSearch(datalist []int, target int) bool {
for _, item := range datalist {
if item == target {
return true
}
}
return false
}
func main() {
numbers := []int{10, 14, 19, 26, 27, 31, 33, 35, 42, 44}
fmt.Println(linearSearch(numbers, 33))
}
<file_sep>// using built-in sort.Search()
package main
import (
"fmt"
"sort"
)
func main() {
datalist := []int{1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
target := 37
i := sort.Search(len(datalist), func(i int) bool { return datalist[i] >= target })
if i < len(datalist) && datalist[i] == target {
fmt.Printf("found %d at index %d", target, i)
} else {
fmt.Printf("%d not found", target)
}
}
<file_sep>package main
import (
"fmt"
"strings"
)
type Graph struct {
adjacency map[string][]string
}
func NewGraph() Graph {
return Graph{
adjacency: make(map[string][]string),
}
}
func (g *Graph) AddVertex(vertex string) bool {
if _, ok := g.adjacency[vertex]; ok {
fmt.Printf("vertex %v already exists\n", vertex)
return false
}
g.adjacency[vertex] = []string{}
return true
}
func (g *Graph) AddEdge(vertex, node string) bool {
if _, ok := g.adjacency[vertex]; !ok {
fmt.Printf("vertex %v does not exists\n", vertex)
return false
}
if ok := contains(g.adjacency[vertex], node); ok {
fmt.Printf("node %v already exists\n", node)
return false
}
g.adjacency[vertex] = append(g.adjacency[vertex], node)
return true
}
func (g Graph) CreatePath(firstNode, secondNode string) bool {
visited := g.createVisited()
var (
path []string
q []string
)
q = append(q, firstNode)
visited[firstNode] = true
for len(q) > 0 {
var currentNode string
currentNode, q = q[0], q[1:]
path = append(path, currentNode)
edges := g.adjacency[currentNode]
if contains(edges, secondNode) {
path = append(path, secondNode)
fmt.Println(strings.Join(path, "->"))
return true
}
for _, node := range g.adjacency[currentNode] {
if !visited[node] {
visited[node] = true
q = append(q, node)
}
}
}
fmt.Println("no link found")
return false
}
func (g Graph) createVisited() map[string]bool {
visited := make(map[string]bool, len(g.adjacency))
for key := range g.adjacency {
visited[key] = false
}
return visited
}
func contains(slice []string, item string) bool {
set := make(map[string]struct{}, len(slice))
for _, s := range slice {
set[s] = struct{}{}
}
_, ok := set[item]
return ok
}
func (g Graph) BFS(startingNode string) {
visited := g.createVisited()
var q []string
visited[startingNode] = true
q = append(q, startingNode)
for len(q) > 0 {
var current string
current, q = q[0], q[1:]
fmt.Println("BFS", current)
for _, node := range g.adjacency[current] {
if !visited[node] {
q = append(q, node)
visited[node] = true
}
}
}
}
func main() {
fmt.Println("--- Breadth First Search ---")
g := NewGraph()
g.AddVertex("Dhaka")
g.AddVertex("Savar")
g.AddVertex("Cumilla")
g.AddVertex("Narsingdi")
g.AddVertex("Sylhet")
g.AddEdge("Dhaka", "Savar")
g.AddEdge("Savar", "Dhaka")
g.AddEdge("Dhaka", "Narsingdi")
g.AddEdge("Narsingdi", "Dhaka")
g.AddEdge("Narsingdi", "Sylhet")
g.AddEdge("Sylhet", "Narsingdi")
g.AddEdge("Cumilla", "Dhaka")
g.BFS("Savar")
g.CreatePath("Savar", "Sylhet")
}
<file_sep># Data Structures & Algorithms with Go
Data Structures, Algorithms with Golang
## Searching Algorithms
### [Linear Search](searching/linear.go)
Linear search or sequential search sequentially checks each element of the list until a match is found or the whole list has been searched.

* Worst-case performance O(n)
* Best-case performance O(1)
* Average performance O(n/2)
### [Binary Search](searching/binary_1.go)
Binary search finds the position of a target value within a sorted array.
* The search process initiates by locating the middle element of the sorted array of data
* After that, the key value is compared with the element
* If the key value is smaller than the middle element, then searches analyses the upper values to the middle element for comparison and matching
* In case the key value is greater than the middle element then searches analyses the lower values to the middle element for comparison and matching
Binary Search Algorithm can be implemented in two ways:
1. [Iterative Method](searching/binary_2.go)
1. [Recursive Method](searching/binary_3.go)

* Worst-case performance O(log n)
* Best-case performance O(1)
* Average performance O(log n)
### [Depth First Search](searching/dfs.go)
Search algorithms are what allow us to traverse the entire graph or tree from a single starting point.
As the name suggests, Depth first search (DFS) algorithm starts with the initial node (source or starting node) of the graph, and then goes to deeper and deeper until we find the goal node or the node which has no children. The algorithm, then backtracks from the dead end towards the most recent node that is yet to be completely unexplored.
DFS uses Stack to find the shortest path.
DFS is faster than BFS.

* Worst-case performance O(V+E) where V is the number of vertexes and E is the number of edges
* Best-case performance O(1)
### [Breadth First Search](searching/bfs.go)
Breadth first search (BFS) algorithm starts with the initial node (source or starting node) of the graph, and explores all of the neighbor nodes at the present depth prior before moving on to the nodes at the next depth level.
BFS uses Queue to find the shortest path.

* Worst-case performance O(V+E) where V is the number of vertexes and E is the number of edges
* Best-case performance O(1)
### Jump Search
## Sorting Algorithms
### [Bubble Sort](sorting/bubble.go)
Bubble Sort compares all the element one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.

* Worst-case performance O(n^2)
* Best-case performance O(n)
* Average performance O(n^2)
### [Insertion Sort](sorting/insertion.go)

* Worst-case performance O(n^2)
* Best-case performance O(n)
* Average performance O(n^2)
### Selection Sort
### Heap Sort
### Quick Sort
### Merge Sort
### Counting Sort
## Recursive Algorithms
### Factorial
### Exponential
### Tower of hanoi
## Greedy Algorithms
### Huffman coding
### Fractional knapsack problem
### Activity Selection
### Job sequencing problem
## Types of Data Structures
<file_sep>// using iterative method
package main
import "fmt"
func binarySearch(datalist []int, target int) int {
start_index := 0
end_index := len(datalist) - 1
for start_index <= end_index {
mid := (start_index + end_index) / 2
if datalist[mid] < target {
start_index = mid + 1
} else {
end_index = mid - 1
}
}
if start_index == len(datalist) || datalist[start_index] != target {
return -1
} else {
return start_index
}
}
func main() {
numbers := []int{1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59}
target := 37
result := binarySearch(numbers, target)
fmt.Printf("The number %d is found in position %d.", target, result)
}
| 159327e63a2fbece923455ad7bc6a187ead068f7 | [
"Markdown",
"Go"
]
| 6 | Go | fatematzuhora/data-structures-algorithms-with-go | 4f5f877bf6efa7e79df1a387167ec98530710517 | 6abb98acf72027ee154f37efbea7ae4ac1ccac4c |
refs/heads/main | <repo_name>DameinCode/tech-culture-internship-2021<file_sep>/Week1/ToDo/3.js
function func(x) {
if (typeof(x) !== 'string') {
alert('It is not a STRING!')
}
else {
x = x.trim()
if(x.length > 30) {
x = x.substring(0, 31)
x += '...'
}
return x
}
}
let x = prompt('Enter string !')
if (isNaN(parseInt(x))) {
console.log(func(x))
}
else {
x = parseInt(x)
func(x)
}<file_sep>/README.md
# tech-culture-internship-2021
name: Gulbina
Uni: KBTU
Year of study: 2
<file_sep>/Week1/Tasks6_7/Task6/index.js
let books = document.querySelectorAll(".book")
const new_list = []
function newList() {
new_list.push(books[1].innerHTML)
new_list.push(books[0].innerHTML)
new_list.push(books[4].innerHTML)
new_list.push(books[3].innerHTML)
new_list.push(books[5].innerHTML)
new_list.push(books[2].innerHTML)
}
newList()
for(let i = 0; i < 6; i++) {
books[i].innerHTML = new_list[i]
}
function changeImage() {
document.body.style.backgroundImage = "url('C:/Users/user/Downloads/you-dont-know-js.jpg')"
}
changeImage()
books[2].querySelector("a").textContent = 'Книга 3. this и Прототипы Объектов'
document.querySelector(".adv").remove()
let array = books[4].querySelectorAll('li')
let new_array = []
new_array.push(array[9].innerText)
new_array.push(array[3].innerText)
new_array.push(array[4].innerText)
new_array.push(array[2].innerText)
new_array.push(array[6].innerText)
new_array.push(array[7].innerText)
array[2].innerText = new_array[0]
array[3].innerText = new_array[1]
array[4].innerText = new_array[2]
array[6].innerText = new_array[3]
array[7].innerText = new_array[4]
array[9].innerText = new_array[5]
let array2 = books[1].querySelectorAll('li')
let new_array2 = []
new_array2.push(array2[6].innerText)
new_array2.push(array2[8].innerText)
new_array2.push(array2[4].innerText)
new_array2.push(array2[5].innerText)
array2[4].innerText = new_array2[0]
array2[5].innerText = new_array2[1]
array2[6].innerText = new_array2[2]
array2[8].innerText = new_array2[3]
let array3 = books[5].querySelectorAll('li')
array3[9].innerText = "Глава 8: За пределами ES6"
let li = document.createElement("li");
li.appendChild(document.createTextNode("Приложение A: Благодарности!"))
books[5].querySelector('ul').appendChild(li)<file_sep>/Week1/ToDo/4.js
let arr = ['1234', '4567', '9089', '2222', '23456', '67895', '45678']
const result = arr.filter(ar => ar[0] === '2' || ar[0] === '4');
console.log(result)
let ans = []
function isPrime(x) {
let i = 2
while (i*i <= x) {
if(x % i == 0){
return false
}
i += 1
}
return true
}
for (let i = 2; i < 100; i++) {
if(isPrime(i) === true) {
console.log(i,"Делители этого числа:", 1,"и", i)
}
}
<file_sep>/Week1/Tasks6_7/Task7/index.js
class DomElement {
selector = ''
height = 0
width = 0
bg = ''
fontSize = 0
constructor() {}
createElement(selector, height, width, bg, fontSize) {
this.selector = selector
this.height = height
this.width = width
this.bg = bg
this.fontSize = fontSize
if(this.selector[0] === '.') {
let newDiv = document.createElement("div")
newDiv.innerHTML = "<h1>Привет!</h1>"
newDiv.style.cssText = 'height: ' + this.height + 'px' + ';' + 'width: ' + this.width + 'px' + ';' + 'background: '+ this.bg + ';' + 'font-size: ' + this.fontSize + 'px' +';'
document.body.appendChild(newDiv)
}
else if (this.selector[0] === '#') {
let newDiv = document.createElement("p")
newDiv.style.cssText = 'height: ' + this.height + 'px' + ';' + 'width: ' + this.width + 'px' + ';' + 'background: '+ this.bg + ';' + 'font-size: ' + this.fontSize + 'px' +';'
newDiv.innerHTML = "Привет!"
document.body.appendChild(newDiv)
}
}
}
new DomElement().createElement('.elem', 15, 30, 'red', 5)
new DomElement().createElement('#elem', 15, 30, 'red', 5)
<file_sep>/Week1/ToDo/5.js
const week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sanday']
const todayDay = new Date();
let nw = document.createElement('div')
getAnswer()
function getAnswer() {
week.forEach((item, i) => {
nw = document.createElement('div')
if (i === todayDay.getDay()-1) {
nw.classList.add('bold')
nw.textContent = week[i]
}
if (week[i] == 'Saturday' || week[i] == 'Sanday') {
nw.classList.add('cursiv')
nw.textContent = week[i]
}
else {
nw.textContent = week[i]
}
document.getElementById("days").appendChild(nw)
})
}<file_sep>/dist/dist/js/index.js
const chooseClub = document.querySelector('.chooseClub')
const openPopup = document.getElementsByTagName('a')[3]
const callBack = document. querySelector('.callback-btn')
const present = document.querySelector('.fixed-gift')
const closeBtn = document.getElementsByTagName('button')[7]
const changeSlide = document.querySelector('.services-slider')
const slides = document.querySelector('.services-slider').childNodes
const photoSlide = document.querySelector('.gallery-slider ').childNodes
const portfolioDots = document.querySelector('.portfolio-dots').childNodes
let cntSlide = 6
let cur = cntSlide
let start = false
photoSlide[11].removeAttribute('href')
photoSlide[13].removeAttribute('href')
changeSlide.childNodes[21].removeAttribute('href')
changeSlide.childNodes[23].removeAttribute('href')
openPopup.style.color = '#ffffff'
openPopup.style.textDecoration = 'none'
let hidePresent = false
chooseClub.addEventListener('click', () => {
if (document.querySelector('.bodies').style.display === 'none') {
document.querySelector('.bodies').style.display = 'block'
}
else {
document.querySelector('.bodies').style.display = 'none'
}
})
// open modal
callBack.addEventListener('click', () => {
document.querySelector('#callback_form').style.display = 'block'
})
document.addEventListener('click', (event) => {
if (event.target.className == "close_icon") {
document.querySelector('#callback_form').style.display = 'none'
}
})
// close modals
document.addEventListener('click', (event) => {
if (event.target.className === "close_icon") {
document.querySelector('#free_visit_form').style.display = 'none'
if(document.querySelector('#gift') !== null) {
document.querySelector('#gift').style.display = 'none'
}
}
})
if (closeBtn !== undefined) {
closeBtn.addEventListener('click', () => {
document.querySelector('#gift').style.display = 'none'
})
}
// open popup
openPopup.addEventListener('click', () => {
document.querySelector('#free_visit_form').style.display = 'block'
})
// hide gist and open modal
if (present !== null) {
present.addEventListener('click', () => {
if (hidePresent === false) {
present.style.display = 'none'
document.querySelector('#gift').style.display = 'block'
hidePresent = true
}
})
}
function sliderMain() {
let left = document.createElement('div')
left.innerHTML =
document.querySelector('.main-slider').appendChild()
}
changeSlide.addEventListener('click', (event)=>{
if (event.target.className === 'portfolio-btn next') {
let temp = slides[1].innerHTML
for (let i = 1; i < 9; i++) {
if (i%2 !== 0 ) {
slides[i].innerHTML = slides[i+2].innerHTML
}
}
slides[9].innerHTML = temp
if(window.stop !== undefined) {
window.stop();
} else if (document.execCommand !== undefined) { // для IE
document.execCommand("Stop", false);
}
}
else if (event.target.className === 'portfolio-btn prev') {
let temp2 = slides[9].innerHTML
for (let i = 9; i > 1; i--) {
if (i%2 !== 0 ) {
slides[i].innerHTML = slides[i-2].innerHTML
}
}
slides[1].innerHTML = temp2
if(window.stop !== undefined) {
window.stop();
} else if (document.execCommand !== undefined) { // для IE
document.execCommand("Stop", false);
}
}
})
function changeSlides(cur) {
photoSlide[cntSlide*2 - 1].classList.add("slide-active")
photoSlide[cur*2 - 1].classList.remove("slide-active")
portfolioDots[cntSlide*2 - 1].classList.add("dot-active")
portfolioDots[cur*2 - 1].classList.remove("dot-active")
}
photoSlide[11].addEventListener('click', () => {
if (! start) {
cntSlide = 6
start = true
}
cur = cntSlide === 6 ? 1 : cntSlide
if (cntSlide === 1) {
cntSlide = 6
}
cntSlide --
changeSlides(cur)
})
photoSlide[13].addEventListener('click', () => {
if (! start) {
cntSlide = 1
start = true
}
cur = cntSlide === 0 ? 5 : cntSlide
if (cntSlide === 5) {
cntSlide = 0
}
cntSlide ++
changeSlides(cur)
})
portfolioDots[1].addEventListener('click', () => {
cur = cntSlide
if (! start ) {
cur = 1
start = true
}
cntSlide = 1
changeSlides(cur)
})
portfolioDots[3].addEventListener('click', () => {
cur = cntSlide
if (! start ) {
cur = 1
start = true
}
cntSlide = 2
changeSlides(cur)
})
portfolioDots[5].addEventListener('click', () => {
cur = cntSlide
if (! start ) {
cur = 1
start = true
}
cntSlide = 3
changeSlides(cur)
})
portfolioDots[7].addEventListener('click', () => {
cur = cntSlide
if (! start ) {
cur = 1
start = true
}
cntSlide = 4
changeSlides(cur)
})
portfolioDots[9].addEventListener('click', () => {
cur = cntSlide
if (! start ) {
cur = 1
start = true
}
cntSlide = 5
changeSlides(cur)
})
<file_sep>/dist/dist/js/ajax.js
const xhr = new XMLHttpRequest()
const formItems = document.getElementById('banner-form').elements
// xhr.onload = function() {
// const submitBtn = document.getElementById('banner-form')
// console.log(submitBtn)
// }
const submitBtn = document.querySelector('#banner-form')
submitBtn.action = "server.php"
let toSend = { }
submitBtn.addEventListener('click', (event)=> {
if(event.target.className === 'btn') {
toSend = {
}
}
})
//
// const requestURL = 'https://jsonplaceholder.typicode.com/users'
//
// function sendRequest(method, url, body = null) {
// const headers = {
// 'Content-Type': 'application/json'
// }
//
// return fetch(url, {
// method: method,
// body: JSON.stringify(body),
// headers: headers
// }).then(response => {
// if (response.ok) {
// return response.json()
// }
//
// return response.json().then(error => {
// const e = new Error('Что-то пошло не так')
// e.data = error
// throw e
// })
// })
// }
//
// sendRequest('GET', requestURL)
// .then(data => console.log(data))
// .catch(err => console.log(err))
//
// const body = {
// name: 'Vladilen',
// age: 26
// }
//
// sendRequest('POST', requestURL, body)
// .then(data => console.log(data))
// .catch(err => console.log(err))
//
// JavaScript XMLHttpRequest.js
// const requestURL = 'https://jsonplaceholder.typicode.com/users'
//
// function sendRequest(method, url, body = null) {
// return new Promise((resolve, reject) => {
// const xhr = new XMLHttpRequest()
//
// xhr.open(method, url)
//
// xhr.responseType = 'json'
// xhr.setRequestHeader('Content-Type', 'application/json')
//
// xhr.onload = () => {
// if (xhr.status >= 400) {
// reject(xhr.response)
// } else {
// resolve(xhr.response)
// }
// }
//
// xhr.onerror = () => {
// reject(xhr.response)
// }
//
// xhr.send(JSON.stringify(body))
// })
// }
//
// sendRequest('GET', requestURL)
// .then(data => console.log(data))
// .catch(err => console.log(err))
//
// const body = {
// name: 'Vladilen',
// age: 26
// }
//
// sendRequest('POST', requestURL, body)
// .then(data => console.log(data))
// .catch(err => console.log(err))
<file_sep>/dist/dist/js/calculator.js
localStorage.setItem('mozaika', JSON.stringify({'month1': 2999, 'month6': 14990, 'month9': 21990, 'month12': 14990}))
localStorage.setItem('schelkovo', JSON.stringify({'month1': 2999, 'month6': 14990, 'month9': 21990, 'month12': 14990}))
let mozaika = document.getElementById("card_leto_mozaika")
let schelkovo = document.getElementById("card_leto_schelkovo")
const promo = document.querySelector('.price-message').firstChild
const checkPhoneNumber = document.getElementById('callback_form-phone')
const priceTotal = document.querySelector('#price-total')
const checkSubmit = document.getElementById('check2')
let correctPromo = false
let m1 = document.getElementById("m1")
let m2 = document.getElementById("m2")
let m3 = document.getElementById("m3")
let m4 = document.getElementById("m4")
let isCreated = false
let type = 'mozaika'
checkSubmit.disabled = true
console.log(checkSubmit)
let price = 1999
mozaika.addEventListener('change', function() {
if (mozaika.checked) {
type = 'mozaika'
}
})
schelkovo.addEventListener('change', function() {
if (schelkovo.checked) {
type = 'schelkovo'
}
})
m1.addEventListener('change', () => {
if (m1.checked) {
price = JSON.parse(localStorage.getItem(type)).month1
if (correctPromo) {
price -= price*0.3
}
priceTotal.textContent = (Math.round(price)).toString()
}
})
m2.addEventListener('change', () => {
if (m2.checked) {
price = JSON.parse(localStorage.getItem(type)).month6
if (correctPromo) {
price -= price*0.3
}
priceTotal.textContent = (Math.round(price)).toString()
}
})
m3.addEventListener('change', () => {
if (m3.checked) {
price = JSON.parse(localStorage.getItem(type)).month9
if (correctPromo) {
price -= price*0.3
}
priceTotal.textContent = (Math.round(price)).toString()
}
})
m4.addEventListener('change', () => {
if (m4.checked) {
price = JSON.parse(localStorage.getItem(type)).month12
if (correctPromo) {
price -= price*0.3
}
priceTotal.textContent = (Math.round(price)).toString()
}
})
promo.addEventListener('change', () => {
if (promo.value === "ТЕЛО2019") {
correctPromo = true
price -= price*0.3
priceTotal.textContent = (Math.round(price)).toString()
} else {
correctPromo = false
}
})
function isNumbers(str) {
for (let i = 0; i < str.length; i++) {
if (! isNaN(parseInt(str[i])) || str[0] === '+') {
continue
}
if (isNaN(parseInt(str[i]))) {
return false
}
}
return true
}
function checkPhone() {
if (checkPhoneNumber.value.trim() === '' || (!isNumbers(checkPhoneNumber.value))) {
if (! isCreated) {
let div = document.querySelector('#card_order')
let aler = document.createElement('div')
aler.innerHTML = "<strong>! Введите</strong> правильный номер."
aler.className = "phone-error"
aler.style.color = "#ffffff"
aler.style.backgroundColor = "#ffd11a"
aler.style.width = "210px"
aler.style.padding = "1%"
div.insertBefore(aler, document.querySelector('#card_order').childNodes[15])
isCreated = true
return div
} else {
return 1
}
} return 0
}
checkPhoneNumber.addEventListener('change', () => {
let div = checkPhone()
if (div === 0 && isCreated) {
document.querySelector('.phone-error').remove()
isCreated = false
}
})
| d54380c2a05b34eba69ecbcdbf02354fd3bf28cc | [
"JavaScript",
"Markdown"
]
| 9 | JavaScript | DameinCode/tech-culture-internship-2021 | 45fef593aeb872da0862bf53db708c827fc86bf3 | b3c8d274edbd1cd5c8141d67bf931b8f4004c769 |
refs/heads/master | <file_sep>#include "config.h"
#include "debug.h"
#include "string.h"
#include "uart.h"
const char* cfg_area_status_names[] = {
"empty",
"dirty",
"open",
"modified",
"closed",
"completed"
};
static inline unsigned char cfg_type2tag(struct cfg_type const* t)
{
return t ? t - g_cfg_types : ~0;
}
static struct cfg_type const* cfg_get_obj_type(struct cfg_obj_header const* h)
{
if (h->type_tag > g_cfg_ntypes)
return 0;
return &g_cfg_types[h->type_tag];
}
static inline unsigned cfg_obj_data_size_unaligned_(struct cfg_type const* t, unsigned char str_sz)
{
return t->str ? str_sz + 1 : sizeof(int);
}
static inline unsigned cfg_obj_data_size_(struct cfg_type const* t, unsigned char str_sz)
{
if (!t) {
return 0;
} else if (t->str) {
unsigned sz = str_sz + 1;
if (sz & 1) sz += 1;
return sz;
} else
return sizeof(int);
}
static inline unsigned cfg_obj_data_size(struct cfg_type const* t, struct cfg_obj_header const* h)
{
return cfg_obj_data_size_(t, h->j_sz);
}
// Returns the size of the object representation including header and footer
static inline unsigned cfg_obj_size_(struct cfg_type const* t, struct cfg_obj_header const* h)
{
return sizeof(struct cfg_obj_header) + cfg_obj_data_size(t, h) + sizeof(struct cfg_obj_footer);
}
static inline unsigned cfg_obj_size(struct cfg_obj_header const* h)
{
return cfg_obj_size_(cfg_get_obj_type(h), h);
}
static inline void cfg_init_hdr(struct cfg_type const* t, struct cfg_obj_header* h, int i, int j)
{
h->type_tag = cfg_type2tag(t);
h->j_sz = j;
h->i = i;
}
static inline int cfg_is_status_tag(struct cfg_obj_header const* h)
{
return !(unsigned char)~h->type_tag;
}
// Check if 2 objects represents different versions of the same object instance
static inline int cfg_same_instance(struct cfg_type const* t, struct cfg_obj_header const* h, struct cfg_obj_header const* h_)
{
if (h->type_tag != h_->type_tag)
return 0;
return t->str ? h->i == h_->i : h->ij == h_->ij;
}
static inline struct config_area* cfg_active_area(struct config* cfg)
{
int a = cfg->active_area;
BUG_ON(a < 0);
return &cfg->area[a];
}
static void cfg_erase_area(struct config* cfg, signed char a)
{
struct config_area* ar = &cfg->area[a];
flash_erase(ar->storage, CFG_BUFF_SEGS);
ar->used_bytes = 0;
ar->crc = CRC16_INIT;
ar->status = area_empty;
ar->invalid = 0;
}
static inline void cfg_erase_all(struct config* cfg)
{
cfg_erase_area(cfg, 0);
cfg_erase_area(cfg, 1);
cfg->active_area = 0;
}
static int cfg_is_area_clean(struct config* cfg, signed char a)
{
struct config_area* ar = &cfg->area[a];
unsigned const* ptr = (unsigned const*)(ar->storage + ar->used_bytes);
unsigned const* end = (unsigned const*)(ar->storage + CFG_BUFF_SIZE);
for (; ptr < end; ++ptr) {
if (~*ptr)
return 0;
}
return 1;
}
static void cfg_chk_area(struct config* cfg, signed char a)
{
struct config_area* ar = &cfg->area[a];
char const *ptr, *ptr_, *end;
ar->crc = CRC16_INIT;
ar->status = area_empty;
for (ptr = ar->storage, end = ptr + CFG_BUFF_SIZE; ptr < end; ptr = ptr_)
{
unsigned sz;
struct cfg_obj_footer const* f;
struct cfg_obj_header const* h = (struct cfg_obj_header const*)ptr;
struct cfg_type const* t = cfg_get_obj_type(h);
if (!t) {
if ((unsigned char)~h->type_tag)
goto invalid;
if (!(unsigned char)~h->ij) // header is all ones
break;
}
sz = cfg_obj_size_(t, h);
ptr_ = ptr + sz;
if (ptr_ > end)
goto invalid;
f = (struct cfg_obj_footer const*)ptr_ - 1;
ar->crc = crc16_up_buff(ar->crc, ptr, sz - sizeof(*f));
if (f->crc != ar->crc)
goto invalid;
if (!t) {
switch (h->ij) {
case area_open:
if (ar->status != area_empty && ar->status != area_dirty)
goto invalid_status;
ar->status = area_open;
break;
case area_closed:
if (ar->status != area_open && ar->status != area_modified)
goto invalid_status;
ar->status = area_closed;
break;
case area_completed:
if (ar->status != area_closed && ar->status != area_empty)
goto invalid_status;
ar->status = area_completed;
break;
default:
goto invalid_status;
}
} else {
if (ar->status > area_modified)
goto invalid_status;
switch (ar->status) {
case area_empty:
ar->status = area_dirty;
break;
case area_open:
ar->status = area_modified;
break;
}
}
continue;
invalid_status:
DBG_BUG();
invalid:
ar->invalid = 1;
break;
}
ar->used_bytes = ptr - ar->storage;
BUG_ON(ar->used_bytes > CFG_BUFF_SIZE);
if (!ar->invalid && !cfg_is_area_clean(cfg, a))
ar->invalid = 1;
}
static int cfg_has_instance(struct config* cfg, struct cfg_obj_header const* h, unsigned range)
{
char const *ptr = cfg_active_area(cfg)->storage, *end = ptr + range;
struct cfg_type const* t = cfg_get_obj_type(h);
while (ptr < end) {
struct cfg_obj_header const* h_ = (struct cfg_obj_header const*)ptr;
if (cfg_same_instance(t, h, h_))
return 1;
ptr += cfg_obj_size(h_);
}
return 0;
}
// Enumerate objects
void cfg_enum(struct config* cfg, cfg_enum_cb cb)
{
struct config_area const* ar = cfg_active_area(cfg);
unsigned used_bytes = ar->used_bytes;
if (!used_bytes)
return;
// We are going to find all latest versions of all objects
// and do it exactly once
char const *ptr = ar->storage, *end = ptr + used_bytes, *next_ptr = 0, *ptr_;
for (; ptr; ptr = next_ptr)
{
unsigned processed_range = ptr - ar->storage;
struct cfg_obj_header const* h = (struct cfg_obj_header const*)ptr;
struct cfg_type const* t = cfg_get_obj_type(h);
ptr += cfg_obj_size_(t, h);
if (!t) { // skip status tags
next_ptr = ptr < end ? ptr : 0;
continue;
}
struct cfg_obj_footer const* f = (struct cfg_obj_footer const*)ptr - 1;
// Find latest version of the selected instance and find
// the next unprocessed instance
for (next_ptr = 0; ptr < end; ptr = ptr_)
{
struct cfg_obj_header const* h_ = (struct cfg_obj_header const*)ptr;
ptr_ = ptr + cfg_obj_size(h_);
BUG_ON(ptr_ > end);
if (cfg_is_status_tag(h_)) {
continue;
}
if (cfg_same_instance(t, h, h_)) {
// more recent version
struct cfg_obj_footer const* f_ = (struct cfg_obj_footer const*)ptr_ - 1;
h = h_;
f = f_;
continue;
}
if (!next_ptr && !cfg_has_instance(cfg, h_, processed_range)) {
// next unprocessed instance
next_ptr = ptr;
}
}
cb(cfg, t, h, f);
}
}
// The space is reserved for closed + completed records
#define CFG_RESERVED_SPACE (2*(sizeof(struct cfg_obj_header)+sizeof(struct cfg_obj_footer)))
// Append value to the current area. Returns written object size on success, 0 if no space left.
static unsigned cfg_write(
struct config* cfg, int a,
const struct cfg_type* t,
void const* pval,
unsigned char i,
unsigned char j
)
{
unsigned val_sz = cfg_obj_data_size_(t, j);
unsigned sz = sizeof(struct cfg_obj_header) + val_sz + sizeof(struct cfg_obj_footer);
struct config_area* ar = &cfg->area[a];
BUG_ON(ar->invalid);
BUG_ON(ar->used_bytes > CFG_BUFF_SIZE);
if (ar->used_bytes + sz > (t ? CFG_BUFF_SIZE-CFG_RESERVED_SPACE : CFG_BUFF_SIZE))
return 0;
const char* ptr = ar->storage + ar->used_bytes;
struct cfg_obj_footer f;
struct cfg_obj_header h;
cfg_init_hdr(t, &h, i, j);
flash_write((unsigned*)ptr, (unsigned const*)&h, sizeof(h));
ar->crc = crc16_up_buff(ar->crc, &h, sizeof(h));
ptr += sizeof(h);
if (val_sz) {
unsigned val_sz_ = cfg_obj_data_size_unaligned_(t, j);
flash_write((unsigned*)ptr, (unsigned const*)pval, val_sz_);
ar->crc = crc16_up_buff(ar->crc, pval, val_sz_);
ptr += val_sz;
if (val_sz_ & 1)
ar->crc = crc16_up(ar->crc, 0xff);
ar->status = ar->status < area_open ? area_dirty : area_modified;
}
f.crc = ar->crc;
flash_write((unsigned*)ptr, (unsigned const*)&f, sizeof(f));
ar->used_bytes += sz;
return sz;
}
static void cfg_commit_status(struct config* cfg, int a, cfg_area_status_t st)
{
unsigned res;
if (cfg->area[a].invalid || cfg->area[a].status >= st)
return;
res = cfg_write(cfg, a, 0, 0, st, 0);
BUG_ON(!res);
cfg->area[a].status = st;
}
void cfg_chkpt_cb(struct config* cfg, struct cfg_type const* t, struct cfg_obj_header const* h, struct cfg_obj_footer const* f)
{
// write it to snapshot
int a = cfg->active_area;
unsigned res = cfg_write(cfg, a ^ 1, t, h + 1, h->i, h->j_sz);
BUG_ON(!res);
}
// Checkpoint storage.
// Make the snapshot of the active area onto the inactive one and make them active
static void cfg_chkpt(struct config* cfg)
{
BUG_ON(cfg->active_area < 0);
int old_a = cfg->active_area, new_a = old_a ^ 1;
BUG_ON(cfg->area[old_a].status < area_open);
cfg_commit_status(cfg, old_a, area_closed);
cfg_erase_area(cfg, new_a);
cfg_enum(cfg, cfg_chkpt_cb);
cfg_commit_status(cfg, new_a, area_open);
cfg_commit_status(cfg, old_a, area_completed);
cfg->active_area = new_a;
}
static unsigned cfg_put(
struct config* cfg,
const struct cfg_type* t,
void const* pval,
unsigned char i,
unsigned char j_sz
)
{
unsigned res;
int a = cfg->active_area;
BUG_ON(a < 0);
res = cfg_write(cfg, cfg->active_area, t, pval, i, j_sz);
if (res)
return res;
// Free space by check pointing
cfg_chkpt(cfg);
return cfg_write(cfg, cfg->active_area, t, pval, i, j_sz);
}
static inline int cfg_select_active_area(struct config* cfg)
{
// area has no usable data
if (cfg->area[1].status < area_open)
return 0;
if (cfg->area[0].status < area_open)
return 1;
// area successfully open
if (cfg->area[0].status < area_closed)
return 0;
if (cfg->area[1].status < area_closed)
return 1;
// in the middle of checkpoint
if (cfg->area[0].status == area_closed)
return 0;
if (cfg->area[1].status == area_closed)
return 1;
// checkpoint completed
if (cfg->area[1].status == area_completed)
return 0;
if (cfg->area[0].status == area_completed)
return 1;
BUG(); // Should never hit
return -1;
}
void cfg_init(struct config* cfg)
{
cfg_chk_area(cfg, 0);
cfg_chk_area(cfg, 1);
// Choose active area
cfg->active_area = cfg_select_active_area(cfg);
if (cfg->active_area < 0 || cfg->area[cfg->active_area].status < area_open) {
// Prepare active area if necessary
cfg_erase_all(cfg);
cfg_commit_status(cfg, cfg->active_area, area_open);
cfg_commit_status(cfg, cfg->active_area^1, area_completed);
}
else if (
cfg->area[cfg->active_area].status != area_open ||
cfg->area[cfg->active_area^1].status != area_completed ||
cfg->area[cfg->active_area].invalid
) {
// Stabilize storage
cfg_chkpt(cfg);
}
// Erase failed inactive area
if (cfg->area[cfg->active_area^1].invalid)
cfg_erase_area(cfg, cfg->active_area^1);
// We should never start from invalid active area
BUG_ON(cfg->area[cfg->active_area].invalid);
}
// Lookup value in storage
static void const* cfg_lookup(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j)
{
void const* obj = 0;
struct config_area* ar = cfg_active_area(cfg);
char const *ptr = ar->storage, *end = ptr + ar->used_bytes;
struct cfg_obj_header h;
BUG_ON(j && t->str);
cfg_init_hdr(t, &h, i, j);
while (ptr < end) {
struct cfg_obj_header const* h_ = (struct cfg_obj_header const*)ptr;
if (cfg_same_instance(t, &h, h_)) {
obj = h_ + 1;
}
ptr += cfg_obj_size(h_);
}
return obj;
}
// Lookup value in storage and return default if not found
int cfg_get_val_(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j)
{
BUG_ON(t->str);
BUG_ON(i && t->nind < 1);
BUG_ON(j && t->nind < 2);
void const* ptr = cfg_lookup(cfg, t, i, j);
if (ptr)
return *(int const*)ptr;
return def_cfg_val(t);
}
const char* cfg_get_str_(struct config* cfg, const struct cfg_type* t, unsigned char i)
{
BUG_ON(!t->str);
BUG_ON(i && t->nind < 1);
void const* ptr = cfg_lookup(cfg, t, i, 0);
if (ptr)
return (char const*)ptr;
return def_cfg_str(t);
}
// Put value to the storage. Returns 0 on success, -1 if no space left on the storage.
int cfg_put_val_(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j, int val)
{
BUG_ON(t->str);
BUG_ON(i && t->nind < 1);
BUG_ON(j && t->nind < 2);
if (cfg_put(cfg, t, &val, i, j))
return 0;
return -1; // Out of space
}
// Put zero-terminated string to the storage. If string length exceeds MAX_CFG_STR_LEN the -1 will be returned.
int cfg_put_str_(struct config* cfg, const struct cfg_type* t, unsigned char i, const char* str)
{
BUG_ON(!t->str);
BUG_ON(i && t->nind < 1);
unsigned sz = strlen(str);
if (sz > MAX_CFG_STR_LEN)
return -1; // String too long
if (cfg_put(cfg, t, str, i, sz))
return 0;
return -1; // Out of space
}
<file_sep>#pragma once
#include "io430.h"
#define UART_BUFF_SZ 32
typedef void (*uart_rx_cb)(char);
struct uart_ctx {
char tx_buff[UART_BUFF_SZ];
char rx_buff[UART_BUFF_SZ];
unsigned char tx_len;
unsigned char tx_curr;
unsigned char rx_len;
uart_rx_cb rx_cb;
};
extern struct uart_ctx g_uart;
static inline void uart_init()
{
// Configure UART
P1SEL |= BIT1|BIT2; // P1.1=RXD P1.2=TXD
P1SEL2 |= BIT1|BIT2;
UCA0CTL1 |= UCSSEL_2; // SMCLK
UCA0BR0 = 104; // 1MHz 9600
UCA0BR1 = 0;
UCA0MCTL = UCBRS0; // Modulation UCBRSx = 1
UCA0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
}
static inline void uart_wait()
{
while (g_uart.tx_curr < g_uart.tx_len || (UCA0STAT & UCBUSY))
__no_operation();
}
// Send current TX buffer asynchronously (no more than UART_BUFF_SZ)
void uart_send_start();
// Send string asynchronously.
void uart_send_str_async(const char* str);
// Send string to UART. Strings of length <= UART_BUFF_SZ
// will be sent without blocking.
void uart_send_str(const char* str);
// Formatted output
void uart_print_i(int n);
void uart_print_x(unsigned n);
// Start/stop receiving.
void uart_receive_enable(uart_rx_cb cb);
<file_sep>#pragma once
// ASCII <-> number conversions
int a2i(const char* str);
int i2a(int n, char* buff);
int x2a(unsigned n, char* buff);
static inline int i2az(int n, char* buff)
{
int r = i2a(n, buff);
buff[r] = 0;
return r;
}
static inline int x2az(unsigned n, char* buff)
{
int r = x2a(n, buff);
buff[r] = 0;
return r;
}
<file_sep>#pragma once
#include "io430.h"
typedef void (*wdt_cb)(unsigned);
struct wdt_clnt {
wdt_cb cb;
struct wdt_clnt* next;
};
struct wdt_ctx {
unsigned clk;
struct wdt_clnt* clients;
};
extern struct wdt_ctx g_wdt;
static inline void wdt_timer_subscribe(struct wdt_clnt *c)
{
c->next = g_wdt.clients;
g_wdt.clients = c;
}
static inline void wdt_hold()
{
// Stop watchdog timer to prevent time out reset
WDTCTL = WDTPW + WDTHOLD;
}
static inline void wdt_timer_init()
{
// SMCLK / 32768 (32msec for 1MHz clock)
WDTCTL = WDTPW + WDTTMSEL + WDTCNTCL;
IE1 |= WDTIE;
}
<file_sep>#pragma once
#define CRC16_INIT 0xffff
#define CRC16_CHK_STR "123456789"
#define CRC16_CHK_VALUE 0x6F91
typedef unsigned short crc16_t;
crc16_t crc16_up(crc16_t crc, unsigned char data);
crc16_t crc16_up_buff(crc16_t crc, const void* data, unsigned len);
crc16_t crc16_str(const char* str);
<file_sep>#pragma once
#include "io430.h"
static inline void init_clock()
{
// MCLK=SMCLK=1MHz
BCSCTL1 = CALBC1_1MHZ;
DCOCTL = CALDCO_1MHZ;
}
<file_sep>//
// Configuration auto test
//
#include "io430.h"
#include "init.h"
#include "wdt.h"
#include "cli.h"
#include "uart.h"
#include "cfg.h"
#include "aconv.h"
#include "debug.h"
#include "uart.h"
#include "crc16.h"
#define M 16
unsigned ttl = 100;
unsigned last_clk;
// To simulate power failure we connect P1.6 to ground and
// pass VCC through 510 ohm resistor
void power_failure()
{
#ifdef SIMULATE_PW_FAIL
P1DIR |= BIT6;
P1OUT |= BIT6;
#endif
}
void wdtcb(unsigned clk)
{
if (clk > ttl)
dbg_reset();
else if (clk >= ttl)
power_failure();
last_clk = clk;
}
struct wdt_clnt wdtc = {wdtcb};
int last_sys[M], last_usr[M];
static int verify_array(const struct cfg_type* ta)
{
int i;
int sys_min, sys_max, usr_min, usr_max;
for (i = 0; i < M; ++i) {
int sys = cfg_get_val_i(&cfg_system, ta, i);
int usr = cfg_get_val_i(&cfg_user, ta, i);
last_sys[i] = sys;
last_usr[i] = usr;
if (!i) {
sys_min = sys_max = sys;
usr_min = usr_max = usr;
} else {
BUG_ON(sys - last_sys[i-1] > 0);
BUG_ON(usr - last_usr[i-1] > 0);
if (sys - sys_max > 0) sys_max = sys;
if (sys - sys_min < 0) sys_min = sys;
if (usr - usr_max > 0) usr_max = usr;
if (usr - usr_min < 0) usr_min = usr;
}
}
BUG_ON(sys_max - sys_min < 0);
BUG_ON(sys_max - sys_min > 1);
BUG_ON(usr_max - usr_min < 0);
BUG_ON(usr_max - usr_min > 1);
BUG_ON(sys_max != sys_min && usr_max != usr_min);
BUG_ON(sys_max - usr_max > 1);
BUG_ON(sys_max - usr_max < 0);
if (sys_max != sys_min) {
for (i = 0; i < M; ++i)
cfg_put_val_i(&cfg_system, ta, i, sys_max);
}
if (usr_max != usr_min) {
for (i = 0; i < M; ++i)
cfg_put_val_i(&cfg_user, ta, i, usr_max);
}
if (sys_max - usr_max > 0) {
for (i = 0; i < M; ++i)
cfg_put_val_i(&cfg_user, ta, i, sys_max);
}
return sys_max;
}
static void update_array(const struct cfg_type* ta, int v)
{
int i;
for (i = 0; i < M; ++i)
cfg_put_val_i(&cfg_system, ta, i, v);
for (i = 0; i < M; ++i)
cfg_put_val_i(&cfg_user, ta, i, v);
}
static void test_init()
{
init_clock();
wdt_timer_init();
wdt_timer_subscribe(&wdtc);
uart_init();
__enable_interrupt();
dbg_init();
cfg_init_all();
cli_init();
}
static void test_print(const char* str)
{
uart_send_str(str);
uart_send_str("\r");
uart_wait();
}
void main( void )
{
const struct cfg_type* t;
const char* str;
int v, n, sz;
char buff[7];
test_init();
BUG_ON(crc16_str(CRC16_CHK_STR) != CRC16_CHK_VALUE);
//
// Update run counter
//
t = get_cfg_type("test.runs");
BUG_ON(!t);
n = cfg_get_val(&cfg_system, t);
cfg_put_val(&cfg_system, t, n + 1);
//
// Testing string value
//
t = get_cfg_type("test.str");
BUG_ON(!t);
str = cfg_get_str_i(&cfg_system, t, 0);
test_print(str);
v = a2i(str);
BUG_ON(v != n && v != n - 1);
sz = i2az(n + 1, buff);
BUG_ON(sz >= sizeof(buff));
cfg_put_str_i(&cfg_system, t, 0, buff);
//
// The following value is written only once
// It helps to test sequence numbering scheme
//
t = get_cfg_type("test.static");
BUG_ON(!t);
v = cfg_get_val(&cfg_system, t);
if (!v) {
BUG_ON(n);
cfg_put_val(&cfg_system, t, 1);
}
//
// Now testing value array
//
t = get_cfg_type("test.arr");
BUG_ON(!t);
v = verify_array(t);
//
// Schedule suicide
//
ttl = last_clk + ((unsigned)n * 27361) % 61;
//
// Update test array in a loop
//
for (;;)
{
cli_process();
update_array(t, ++v);
if (!(v & 0xf))
cfg_init_all();
}
}
<file_sep>#include "cfg.h"
#include "cfg_cli.h"
#include "cfg_types.h"
#include "debug.h"
#include "uart.h"
#include "aconv.h"
#include "string.h"
static void (*cfg_cli_complete_cb)() = 0;
#define BUFF_SZ MAX_CFG_STR_LEN
struct cfg_set_ctx {
struct config* cfg;
struct cfg_type const* type;
unsigned char ind[2];
unsigned char nind;
union {
int val;
char buff[BUFF_SZ+1];
};
};
static struct cfg_set_ctx set_ctx;
static void print_cfg_ind(int i)
{
uart_send_str("[");
uart_print_i(i);
uart_send_str("]");
}
static void print_cfg_val(int val)
{
uart_send_str("=");
uart_print_i(val);
uart_send_str("\r");
}
static void print_cfg_str(const char* str)
{
uart_send_str("='");
uart_send_str(str);
uart_send_str("'\r");
}
static void print_cfg_types()
{
const struct cfg_type* t;
for (t = g_cfg_types; t->name; ++t)
{
int i;
uart_send_str(t->name);
for (i = 0; i < t->nind; ++i)
uart_send_str("[]");
if (t->str)
print_cfg_str(def_cfg_str(t));
else
print_cfg_val(def_cfg_val(t));
}
}
static void print_cfg_area_status(const struct config_area* ar)
{
uart_send_str(cfg_area_status_names[ar->status]);
if (ar->invalid)
uart_send_str("/invalid");
}
static void print_cfg_info(const struct config* cfg)
{
uart_send_str("[");
uart_print_i(cfg->area[0].used_bytes);
uart_send_str("/");
uart_print_i(cfg->area[1].used_bytes);
uart_send_str(" bytes used, active area #");
uart_print_i(cfg->active_area);
uart_send_str(" is ");
print_cfg_area_status(&cfg->area[cfg->active_area]);
uart_send_str(", inactive area #");
uart_print_i(cfg->active_area^1);
uart_send_str(" is ");
print_cfg_area_status(&cfg->area[cfg->active_area^1]);
uart_send_str("]\r");
}
static void print_cfg_value_cb(struct config* cfg, struct cfg_type const* t, struct cfg_obj_header const* h, struct cfg_obj_footer const* f)
{
uart_send_str(t->name);
if (t->nind)
print_cfg_ind(h->i);
if (t->nind > 1)
print_cfg_ind(h->j_sz);
if (t->str)
print_cfg_str((const char*)(h+1));
else
print_cfg_val(*(int*)(h+1));
}
static void print_cfg_values()
{
uart_send_str("--- system config:\r");
print_cfg_info(&cfg_system);
cfg_enum(&cfg_system, print_cfg_value_cb);
uart_send_str("--- user config:\r");
print_cfg_info(&cfg_user);
cfg_enum(&cfg_user, print_cfg_value_cb);
}
static void cfg_cli_set_complete()
{
int i;
struct cfg_set_ctx s = set_ctx;
if (!s.cfg || !s.type)
return;
// store value
int r;
if (s.type->str)
r = cfg_put_str_(s.cfg, s.type, s.ind[0], s.buff);
else
r = cfg_put_val_(s.cfg, s.type, s.ind[0], s.ind[1], s.val);
if (r < 0) {
uart_send_str("failed to store value");
return;
}
// lookup value
uart_send_str(s.type->name);
for (i = 0; i < s.type->nind; ++i)
print_cfg_ind(s.ind[i]);
if (s.type->str)
print_cfg_str(cfg_get_str_(s.cfg, s.type, s.ind[0]));
else
print_cfg_val(cfg_get_val_(s.cfg, s.type, s.ind[0], s.ind[1]));
}
static cli_proc_res cfg_cli_set(struct config* cfg)
{
if (cfg) {
// initialize
set_ctx.cfg = cfg;
set_ctx.type = 0;
set_ctx.ind[0] = set_ctx.ind[1] = set_ctx.nind = 0;
return cli_accepted;
}
if (!set_ctx.type) {
// lookup type
set_ctx.type = get_cfg_type(g_uart.rx_buff);
return set_ctx.type ? cli_accepted : cli_failed;
}
if (set_ctx.nind < set_ctx.type->nind) {
// get index
set_ctx.ind[set_ctx.nind++] = a2i(g_uart.rx_buff);
return cli_accepted;
} else {
// copy value
if (set_ctx.type->str) {
strncpy(set_ctx.buff, g_uart.rx_buff, BUFF_SZ);
} else {
set_ctx.val = a2i(g_uart.rx_buff);
}
cfg_cli_complete_cb = cfg_cli_set_complete;
return cli_complete_pending;
}
}
static cli_proc_res cfg_cli_process(int start)
{
if (!start) {
return cfg_cli_set(0);
}
if (cli_cmd_matched("set")) {
return cfg_cli_set(&cfg_system);
}
if (cli_cmd_matched("setu")) {
return cfg_cli_set(&cfg_user);
}
if (cli_cmd_matched("types")) {
cfg_cli_complete_cb = print_cfg_types;
return cli_complete_pending;
}
if (cli_cmd_matched("cfg")) {
cfg_cli_complete_cb = print_cfg_values;
return cli_complete_pending;
}
return cli_ignored;
}
static void cfg_cli_complete()
{
BUG_ON(!cfg_cli_complete_cb);
cfg_cli_complete_cb();
}
static void cfg_cli_get_help()
{
uart_send_str("types\t- show configuration types\r");
uart_send_str("cfg\t- show stored configuration\r");
uart_send_str("set name [i [j]] value - set system configuration value\r");
uart_send_str("setu name [i [j]] value - set user configuration value\r");
}
const struct cli_subsystem cfg_cli = {
cfg_cli_process,
cfg_cli_complete,
cfg_cli_get_help
};
<file_sep>#pragma once
//
// Configuration types registry
//
// The configuration types are derived from either int or string
// base types. They may be either singletons or have 1D or 2D
// array of instances. Every configuration type has distinct name
// and default value common for all instances.
struct cfg_type {
const char* name;
unsigned char nind; // 0..2 for int, 0..1 for str
unsigned char str; // is string flag
union { // default value
int val;
const char* ptr;
} def;
};
#define CFG_INT(n, d) {.name=n, .nind=0, .str=0, .def.val=d}
#define CFG_INT_I(n, d) {.name=n, .nind=1, .str=0, .def.val=d}
#define CFG_INT_IJ(n, d) {.name=n, .nind=2, .str=0, .def.val=d}
#define CFG_STR(n, d) {.name=n, .nind=0, .str=1, .def.ptr=d}
#define CFG_STR_I(n, d) {.name=n, .nind=1, .str=1, .def.ptr=d}
#define CFG_TYPE_END {.name=0}
#define CFG_NTYPES (sizeof(g_cfg_types)/sizeof(g_cfg_types[0])-1)
#define MAX_CFG_TYPES 255
// Global types registry
extern const struct cfg_type g_cfg_types[];
extern unsigned g_cfg_ntypes; // number of types
// Lookup type by name
const struct cfg_type* get_cfg_type(const char* name);
// Get default value
int def_cfg_val(const struct cfg_type* t);
// Get default string
const char* def_cfg_str(const struct cfg_type* t);
<file_sep>#include "uart.h"
#include "aconv.h"
struct uart_ctx g_uart;
// Send current TX buffer asynchronously
void uart_send_start()
{
g_uart.tx_curr = 0;
IE2 |= UCA0TXIE;
}
static inline void uart_send_next()
{
UCA0TXBUF = g_uart.tx_buff[g_uart.tx_curr];
if (++g_uart.tx_curr >= g_uart.tx_len)
IE2 &= ~UCA0TXIE;
}
// USCI A0/B0 Transmit ISR
#pragma vector=USCIAB0TX_VECTOR
__interrupt void USCI0TX_ISR(void)
{
uart_send_next();
}
// Send current TX buffer asynchronously (no more than UART_BUFF_SZ)
void uart_send_str_async(const char* str)
{
g_uart.tx_len = 0;
for (; *str && g_uart.tx_len < UART_BUFF_SZ; ++str)
g_uart.tx_buff[g_uart.tx_len++] = *str;
uart_send_start();
}
// Send string to UART. Strings of length <= UART_BUFF_SZ
// will be sent without blocking.
void uart_send_str(const char* str)
{
while (*str) {
uart_wait();
uart_send_str_async(str);
str += g_uart.tx_len;
}
}
// Formatted output
void uart_print_i(int n)
{
uart_wait();
g_uart.tx_len = i2a(n, g_uart.tx_buff);
uart_send_start();
}
void uart_print_x(unsigned n)
{
uart_wait();
g_uart.tx_len = x2a(n, g_uart.tx_buff);
uart_send_start();
}
// Start/stop receiving.
void uart_receive_enable(uart_rx_cb cb)
{
g_uart.rx_len = 0;
g_uart.rx_cb = cb;
if (cb)
IE2 |= UCA0RXIE;
else
IE2 &= ~UCA0RXIE;
}
static inline void uart_receive_next()
{
char c = UCA0RXBUF;
if (g_uart.rx_len < UART_BUFF_SZ)
g_uart.rx_buff[g_uart.rx_len++] = c;
if (g_uart.rx_cb)
g_uart.rx_cb(c);
}
// USCI A0/B0 Receive ISR
#pragma vector=USCIAB0RX_VECTOR
__interrupt void USCI0RX_ISR(void)
{
uart_receive_next();
}
<file_sep>//
// Configuration types table
//
#include "cfg_types.h"
const struct cfg_type g_cfg_types[] = {
CFG_INT("test.static", 0),
CFG_INT("test.runs", 0),
CFG_STR_I("test.str", "0"),
CFG_INT_I("test.arr", 0),
// end of array marker
CFG_TYPE_END
};
unsigned g_cfg_ntypes = CFG_NTYPES;
<file_sep>micro-config
============
Fail safe flash based tiny configuration storage for MSP430
<file_sep>#pragma once
#include "cli.h"
extern const struct cli_subsystem dbg_cli;
<file_sep>#pragma once
#define VER_STRING "0.1"
#define VER_INFO "developer"
<file_sep>#include "dbg_cli.h"
#include "debug.h"
#include "uart.h"
static void dbg_cli_complete()
{
if (!dbg_soft_restarted()) {
uart_send_str("no debug info available\r");
} else {
uart_send_str("was ");
dbg_print_restart_info();
}
}
static cli_proc_res dbg_cli_process(int start)
{
if (cli_cmd_matched("reset"))
dbg_reset();
if (cli_cmd_matched("dbg"))
return cli_complete_pending;
return cli_ignored;
}
static void dbg_cli_get_help()
{
uart_send_str("reset\t- reset device\r");
uart_send_str("dbg\t- show debug info\r");
}
const struct cli_subsystem dbg_cli = {
dbg_cli_process,
dbg_cli_complete,
dbg_cli_get_help
};
<file_sep>#include "aconv.h"
int a2i(const char* str)
{
int acc = 0, m = 0;
if (str[0] == '-') {
++str;
m = 1;
}
for (;;) {
char c = *str;
if (c < '0' || c > '9')
break;
acc *= 10;
acc += c - '0';
++str;
}
return m ? -acc : acc;
}
int i2a(int n, char* buff)
{
if (!n) {
buff[0] = '0';
return 1;
}
int m = 0, len = 0, i;
if (n < 0) {
*buff++ = '-';
n = -n;
m = 1;
}
while (n) {
unsigned d = n % 10;
n /= 10;
for (i = len; i > 0; --i)
buff[i] = buff[i-1];
buff[0] = '0' + d;
++len;
}
return m ? len + 1 : len;
}
int x2a(unsigned n, char* buff)
{
if (!n) {
buff[0] = '0';
return 1;
}
int shift, len = 0;
for (shift = 12; shift >= 0; shift -= 4) {
unsigned d = (n >> shift) & 0xf;
if (!d && !len)
continue;
*buff++ = d < 10 ? '0' + d : 'A' + (d - 10);
++len;
}
return len;
}
<file_sep>#include "cfg.h"
#pragma data_alignment=FLASH_SEG_SZ
static __no_init const char cfg_system_storage[2][CFG_BUFF_SIZE] @ "CODE";
#pragma data_alignment=FLASH_SEG_SZ
static __no_init const char cfg_user_storage[2][CFG_BUFF_SIZE] @ "CODE";
// System config is not expected to be changed by user
struct config cfg_system = {{
{cfg_system_storage[0]},
{cfg_system_storage[1]}
}};
// User config is expected to be changed by user
struct config cfg_user = {{
{cfg_user_storage[0]},
{cfg_user_storage[1]}
}};
<file_sep>#pragma once
//
// Configuration storage instances
//
#include "config.h"
// We are using 2 storage instances for reliability and convenience.
// The user configuration is expected to be updated frequently by the user.
// The system configuration will never be updated during normal operation.
// Besides reliability it means that clients may obtain pointer to the
// configuration value only once during initialization.
// System config is not expected to be changed by user
extern struct config cfg_system;
// User config is expected to be changed by user
extern struct config cfg_user;
static inline void cfg_init_all()
{
cfg_init(&cfg_system);
cfg_init(&cfg_user);
}
<file_sep>#include "debug.h"
#include "uart.h"
#include "wdt.h"
#include "io430.h"
__no_init struct dbg_info g_dgb_info;
static inline void reset()
{
FCTL2 = 0xDEAD;
}
int dbg_soft_restarted()
{
return FCTL3 & KEYV;
}
static inline void clear_bug_info()
{
g_dgb_info.bug_file = 0;
}
static inline void print_bug_info()
{
uart_send_str("BUG at ");
uart_send_str(g_dgb_info.bug_file);
uart_send_str(":");
uart_print_i(g_dgb_info.bug_line);
uart_send_str("\r");
uart_wait();
}
void dbg_print_restart_info()
{
if (!g_dgb_info.bug_file)
uart_send_str("restarted\r");
else
print_bug_info();
}
void dbg_init()
{
if (dbg_soft_restarted())
dbg_print_restart_info();
else
clear_bug_info();
}
void dbg_reset()
{
clear_bug_info();
reset();
}
void dbg_fatal(const char* file, int line)
{
g_dgb_info.bug_file = file;
g_dgb_info.bug_line = line;
reset();
}
<file_sep>#pragma once
#include "uart.h"
typedef enum {
cli_ignored,
cli_accepted,
cli_done,
cli_complete_pending,
cli_failed
} cli_proc_res;
struct cli_subsystem;
typedef void (*cli_cb)();
typedef cli_proc_res (*cli_proc_cb)(int start);
struct cli_subsystem {
cli_proc_cb process;
cli_cb complete;
cli_cb get_help;
};
struct cli_ctx {
const struct cli_subsystem* const* subsystems;
const struct cli_subsystem* processing;
const struct cli_subsystem* complete_pending;
cli_proc_res proc_res;
};
extern struct cli_ctx g_cli;
// Compare receiver buffer with the command string. Returns 1 if the buffer is the
// non-empty prefix of the command. Otherwise returns 0.
int cli_cmd_matched(const char* cmd);
// Asynchronous processing callback
static inline void cli_process()
{
if (g_cli.complete_pending) {
g_cli.complete_pending->complete(g_cli.complete_pending);
g_cli.complete_pending = 0;
}
}
// Initialize command line interface
void cli_init();
<file_sep>#pragma once
#include "cfg_types.h"
#include "flash.h"
#include "crc16.h"
//
// Configuration storage
//
// It uses flash for storing configuration types instances.
// Every storage instance needs 2 flash buffers (areas)
// since when we are erasing one the another one keeps
// configuration content.
#define CFG_BUFF_SEGS 2
#define CFG_BUFF_SIZE (FLASH_SEG_SZ*CFG_BUFF_SEGS)
typedef enum {
area_empty,
area_dirty,
area_open,
area_modified,
area_closed,
area_completed
} cfg_area_status_t;
extern const char* cfg_area_status_names[];
// Storage buffer
struct config_area {
const char* storage;
unsigned used_bytes;
crc16_t crc;
unsigned char status;
unsigned char invalid;
};
// The config instance has 2 buffer areas and keeps index of the active one
struct config {
struct config_area area[2];
int active_area;
};
// The header is written before actual data (config type instance)
struct cfg_obj_header {
unsigned char type_tag; // index of the type in global registry
union {
struct {
unsigned char i:4; // first index
unsigned char j_sz:4; // second index or string size not including 0-termination
};
unsigned char ij;
};
};
// The footer is written right after the data
struct cfg_obj_footer {
crc16_t crc;
};
// Initialize the particular config instance
void cfg_init(struct config* cfg);
typedef void (*cfg_enum_cb)(struct config*, struct cfg_type const*, struct cfg_obj_header const*, struct cfg_obj_footer const*);
// Enumerate objects
void cfg_enum(struct config* cfg, cfg_enum_cb cb);
// Lookup value in storage and return default if not found
int cfg_get_val_(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j);
const char* cfg_get_str_(struct config* cfg, const struct cfg_type* t, unsigned char i);
//
// The shorthand variants of lookup routine
//
static inline int cfg_get_val(struct config* cfg, const struct cfg_type* t)
{
return cfg_get_val_(cfg, t, 0, 0);
}
static inline int cfg_get_val_i(struct config* cfg, const struct cfg_type* t, unsigned char i)
{
return cfg_get_val_(cfg, t, i, 0);
}
static inline int cfg_get_val_ij(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j)
{
return cfg_get_val_(cfg, t, i, j);
}
static inline const char* cfg_get_str(struct config* cfg, const struct cfg_type* t)
{
return cfg_get_str_(cfg, t, 0);
}
static inline const char* cfg_get_str_i(struct config* cfg, const struct cfg_type* t, unsigned char i)
{
return cfg_get_str_(cfg, t, i);
}
// Put value to the storage. Returns 0 on success, -1 if no space left on the storage.
int cfg_put_val_(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j, int val);
#define MAX_CFG_STR_LEN 15
// Put zero-terminated string to the storage. If string length exceeds MAX_CFG_STR_LEN the -1 will be returned.
int cfg_put_str_(struct config* cfg, const struct cfg_type* t, unsigned char i, const char* str);
//
// The shorthand variants of put routine
//
static inline int cfg_put_val(struct config* cfg, const struct cfg_type* t, int val)
{
return cfg_put_val_(cfg, t, 0, 0, val);
}
static inline int cfg_put_val_i(struct config* cfg, const struct cfg_type* t, unsigned char i, int val)
{
return cfg_put_val_(cfg, t, i, 0, val);
}
static inline int cfg_put_val_ij(struct config* cfg, const struct cfg_type* t, unsigned char i, unsigned char j, int val)
{
return cfg_put_val_(cfg, t, i, j, val);
}
static inline int cfg_put_str(struct config* cfg, const struct cfg_type* t, const char* str)
{
return cfg_put_str_(cfg, t, 0, str);
}
static inline int cfg_put_str_i(struct config* cfg, const struct cfg_type* t, unsigned char i, const char* str)
{
return cfg_put_str_(cfg, t, i, str);
}
<file_sep>#include "ver_cli.h"
#include "version.h"
#include "uart.h"
static cli_proc_res ver_cli_process(int start)
{
if (cli_cmd_matched("version"))
return cli_complete_pending;
else
return cli_ignored;
}
static void ver_cli_complete()
{
uart_send_str("version "VER_STRING" ["VER_INFO"] built "__DATE__" "__TIME__"\r");
}
static void ver_cli_get_help()
{
uart_send_str("version\t- show version info\r");
}
const struct cli_subsystem ver_cli = {
ver_cli_process,
ver_cli_complete,
ver_cli_get_help
};
<file_sep>#pragma once
#include "wdt.h"
struct wdt_ctx g_wdt;
#pragma vector=WDT_VECTOR
__interrupt void wdt_timer(void)
{
struct wdt_clnt* c;
++g_wdt.clk;
for (c = g_wdt.clients; c; c = c->next)
c->cb(g_wdt.clk);
}
<file_sep>#include "cli.h"
#include "ver_cli.h"
#include "dbg_cli.h"
#include "cfg_cli.h"
#define IS_EOL(ch) (ch == '\r' || ch == '\n')
#define IS_SPACE(ch) (ch == ' ' || ch == '\t' || IS_EOL(ch))
// Compare receiver buffer with the command string. Returns 1 if the buffer is the
// non-empty prefix of the command. Otherwise returns 0.
int cli_cmd_matched(const char* cmd)
{
const char* buff = g_uart.rx_buff;
while (*buff && *cmd)
if (*buff++ != *cmd++) // not matched
return 0;
if (*buff) // has extra symbols
return 0;
// matched
return 1;
}
// Callback called on every symbol received by uart
static void cli_uart_cb(char ch)
{
if (!IS_SPACE(ch))
return;
if (--g_uart.rx_len) // drop space
{
cli_proc_res res;
// zero-terminate input
g_uart.rx_buff[g_uart.rx_len] = 0;
if (g_cli.complete_pending || g_cli.proc_res >= cli_done) {
// unexpected input
g_cli.proc_res = cli_failed;
g_uart.rx_len = 0;
}
else if (g_cli.processing) {
if ((res = g_cli.processing->process(0)) != cli_ignored) {
g_cli.proc_res = res;
g_uart.rx_len = 0;
}
}
else {
const struct cli_subsystem* const* ssp;
for (ssp = g_cli.subsystems; *ssp; ++ssp) {
const struct cli_subsystem* ss = *ssp;
if ((res = ss->process(1)) != cli_ignored) {
g_cli.processing = ss;
g_cli.proc_res = res;
g_uart.rx_len = 0;
break;
}
}
}
}
if (IS_EOL(ch)) {
if (g_cli.proc_res == cli_accepted || (g_cli.proc_res == cli_ignored && g_uart.rx_len)) // incomplete input
g_cli.proc_res = cli_failed;
if (g_cli.proc_res == cli_failed)
uart_send_str_async("invalid command\r");
else if (g_cli.proc_res == cli_complete_pending)
g_cli.complete_pending = g_cli.processing;
// reset state
g_cli.processing = 0;
g_cli.proc_res = cli_ignored;
g_uart.rx_len = 0;
}
}
static cli_proc_res cli_help_process(int start)
{
if (cli_cmd_matched("help"))
return cli_complete_pending;
else
return cli_ignored;
}
static void cli_help_complete()
{
const struct cli_subsystem* const* ssp;
for (ssp = g_cli.subsystems; *ssp; ++ssp) {
const struct cli_subsystem* ss = *ssp;
ss->get_help();
}
}
static void cli_help_get_help()
{
uart_send_str("help\t- this help\r");
}
static const struct cli_subsystem hlp_cli = {
cli_help_process,
cli_help_complete,
cli_help_get_help
};
static const struct cli_subsystem* const cli_subsystems[] = {
&ver_cli,
&cfg_cli,
&dbg_cli,
&hlp_cli,
0
};
struct cli_ctx g_cli = {cli_subsystems};
void cli_init()
{
uart_receive_enable(cli_uart_cb);
}
<file_sep>#pragma once
#include "cli.h"
extern const struct cli_subsystem ver_cli;
<file_sep>#pragma once
struct dbg_info {
const char* bug_file;
int bug_line;
};
extern struct dbg_info g_dgb_info;
void dbg_init();
void dbg_reset();
void dbg_fatal(const char* file, int line);
int dbg_soft_restarted();
void dbg_print_restart_info();
#define BUG() do { dbg_fatal(__FILE__, __LINE__); } while(0)
#define BUG_ON(cond) do { if (cond) dbg_fatal(__FILE__, __LINE__); } while(0)
#ifdef DBG_BUG_ON_EN
#define DBG_BUG_ON(cond) BUG_ON(cond)
#define DBG_BUG() BUG()
#else
#define DBG_BUG() do {} while(0)
#define DBG_BUG_ON(cond) do {} while(0)
#endif
<file_sep>#include "cfg_types.h"
#include "debug.h"
static inline int type_name_eq(const char* a, const char* b)
{
#define _CMP_ if (*a != *b) return 0; if (!*a) return 1; ++a; ++b;
// Compare at most 8 chars for speed
_CMP_
_CMP_
_CMP_
_CMP_
_CMP_
_CMP_
_CMP_
_CMP_
return 1;
}
// Lookup type by name
const struct cfg_type* get_cfg_type(const char* name)
{
const struct cfg_type* t;
for (t = g_cfg_types; t->name; ++t) {
if (type_name_eq(t->name, name))
return t;
}
return 0;
}
// Get default value
int def_cfg_val(const struct cfg_type* t)
{
BUG_ON(!t);
BUG_ON(t->str);
return t->def.val;
}
// Get default string
const char* def_cfg_str(const struct cfg_type* t)
{
BUG_ON(!t);
BUG_ON(!t->str);
return t->def.ptr;
}
| be1d47fbe8d78eacb691191675d5e04de7a3643d | [
"Markdown",
"C"
]
| 27 | C | bwp530/micro-config | baf5b2307afa24d122f47f9961b3e036a98a5d4b | f93ec9f865c1f241782db63e4ec07c11b9e5c68f |
refs/heads/master | <file_sep>package co.grandcircus.lab.Coffee_Shop.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.stereotype.Repository;
import co.grandcircus.lab.Coffee_Shop.entity.Items;
import co.grandcircus.lab.Coffee_Shop.entity.cartitems;
@Repository
@Transactional
public class ItemsDao {
@PersistenceContext
private EntityManager em;
public Items findById(Long id) {
return em.find(Items.class, id);
}
public List<Items> findAll() {
return em.createQuery("FROM Items", Items.class).getResultList();
}
public List<cartitems> findByCartitems(cartitems cartitems) {
return em.createQuery("from cartitems where cartitems = :cartitems order by itemname", cartitems.class)
.setParameter("cartitems", cartitems)
.getResultList();
}
public void create(Items items) {
em.persist(items);
}
public void update(Items items) {
em.merge(items);
}
public void delete(Long id) {
em.remove(em.getReference(Items.class, id));
}
}
| 5ec8d6d69639933167b89f6dfaadc7ae32bb40ff | [
"Java"
]
| 1 | Java | Maltheos/Lab_22_23 | acc4224bc312f8a34753d7261e9d15066ff983f6 | d52a3d3b128debbaa9d511f58569e5ac08221fbb |
refs/heads/main | <repo_name>itairozen/dealer_choice<file_sep>/server.js
const { db, syncAndSeed, models:{Item} } = require('./db');
const express = require('express');
const path = require('path');
const app = express();
app.get('/styles.css', (req,res)=> res.sendFile(path.join(__dirname, 'styles.css')));
app.get('/', (req,res)=> res.redirect('/items'));
app.get('/items', async(req,res,next)=>{
try {
const items = await Item.findAll();
res.send(`
<html>
<head>
<link rel='stylesheet' href='/styles.css' />
</head>
<body>
<h1>Items (${items.length})</h1>
<ul>
${items.map( item => `
<li>
<a href='/items/${item.id}'>
${item.name}
</a>
</li>
`).join('')}
</ul>
</body>
</html>
`);
}
catch(ex){
next(ex);
}
});
app.get('/items/:id', async(req,res,next)=>{
try {
const items = [await Item.findByPk(req.params.id)];
res.send(`
<html>
<head>
<link rel='stylesheet' href='/styles.css' />
</head>
<body>
<h1>${items.map( item => item.name)}</h1>
<h3><a href='/items'>Back To Home</a></h3>
<ul>
${items.map( item => `
${item.details}
`).join('')}
</ul>
</body>
</html>
`);
}
catch(ex){
next(ex);
}
});
const init = async()=> {
try {
await db.authenticate();
await syncAndSeed();
const port = process.env.PORT || 3000;
app.listen(port, ()=> console.log(`listening on port ${port}`));
}
catch(ex) {
console.log(ex);
}
};
init() | d61c1bbce7b5590a7b010415661ae347917f9d50 | [
"JavaScript"
]
| 1 | JavaScript | itairozen/dealer_choice | 3fc01801261c9210999359632ab1869fbffacc8a | 9d2008e3529a3857fa155033f0db8d09b87925e3 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
namespace ImageProcessing
{
public class DerivateiveEdgeDetectorParms
{
[NotifyParentProperty(true)]
public Channels Channel { get; set; }
[NotifyParentProperty(true)]
public int Threshold { get; set; }
[NotifyParentProperty(true)]
public bool ConvertToGrayscale { get; set; }
[NotifyParentProperty(true)]
public Color EdgeColor { get; set; }
[NotifyParentProperty(true)]
public bool CopyOriginal { get; set; }
public DerivateiveEdgeDetectorParms()
{
Channel = Channels.RGB;
Threshold = 50;
ConvertToGrayscale = true;
EdgeColor = Color.Yellow;
CopyOriginal = true;
}
}
public class DerivativeEdgeDetector: ImageFilter<DerivateiveEdgeDetectorParms>
{
public override Bitmap FilterProcessImage(DerivateiveEdgeDetectorParms parms, Bitmap image)
{
Bitmap ret = new Bitmap(image.Width, image.Height);
for (int i = 1; i < image.Width - 1; i++)
{
for (int j = 1; j < image.Height - 1; j++)
{
Color cr = image.GetPixel(i + 1, j);
Color cl = image.GetPixel(i - 1, j);
Color cu = image.GetPixel(i, j - 1);
Color cd = image.GetPixel(i, j + 1);
int dx = 0, dy = 0;
switch (parms.Channel)
{
case Channels.R:
dx = cr.R - cl.R;
dy = cd.R - cu.R;
break;
case Channels.G:
dx = cr.G - cl.G;
dy = cd.G - cu.G;
break;
case Channels.B:
dx = cr.B - cl.B;
dy = cd.B - cu.B;
break;
case Channels.RGB:
dx = (int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11 - (cl.R * .3 + cl.G * .59 + cl.B * 0.11));
dy = (int)(cd.R * .3 + cd.G * .59 + cd.B * 0.11 - (cu.R * .3 + cu.G * .59 + cu.B * 0.11));
break;
}
double power = Math.Sqrt(dx * dx / 4 + dy * dy / 4);
if (power > parms.Threshold)
ret.SetPixel(i, j, parms.EdgeColor);
else
{
if (parms.CopyOriginal)
{
Color c = image.GetPixel(i, j);
if (parms.ConvertToGrayscale)
{
ret.SetPixel(i, j,
Color.FromArgb(255,
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11),
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11),
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11)));
}
else
ret.SetPixel(i, j, c);
}
else
ret.SetPixel(i, j, Color.White);
}
}
}
return ret;
}
public override System.Windows.Forms.Control GetParameterWindow()
{
return new DerivativeEdgeDetectorParmForm();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class ParmFormBase : UserControl
{
public event EventHandler<EventArgs> ParmsChanged;
public ParmFormBase()
{
InitializeComponent();
}
protected void raiseParmChangedEvent()
{
if (ParmsChanged != null)
ParmsChanged(this, new EventArgs());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class DerivativeEdgeDetectorParmForm : ParmFormBase
{
private DerivateiveEdgeDetectorParms mParms = new DerivateiveEdgeDetectorParms();
public DerivativeEdgeDetectorParmForm()
{
InitializeComponent();
derivateiveEdgeDetectorParmsBindingSource.DataSource = mParms;
}
void mParms_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
raiseParmChangedEvent();
}
private void DerivativeEdgeDetectorParmForm_Load(object sender, EventArgs e)
{
cbChannels.Items.Clear();
cbChannels.Items.Add(Channels.R);
cbChannels.Items.Add(Channels.G);
cbChannels.Items.Add(Channels.B);
cbChannels.Items.Add(Channels.RGB);
}
public DerivateiveEdgeDetectorParms Parms
{
get
{
return mParms;
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
raiseParmChangedEvent();
}
private void panelBorderColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
panelBorderColor.BackColor = colorDialog1.Color;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
namespace ImageProcessing
{
public class BinaryEroderParms
{
[NotifyParentProperty(true)]
public Color ActiveColor { get; set; }
[NotifyParentProperty(true)]
public Color BlankColor { get; set; }
[NotifyParentProperty(true)]
public Bitmap StructureElement { get; set; }
[NotifyParentProperty(true)]
public Color SEActiveColor { get; set; }
[NotifyParentProperty(true)]
public int GrayscaleThreshold { get; set; }
public BinaryEroderParms()
{
ActiveColor = Color.Yellow;
StructureElement = new Bitmap(3, 3);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (i == 1 || j == 1)
StructureElement.SetPixel(i, 0, Color.Red);
else
StructureElement.SetPixel(i, 0, Color.Black);
}
}
SEActiveColor = Color.Red;
ActiveColor = Color.Yellow;
BlankColor = Color.Black;
GrayscaleThreshold = 200;
}
}
public class BinaryEroder : ImageFilter<BinaryEroderParms>
{
public override Bitmap FilterProcessImage(BinaryEroderParms parms, Bitmap image)
{
Bitmap ret = new Bitmap(image.Width, image.Height);
for (int i = 0; i < image.Width; i++)
{
for (int j = 0; j < image.Height; j++)
{
bool keep = true;
for (int m = 0; m < parms.StructureElement.Width; m++)
{
for (int n = 0; n < parms.StructureElement.Height; n++)
{
Color a = image.GetPixel(Math.Min(Math.Max(0, i + m - parms.StructureElement.Width / 2), image.Width - 1),
Math.Min(Math.Max(0, j + n - parms.StructureElement.Height / 2), image.Height - 1));
Color b = parms.StructureElement.GetPixel(m, n);
int grayScale = (int)(a.R * 0.3 + a.G * 0.59 + a.B * 0.11);
if (b.R == parms.SEActiveColor.R
&& b.G == parms.SEActiveColor.G
&& b.B == parms.SEActiveColor.B
&& grayScale < parms.GrayscaleThreshold)
{
keep = false;
continue;
}
}
}
ret.SetPixel(i, j, keep? parms.ActiveColor: parms.BlankColor);
}
}
return ret;
}
public override System.Windows.Forms.Control GetParameterWindow()
{
return new BinaryEroderParmForm();
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (ofDialog.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(ofDialog.FileName))
{
picViewer view1 = new picViewer();
view1.MdiParent = this;
view1.WindowState = FormWindowState.Normal;
view1.Image = Image.FromFile(ofDialog.FileName);
view1.Show();
Bitmap move1 = view1.Bitmap;
move1.Save("c:\\Users\\Main\\Documents\\myNewimage1.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
private void dervivativeEdgeDetectionToolStripMenuItem_Click(object sender, EventArgs e)
{
DerivativeEdgeDetector filter = new DerivativeEdgeDetector();
picViewer view = new picViewer();
view.ParmControl = filter.GetParameterWindow();
Image image = filter.ProcessImage(
((DerivativeEdgeDetectorParmForm)view.ParmControl).Parms,
((picViewer)this.ActiveMdiChild).Image );
view.MdiParent = this;
view.WindowState = FormWindowState.Normal;
view.Image = image;
view.ParmControl = filter.GetParameterWindow();
((DerivativeEdgeDetectorParmForm)view.ParmControl).ParmsChanged += new EventHandler<EventArgs>((obj,target)=>
{
view.Image = filter.ProcessImage(
((DerivativeEdgeDetectorParmForm)view.ParmControl).Parms,
filter.OriginalImage);
});
view.Show();
}
private void sobelEdgeDetectorToolStripMenuItem_Click(object sender, EventArgs e)
{
SobelEdgeDetector filter = new SobelEdgeDetector();
picViewer view = new picViewer();
view.ParmControl = filter.GetParameterWindow();
Image image = filter.ProcessImage(
((SobelEdgeDetectorParmForm)view.ParmControl).Parms,
((picViewer)this.ActiveMdiChild).Image);
view.MdiParent = this;
view.WindowState = FormWindowState.Normal;
view.Image = image;
view.ParmControl = filter.GetParameterWindow();
((SobelEdgeDetectorParmForm)view.ParmControl).ParmsChanged += new EventHandler<EventArgs>((obj, target) =>
{
view.Image = filter.ProcessImage(
((SobelEdgeDetectorParmForm)view.ParmControl).Parms,
filter.OriginalImage);
});
view.Show();
}
private void binaryErosionToolStripMenuItem_Click(object sender, EventArgs e)
{
BinaryEroder filter = new BinaryEroder();
picViewer view = new picViewer();
view.ParmControl = filter.GetParameterWindow();
Image image = filter.ProcessImage(
((BinaryEroderParmForm)view.ParmControl).Parms,
((picViewer)this.ActiveMdiChild).Image);
view.MdiParent = this;
view.WindowState = FormWindowState.Normal;
view.Image = image;
view.ParmControl = filter.GetParameterWindow();
((BinaryEroderParmForm)view.ParmControl).ParmsChanged += new EventHandler<EventArgs>((obj, target) =>
{
view.Image = filter.ProcessImage(
((BinaryEroderParmForm)view.ParmControl).Parms,
filter.OriginalImage);
});
view.Show();
}
private void krischEdgeDetectorToolStripMenuItem_Click(object sender, EventArgs e)
{
KrischEdgeDetector filter = new KrischEdgeDetector();
picViewer view = new picViewer();
view.ParmControl = filter.GetParameterWindow();
Image image = filter.ProcessImage(
((KrischEdgeDetectorParmForm)view.ParmControl).Parms,
((picViewer)this.ActiveMdiChild).Image );
view.MdiParent = this;
view.StartPosition = FormStartPosition.CenterScreen;
view.WindowState = FormWindowState.Normal;
view.Image = image;
view.ParmControl = filter.GetParameterWindow();
((KrischEdgeDetectorParmForm)view.ParmControl).ParmsChanged += new EventHandler<EventArgs>((obj, target) =>
{
view.Image = filter.ProcessImage(
((KrischEdgeDetectorParmForm)view.ParmControl).Parms,
filter.OriginalImage);
});
// messageOutput = image.Tag.ToString();
view.Show();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
String messageOutput = "";
KrischEdgeDetector filter = new KrischEdgeDetector();
picViewer view = new picViewer();
view.ParmControl = filter.GetParameterWindow();
Image image = filter.ProcessImage(
((KrischEdgeDetectorParmForm)view.ParmControl).Parms,
((picViewer)this.ActiveMdiChild).Image);
view.StartPosition = FormStartPosition.CenterScreen;
view.WindowState = FormWindowState.Normal;
view.Image = image;
view.ParmControl = filter.GetParameterWindow();
((KrischEdgeDetectorParmForm)view.ParmControl).ParmsChanged += new EventHandler<EventArgs>((obj, target) =>
{
view.Image = filter.ProcessImage(
((KrischEdgeDetectorParmForm)view.ParmControl).Parms,
filter.OriginalImage);
});
messageOutput = image.Tag.ToString();
textBox1.Text += messageOutput;
}
private void toolStripButtonMove_Click(object sender, EventArgs e)
{
if (ofDialog.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(ofDialog.FileName))
{
picViewer view2 = new picViewer();
view2.MdiParent = this;
view2.StartPosition = FormStartPosition.CenterScreen;
view2.WindowState = FormWindowState.Normal;
view2.Image = Image.FromFile(ofDialog.FileName);
view2.Show();
Bitmap move2 = view2.Bitmap;
move2.Save("c:\\Users\\Main\\Documents\\myNewimage2.png", System.Drawing.Imaging.ImageFormat.Png);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace ImageProcessing
{
public abstract class ImageFilter<T>
{
Bitmap mOriginalImage;
T mSetting;
public Image ProcessImage(T setting, Image image)
{
return ProcessImage(setting, new Bitmap(image));
}
public Bitmap ProcessImage(T setting, Bitmap image)
{
mSetting = setting;
mOriginalImage = image;
return FilterProcessImage(setting, image);
}
public abstract Bitmap FilterProcessImage(T setting, Bitmap image);
public abstract Control GetParameterWindow();
public Bitmap OriginalImage
{
get
{
return mOriginalImage;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class picViewer : Form
{
public Image Image
{
set
{
picture.Image = value;
}
get
{
return picture.Image;
}
}
public Bitmap Bitmap
{
set
{
picture.Image = value;
}
get
{
return new Bitmap(picture.Image);
}
}
public Control ParmControl
{
set
{
if (value != null)
{
splitMain.Panel1.Controls.Clear();
splitMain.Panel1.Controls.Add(value);
splitMain.SplitterDistance = value.Height;
splitMain.Panel1Collapsed = false;
}
else
splitMain.Panel1Collapsed = true;
}
get
{
if (splitMain.Panel1.Controls.Count > 0)
return splitMain.Panel1.Controls[0];
else
return null;
}
}
public picViewer()
{
InitializeComponent();
}
private void picViewer_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class BinaryEroderParmForm : ParmFormBase
{
private BinaryEroderParms mParms = new BinaryEroderParms();
public BinaryEroderParmForm()
{
InitializeComponent();
binaryEroderParmsBindingSource.DataSource = mParms;
}
void mParms_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
raiseParmChangedEvent();
}
private void BinaryEroderParmForm_Load(object sender, EventArgs e)
{
}
public BinaryEroderParms Parms
{
get
{
return mParms;
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
raiseParmChangedEvent();
}
private void panelStructureColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
panelStructureColor.BackColor = colorDialog1.Color;
}
private void panelBackColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
panelBackColor.BackColor = colorDialog1.Color;
}
private void panelActiveColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
panelActiveColor.BackColor = colorDialog1.Color;
}
private void btnElementReference_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
picElement.Load(openFileDialog1.FileName);
mParms.StructureElement = (Bitmap)picElement.Image;
}
catch
{
MessageBox.Show("Can't load selected image file.");
}
}
}
private void binaryEroderParmsBindingSource_CurrentItemChanged(object sender, EventArgs e)
{
lblElementSize.Text = "Size:" + (picElement.Image == null ? "(null)" : "(" + picElement.Image.Width.ToString() + " X " + picElement.Image.Height.ToString() + ")");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using AForge;
using Accord.Imaging;
using Accord.Imaging.Filters;
using System.Windows.Forms;
using AForge.Imaging.Filters;
using AForge.Imaging;
using System.Drawing.Imaging;
namespace ImageProcessing
{
public class KrischEdgeDetectorParms
{
[NotifyParentProperty(true)]
public Channels Channel { get; set; }
[NotifyParentProperty(true)]
public int Threshold { get; set; }
[NotifyParentProperty(true)]
public bool ConvertToGrayscale { get; set; }
[NotifyParentProperty(true)]
public Color EdgeColor { get; set; }
[NotifyParentProperty(true)]
public bool CopyOriginal { get; set; }
[NotifyParentProperty(true)]
public String messageOut { get; set; }
public KrischEdgeDetectorParms()
{
Channel = Channels.RGB;
Threshold = 185;
ConvertToGrayscale = true;
EdgeColor = Color.Yellow;
CopyOriginal = true;
}
}
public class KrischEdgeDetector : ImageFilter<KrischEdgeDetectorParms>
{
private Color grayscale(Color cr)
{
return Color.FromArgb(cr.A, (int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11));
}
private int getD(int cr, int cl, int cu, int cd,
int cld, int clu, int cru, int crd, int[,] matrix)
{
return Math.Abs(matrix[0, 0] * clu + matrix[0, 1] * cu + matrix[0, 2] * cru
+ matrix[1, 0] * cl + matrix[1, 2] * cr
+ matrix[2, 0] * cld + matrix[2, 1] * cd + matrix[2, 2] * crd);
}
private int getMaxD(int cr, int cl, int cu, int cd,
int cld, int clu, int cru, int crd)
{
int max = int.MinValue;
for (int i = 0; i < templates.Count; i++)
{
int newVal = getD(cr, cl, cu, cd, cld, clu, cru, crd, templates[i]);
if (newVal > max)
max = newVal;
}
return max;
}
private List<int[,]> templates = new List<int[,]>
{
new int[,] {{ -3, -3, 5 }, { -3, 0, 5 }, { -3, -3, 5 } },
new int[,] {{ -3, 5, 5 }, { -3, 0, 5 }, { -3, -3, -3 } },
new int[,] {{ 5, 5, 5 }, { -3, 0, -3 }, { -3, -3, -3 } },
new int[,] {{ 5, 5, -3 }, { 5, 0, -3 }, { -3, -3, -3 } },
new int[,] {{ 5, -3, -3 }, { 5, 0, -3 }, { 5, -3, -3 } },
new int[,] {{ -3, -3, -3 }, { 5, 0, -3 }, { 5, 5, -3 } },
new int[,] {{ -3, -3, -3 }, { -3, 0, -3 }, { 5, 5, 5 } },
new int[,] {{ -3, -3, -3 }, { -3, 0, 5 }, { -3, 5, 5 } }
};
public override Bitmap FilterProcessImage(KrischEdgeDetectorParms parms, Bitmap image)
{
Bitmap ret = new Bitmap(image.Width, image.Height);
//for (int i = 1; i < image.Width - 1; i++)
//{
// for (int j = 1; j < image.Height - 1; j++)
// {
// Color cr = image.GetPixel(i + 1, j);
// Color cl = image.GetPixel(i - 1, j);
// Color cu = image.GetPixel(i, j - 1);
// Color cd = image.GetPixel(i, j + 1);
// Color cld = image.GetPixel(i - 1, j + 1);
// Color clu = image.GetPixel(i - 1, j - 1);
// Color crd = image.GetPixel(i + 1, j + 1);
// Color cru = image.GetPixel(i + 1, j - 1);
// int d = 0;
// switch (parms.Channel)
// {
// case Channels.R:
// d = getMaxD(cr.R, cl.R, cu.R, cd.R, cld.R, clu.R, cru.R, crd.R);
// break;
// case Channels.G:
// d = getMaxD(cr.G, cl.G, cu.G, cd.G, cld.G, clu.G, cru.G, crd.G);
// break;
// case Channels.B:
// d = getMaxD(cr.B, cl.B, cu.B, cd.B, cld.B, clu.B, cru.B, crd.B);
// break;
// case Channels.RGB:
// d = getMaxD(grayscale(cr).B, grayscale(cl).B, grayscale(cu).B, grayscale(cd).B, grayscale(cld).B, grayscale(clu).B, grayscale(cru).B, grayscale(crd).B);
// break;
// }
// double power = d;
// if (power > parms.Threshold)
// ret.SetPixel(i, j, parms.EdgeColor);
// else
// {
// if (parms.CopyOriginal)
// {
// Color c = image.GetPixel(i, j);
// if (parms.ConvertToGrayscale)
// ret.SetPixel(i, j, grayscale(c));
// else
// ret.SetPixel(i, j, c);
// }
// else
// ret.SetPixel(i, j, Color.White);
// }
// }
//}
// create Edge filter
//CannyEdgeDetector filter = new CannyEdgeDetector();
// apply the filter
//filter.ApplyInPlace(image);
Bitmap move1Image = new Bitmap("c:\\Users\\Main\\Documents\\myNewimage1.png");
Bitmap move2Image = new Bitmap("c:\\Users\\Main\\Documents\\myNewimage2.png");
Bitmap background = new Bitmap("C:\\Users\\Main\\Documents\\Image Processing\\ImageProcessing_0.2.1\\Pictures\\background.jpg");
/*
for (int i = 0; i < image.Size.Width; i++)
{
for (int j = 0; j < image.Size.Height; j++)
{
if( background.GetPixel = move1Image)
}
}
*/
// Create a new Corners Detector using the given parameters
HarrisCornersDetector fast = new HarrisCornersDetector();
//create an arry of those pixel deemed to be corners of the image
System.Collections.Generic.List<AForge.IntPoint> corners1 = fast.ProcessImage(move1Image);
System.Collections.Generic.List<AForge.IntPoint> corners2 = fast.ProcessImage(move2Image);
for (int i = 0; i < image.Size.Height; i++)
{
}
float a = corners1[2].X / corners1[2].Y;
float r = 30;
float rPrime = 50;
float q = 10;
float f = 5;
float distanceP = (a * (r + rPrime) + r) * q / ((a + 1) * f);
float move1 = corners2[0].DistanceTo(corners1[0]);
float move2 = corners2[1].DistanceTo(corners1[1]);
float move3 = corners2[2].DistanceTo(corners1[2]);
int[] dimensions = new int[5];
double[] scaled = new double[5];
AForge.IntPoint first = corners1[0];
AForge.IntPoint second = corners2[0];
float differenceX = second.X - first.X ;
float differenceY = second.Y -first.Y ;
System.Console.WriteLine(first);
System.Console.WriteLine(second);
System.Console.WriteLine(differenceX);
double scale = 0.528;
//Measure distance between two points in the corners matrix
for (int i = 0; i < 4; i++)
{
//if the array element integer is even measure the x distance between itself and the next point in the array
if (i % 2 == 0)
{
int xDist = corners1[i + 1].X - corners1[i].X;
dimensions[i] = xDist;
scaled[i] = xDist * scale;
System.Console.WriteLine("From the For-loop: The X Distance Between the Point ({0}) and Point ({1}) is {2}", corners1[i], corners1[i + 1], xDist);
//textBox1.Text = "From the For-loop: The X Distance Between the Point" + corners1[i] + " and Point " + corners1[i + 1] + " is " + xDist;
}
//if the element is the last element in the array measure between itself and the first point
else if (i == 3)
{
int yDist = corners1[i].Y - corners1[0].Y;
scaled[i] = yDist * scale;
dimensions[i] = yDist;
System.Console.WriteLine("From the For-loop: The Y Line Distance Between the Point ({0}) and Point ({1}) is {2}", corners1[i], corners1[0], yDist);
}
//if the array element integer is odd measure the y distance between itself and the next point in the array
else
{
int yDist = corners1[i + 1].Y - corners1[i].Y;
dimensions[i] = yDist;
scaled[i] = yDist * scale;
System.Console.WriteLine("From the For-loop: The Y Line Distance Between the Point ({0}) and Point ({1}) is {2}", corners1[i], corners1[i + 1], yDist);
}
System.Console.WriteLine("The dimension of side {0} is {1} unscaled", i + 1, dimensions[i]);
System.Console.WriteLine("The dimension of side {0} is {1} inches scaled", i + 1, scaled[i]);
}
//create a green label for each corner in image
PointsMarker marker = new PointsMarker(corners1, System.Drawing.Color.Green, 4);
// Apply the corner-marking filter
Bitmap markers = marker.Apply(image);
//save the image after it has mask applied to it
markers.Save(@"C:\Users\Main\Documents\Image Processing\ImageProcessing_0.2.1\Pictures\testResult.png", System.Drawing.Imaging.ImageFormat.Png);
string messageOut = "\t Hello, This is meZtech \n \n";
messageOut += Environment.NewLine;
for (int i = 0; i < scaled.Length - 1; i++)
{
int j = i + 1;
messageOut += "The dimesnion for side " + j + " is " + scaled[i] + " inches \n";
messageOut += Environment.NewLine;
}
messageOut += "\n Your Part has passed inspection!!!";
messageOut += Environment.NewLine;
messageOut += "\n The Distance Moved in the X Direction is: " + differenceX;
messageOut += Environment.NewLine;
messageOut += "\n The Distance Moved in the Y Direction is: " + differenceY;
messageOut += Environment.NewLine;
messageOut += "\n The Distance Moved in the 3 corner is: " + distanceP;
messageOut += Environment.NewLine;
messageOut += "\n The Amount of points in the matrix: " + corners1.Count;
messageOut += Environment.NewLine;
MessageBox.Show(messageOut);
ret.Tag = messageOut;
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
// apply the filter
Bitmap grayImage = filter.Apply(image);
System.Collections.Generic.List<AForge.IntPoint> grayCornerMatrix = fast.ProcessImage(grayImage);
grayImage.Save(@"C:\Users\Main\Documents\Image Processing\ImageProcessing_0.2.1\Pictures\grayResult.png", System.Drawing.Imaging.ImageFormat.Png);
PointsMarker grayMarkers = new PointsMarker(grayCornerMatrix, System.Drawing.Color.Red, 4);
// Apply the corner-marking filter
Bitmap grayProcessedImage = grayMarkers.Apply(grayImage);
grayProcessedImage.Save(@"C:\Users\Main\Documents\Image Processing\ImageProcessing_0.2.1\Pictures\grayCornerResult.png", System.Drawing.Imaging.ImageFormat.Png);
//Call out to the message log
messageOut += "\n The Number of points in the grey matrix: " + grayCornerMatrix.Count;
messageOut += Environment.NewLine;
MessageBox.Show(messageOut);
ret.Tag = messageOut;
return ret;
}
public override System.Windows.Forms.Control GetParameterWindow()
{
return new KrischEdgeDetectorParmForm();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ImageProcessing
{
public partial class KrischEdgeDetectorParmForm : ParmFormBase
{
private KrischEdgeDetectorParms mParms = new KrischEdgeDetectorParms();
public KrischEdgeDetectorParmForm()
{
InitializeComponent();
derivateiveEdgeDetectorParmsBindingSource.DataSource = mParms;
}
void mParms_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
raiseParmChangedEvent();
}
private void DerivativeEdgeDetectorParmForm_Load(object sender, EventArgs e)
{
cbChannels.Items.Clear();
cbChannels.Items.Add(Channels.R);
cbChannels.Items.Add(Channels.G);
cbChannels.Items.Add(Channels.B);
cbChannels.Items.Add(Channels.RGB);
}
public KrischEdgeDetectorParms Parms
{
get
{
return mParms;
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
raiseParmChangedEvent();
}
private void panelBorderColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
panelBorderColor.BackColor = colorDialog1.Color;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
{
}
}
//void KrischEdgeDetector(object sender, EventArgs e)
//{
//}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ImageProcessing
{
public enum Channels
{
A,
R,
G,
B,
RGB
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
namespace ImageProcessing
{
public class SobelEdgeDetectorParms
{
[NotifyParentProperty(true)]
public Channels Channel { get; set; }
[NotifyParentProperty(true)]
public int Threshold { get; set; }
[NotifyParentProperty(true)]
public bool ConvertToGrayscale { get; set; }
[NotifyParentProperty(true)]
public Color EdgeColor { get; set; }
[NotifyParentProperty(true)]
public bool CopyOriginal { get; set; }
public SobelEdgeDetectorParms()
{
Channel = Channels.RGB;
Threshold = 50;
ConvertToGrayscale = true;
EdgeColor = Color.Yellow;
CopyOriginal = true;
}
}
public class SobelEdgeDetector : ImageFilter<SobelEdgeDetectorParms>
{
private Color grayscale(Color cr)
{
return Color.FromArgb(cr.A, (int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11),
(int)(cr.R * .3 + cr.G * .59 + cr.B * 0.11));
}
public override Bitmap FilterProcessImage(SobelEdgeDetectorParms parms, Bitmap image)
{
Bitmap ret = new Bitmap(image.Width, image.Height);
for (int i = 1; i < image.Width - 1; i++)
{
for (int j = 1; j < image.Height - 1; j++)
{
Color cr = image.GetPixel(i + 1, j);
Color cl = image.GetPixel(i - 1, j);
Color cu = image.GetPixel(i, j - 1);
Color cd = image.GetPixel(i, j + 1);
Color cld = image.GetPixel(i - 1, j + 1);
Color clu = image.GetPixel(i - 1, j - 1);
Color crd = image.GetPixel(i + 1, j + 1);
Color cru = image.GetPixel(i + 1, j - 1);
int dx = 0, dy = 0;
switch (parms.Channel)
{
case Channels.R:
dx = cld.R + 2 * cd.R + crd.R - (clu.R + 2 * cu.R + cru.R);
dy = crd.R + 2 * cr.R + cru.R - (cld.R + 2 * cl.R + clu.R);
break;
case Channels.G:
dx = cld.G + 2 * cd.G + crd.G - (clu.G + 2 * cu.G + cru.G);
dy = crd.G + 2 * cr.G + cru.G - (cld.G + 2 * cl.G + clu.G);
break;
case Channels.B:
dx = cld.B + 2 * cd.B + crd.B - (clu.B + 2 * cu.B + cru.B);
dy = crd.B + 2 * cr.B + cru.B - (cld.B + 2 * cl.B + clu.B);
break;
case Channels.RGB:
dx = grayscale(cld).B + 2 * grayscale(cd).B + grayscale(crd).B - (grayscale(clu).B + 2 * grayscale(cu).B + grayscale(cru).B);
dy = grayscale(crd).B + 2 * grayscale(cr).B + grayscale(cru).B - (grayscale(cld).B + 2 * grayscale(cl).B + grayscale(clu).B);
break;
}
double power = Math.Abs(dx) + Math.Abs(dy);
if (power > parms.Threshold)
ret.SetPixel(i, j, parms.EdgeColor);
else
{
if (parms.CopyOriginal)
{
Color c = image.GetPixel(i, j);
if (parms.ConvertToGrayscale)
{
ret.SetPixel(i, j,
Color.FromArgb(255,
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11),
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11),
(int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11)));
}
else
ret.SetPixel(i, j, c);
}
else
ret.SetPixel(i, j, Color.White);
}
}
}
return ret;
}
public override System.Windows.Forms.Control GetParameterWindow()
{
return new SobelEdgeDetectorParmForm();
}
}
}
| f281cd8d6feadbe310e21ab8251857cfb1766bff | [
"C#"
]
| 12 | C# | tjm5114/ImageProcessing_0.2.1 | 328e1610c32386108359a80f8ecc2832d795707a | 9d4478574046700ad0c807fcec43e8410b4f8580 |
refs/heads/master | <repo_name>niharr7/chatAppRepo<file_sep>/extension1/panel.js
var menuLeft = document.getElementById( 'cbp-spmenu-s1' ),
menuRight = document.getElementById( 'cbp-spmenu-s2' ),
menuTop = document.getElementById( 'cbp-spmenu-s3' ),
menuBottom = document.getElementById( 'cbp-spmenu-s4' ),
showLeft = document.getElementById( 'showLeft' ),
showRight = document.getElementById( 'showRight' ),
showTop = document.getElementById( 'showTop' ),
showBottom = document.getElementById( 'showBottom' ),
showLeftPush = document.getElementById( 'showLeftPush' ),
showRightPush = document.getElementById( 'showRightPush' ),
body = document.body;
$(document).ready(function(){
classie.toggle( menuLeft, 'cbp-spmenu-open' );
});
<file_sep>/extension1/popup1.js
$(document).ready(function(){
var newJSONArray= [];
var JSONRules1= [];
var container = $('#cblist');
var id = 0;
$.getJSON('test.json', function(data) {
for (var prop in data) {
JSONRules1.push(data[prop]);
}
//console.log("1" + JSON.stringify(JSONRules1[0]));
var JSONRules=JSONRules1[0];
for(var i=0;i<JSONRules.length;i++){
//console.log(JSONRules[i]);
$('<input />', { type: 'checkbox', id:id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text:JSONRules[i].description}).appendTo(container);
$('<br >', { 'for': 'cb'+id, text:JSONRules[i].description}).appendTo(container);
id++;
}
appendCheckBox();
});
var JSONRules=JSON.stringify(JSONRules1);
//console.log("2" + JSONRules)
// addCheckbox(JSONRules);
function appendCheckBox(){
$('input[type="checkbox"]').change(function () {
var name = $(this).attr("id");
var check = $(this).prop('checked');
if(name=="checkAll" && check ==true) {
newJSONArray=JSONRules1[0];
}
if(name=="checkAll" && check ==false) {
newJSONArray=[];
}
if(name!="checkAll" && check){
alert("true"+name);
alert("tnihar"+JSONRules1[0]);
newJSONArray.push([name,JSONRules1[0][name]]);
}
if(!check && name!="checkAll"){
alert("false"+name);
var index;
for(var i = 0; i < newJSONArray.length; i++) {
if(newJSONArray[i][0] ==name) {
index=i;
}
}
newJSONArray.splice(index,1);
}
console.log(newJSONArray);
});
}
});
function addCheckbox(arrayJSON) {
console.log(arrayJSON);
var container = $('#cblist');
var id = 0;
for(var i=0;i<arrayJSON.length;i++){
console.log(arrayJSON[i]);
$('<input />', { type: 'checkbox', id:id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text:arrayJSON[0][i].description}).appendTo(container);
$('<br >', { 'for': 'cb'+id, text:arrayJSON[i].description}).appendTo(container);
id++;
}
}
$("#checkAll").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});<file_sep>/extension2/background.js
var headerInfo = {};
chrome.webRequest.onHeadersReceived.addListener(function(n) {
parseInt(n.tabId, 10) > 0 && (typeof headerInfo[n.tabId].response[0] != "undefined" && headerInfo[n.tabId].response[0].requestId !== n.requestId && (headerInfo[n.tabId].response = []), headerInfo[n.tabId].response.push(n))
}, {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["responseHeaders"]), chrome.webRequest.onSendHeaders.addListener(function(n) {
parseInt(n.tabId, 10) > 0 && (typeof headerInfo[n.tabId] == "undefined" ? (headerInfo[n.tabId] = {}, headerInfo[n.tabId].request = [], headerInfo[n.tabId].response = []) : headerInfo[n.tabId].request[0].requestId !== n.requestId && (headerInfo[n.tabId].request = []), headerInfo[n.tabId].request.push(n))
}, {
urls: ["<all_urls>"],
types: ["main_frame"]
}, ["requestHeaders"]); <file_sep>/extension1/popup.js
document.getElementById("btnModify").onclick = fun;
function fun(){
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
}
| 4b15aabf3eb7c9c4b76370c5483c0ac2aed36b75 | [
"JavaScript"
]
| 4 | JavaScript | niharr7/chatAppRepo | 7fc95b9febe53ddbaaf8d2bcb2e7d860b510aa51 | f65992e48033fe3ab8c40025eabb3bcb84bd75c0 |
refs/heads/master | <file_sep>var map;
var markers = [];
function initMap() {
var sanDiego = {lat: 32.7913085, lng: -117.1523774};
// Constructor creates a new map - only center and zoom are required.
map = new google.maps.Map(document.getElementById('map'), {
center: sanDiego,
zoom: 11
});
// Create a marker for each location
for(var i = 0; i < locations.length; i++) {
var title = locations[i].title;
var position = locations[i].location;
var yelpTitle = locations[i].yelpTitle;
var marker = new google.maps.Marker({
position: position,
map: map,
title: title,
yelpTitle: yelpTitle,
id: i,
});
markers.push(marker);
marker.addListener('click', function() {
populateInfoWindow(this, infoWindow);
});
marker.addListener('click', function() {
toggleBounce(this);
});
var yelp_url = 'https://api.yelp.com/v2/business/' + yelpTitle;
getAjax(yelp_url, i);
}
var infoWindow = new google.maps.InfoWindow();
//Content to be displayed in infoWindow
function populateInfoWindow(marker, infowindow) {
var name;
var url;
var rating;
var phone;
var address;
var content;
name = marker.yelpData.name ? marker.yelpData.name : 'Name unavailable';
url = marker.yelpData.url ? marker.yelpData.url : 'Url unavailable';
rating = marker.yelpData.rating_img_url_small ? marker.yelpData.rating_img_url_small : 'Rating unavailable';
phone = marker.yelpData.display_phone ? marker.yelpData.display_phone : 'Phone number unavailable';
address = marker.yelpData.location ? marker.yelpData.location.display_address.join(' ') : 'Address unavailable';
content = '<div>';
content += ('<strong>' + name + ' ' + '</strong>');
content += (' <a target="_blank" href=' + url + '><i class="fa fa-external-link" aria-hidden="true"></i></a>');
content += '<br>';
content += ('<img src="' + rating + '" alt="Number of yelp stars"' +'/>');
content += '<br>';
content += phone;
content += '<br>';
content += address;
content += '</div>';
infowindow.marker = marker;
infowindow.open(map, marker);
infowindow.setContent(content);
}
function toggleBounce(marker) {
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function(){ marker.setAnimation(null); }, 1400);
}
}
var locations = [
{title: 'El Patron',
yelpTitle: 'el-patron-traditional-mexican-grill-san-diego',
location: {lat: 32.9190785, lng: -117.1230289},
},
{title: 'Tacos El Gordo',
yelpTitle: 'tacos-el-gordo-chula-vista-3',
location: {lat: 32.6382757, lng: -117.1124098},
},
{title: 'Lucha Libre Taco Shop',
yelpTitle: 'lucha-libre-gourmet-taco-shop-san-diego',
location: {lat: 32.7495285, lng: -117.1563436},
},
{title: "Lolita's Taco Shop",
yelpTitle: 'lolitas-taco-shop-san-diego',
location: {lat: 32.8323715, lng: -117.1626472},
},
{title: 'Tacos El Panson',
yelpTitle: 'tacos-el-panson-san-diego',
location: {lat: 32.8325007, lng: -117.2304995},
}
];
//Array of just the location titles
var titlesArray = locations.map(function(value) {
return value.title;
});
function ViewModel() {
var self = this;
this.inputValue = ko.observable('');
this.titles = ko.observableArray(titlesArray);
this.filteredTitles = ko.computed(function(){
for(var i = 0; i < markers.length; i++) {
if(markers[i].title.toLowerCase().includes(self.inputValue().toLowerCase()) === false) {
markers[i].setVisible(false);
} else {
markers[i].setVisible(true);
}
}
return self.titles().filter(function(value){
return value.toLowerCase().includes(self.inputValue().toLowerCase());
});
});
// Add event listener to the list items
// When clicked, triggers info window for that restaurant
this.listen = function (title) {
for(var i = 0; i < markers.length; i++) {
if(markers[i].title.includes(title)) {
google.maps.event.trigger(markers[i], 'click');
}
}
};
}
ko.applyBindings(new ViewModel());
/// YELP API CODE
// ---------------------------------------------
const YELP_BASE_URL = 'https://api.yelp.com/v2/';
const YELP_KEY = 'MRwDQFLrZ7dbekGz6EeUiw';
const YELP_TOKEN = '<KEY>';
const YELP_KEY_SECRET = '<KEY>';
const YELP_TOKEN_SECRET = '<KEY>';
function nonce_generate() {
return (Math.floor(Math.random() * 1e12).toString());
}
// Makes an ajax call to retrieve yelp API data
// Success function sets API data as a property of a marker
function getAjax(yelp_url, i) {
var parameters = {
oauth_consumer_key: YELP_KEY,
oauth_token: YELP_TOKEN,
oauth_nonce: nonce_generate(),
oauth_timestamp: Math.floor(Date.now()/1000),
oauth_signature_method: 'HMAC-SHA1',
oauth_version : '1.0',
callback: 'cb' // This is crucial to include for jsonp implementation in AJAX or else the oauth-signature will be wrong.
};
var encodedSignature = oauthSignature.generate('GET',yelp_url, parameters, YELP_KEY_SECRET, YELP_TOKEN_SECRET);
parameters.oauth_signature = encodedSignature;
var settings = {
url: yelp_url,
data: parameters,
cache: true, // This is crucial to include as well to prevent jQuery from adding on a cache-buster parameter "_=23489489749837", invalidating our oauth-signature
dataType: 'jsonp',
beforeSend: function() {
markers[i].yelpData = 'notready';
},
success: function(results) {
markers[i].yelpData = results;
},
error: function(error) {
markers[i].yelpData = 'Error';
}
};
$.ajax(settings);
}
<file_sep># Neighborhood Maps Project
Going to school in Northern California made me realize how much I love Mexican food. Having been born and raised in San Diego, there really is no comparison up north. Whenever I came home to visit, I would immediately get a burrito from one of my favorite taco shops. This app shows a list of my favorite taco shops in San Diego County.

## Get Started
Clone this repo, navigate to the folder and install <a href="https://github.com/bettiolo/oauth-signature-js">oauth-signature-js</a>
```
npm install oauth-signature
```
Open the index.html file in a browser
## Reflection
This app uses <a href="http://knockoutjs.com/">knockout.js</a> to handle a dynamic list of titles that renders depending if it satisfies a filter.
**Google Maps API** is used to display a map with markers at each restaurant location. Clicking each marker triggers an animation, and an infowindow to display with more information about that restaurant.
**Yelp API** An ajax request is made to retrieve data from the Yelp API. This data is used to display more info about a restaurant in its respective info window.
| 97740c55ae6d95d2823ead28459fc9ea000a2dca | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | caesarsalad93/neighborhood-map-project | c8de211b1fa580904a5f4165dc4c44124775419c | 1f0734b30531e4baa8d41262fde23cf46f420c0d |
refs/heads/master | <repo_name>sairina/pokedex<file_sep>/src/Pokecard.js
/**Shows a single Pokemon, with their name, image, and type. */
import React from 'react';
import './Pokecard.css';
function Pokecard(props) {
const { id, name, type, base_experience } = props.pokemon;
const image = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`
return (
<div className="Pokecard">
<div className="Pokecard-name">{name}</div>
<img className="Pokecard-image" src={image} />
<div className="Pokecard-details">Type: {type}</div>
<div className="Pokecard-details">EXP: {base_experience}</div>
</div>
);
}
export default Pokecard; | 2b6457dd397341b673a96ea861dbe9a1e80d3048 | [
"JavaScript"
]
| 1 | JavaScript | sairina/pokedex | fb7b13a3989f5179db8130c72b590110aca7bfeb | 7fcf9cad3a0795e6a2cc5317150b1752235dc47b |
refs/heads/master | <file_sep>class Photo < ActiveRecord::Base
mount_uploader :file, Uploader
end
<file_sep>class Uploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process :resize_to_fit => [200,200]
storage :file
def store_dir
'image'
end
end
<file_sep>require 'haml'
get '/' do
@photos= Photo.all
erb :index
end
get '/image/new' do
haml :upload
end
post '/image/new' do
Photo.create(params)
return "success"
end
| 7b0acf5943ce21fd47dcd73f11aa5cfbc28a0542 | [
"Ruby"
]
| 3 | Ruby | wontwon/toybox | 62fe43d16e9a0b4c36bfbe84d59502928f0d0649 | 83d7043b50c8cff865343f7d0c9debd0759a96cd |
refs/heads/master | <repo_name>luclx/Android-Architecture<file_sep>/AndroidArchitecture/domain/src/main/java/tisoul/dev/domain/domain/usecase/GetUserProfile.java
package tisoul.dev.domain.domain.usecase;
import tisoul.dev.domain.domain.usecase.base.UseCase;
import tisoul.dev.domain.model.UserProfile;
public interface GetUserProfile
extends UseCase<Void, UserProfile>{
}
<file_sep>/AndroidArchitecture/domain/build.gradle
apply plugin: 'java'
apply plugin: 'me.tatarka.retrolambda'
configurations {
provided
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'io.reactivex.rxjava2:rxjava:2.1.1'
provided 'javax.annotation:jsr250-api:1.0'
compile 'javax.inject:javax.inject:1'
}
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8<file_sep>/README.md
# Android-Architecture
All architecture model are applied into an android project
<file_sep>/AndroidArchitecture/app/src/main/java/tisoul/dev/androidarchitecture/mvvm/MVVMProfileFragment.java
package tisoul.dev.androidarchitecture.mvvm;
import android.app.Fragment;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import javax.inject.Inject;
import tisoul.dev.androidarchitecture.BR;
import tisoul.dev.androidarchitecture.ProfileActivity;
import tisoul.dev.androidarchitecture.R;
import tisoul.dev.androidarchitecture.databinding.FragmentProfileMvvmBinding;
public class MVVMProfileFragment
extends Fragment {
@Inject
ProfileViewModel viewModel;
FragmentProfileMvvmBinding dataBinding;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpInjector();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
dataBinding = DataBindingUtil
.inflate(
inflater,
R.layout.fragment_profile_mvvm,
container,
false);
return dataBinding.getRoot();
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dataBinding.setVariable(BR.profile, viewModel);
dataBinding.executePendingBindings();
getDataStream(dataBinding.tvName)
.subscribe(name -> viewModel.name.set(name));
getDataStream(dataBinding.tvEmail)
.subscribe(email -> viewModel.email.set(email));
}
@Override
public void onStart() {
super.onStart();
viewModel.subscribe();
}
@Override
public void onStop() {
super.onStop();
viewModel.unSubscribe();
}
@Override
public void onDestroyView() {
super.onDestroyView();
dataBinding.unbind();
}
private io.reactivex.Observable<String> getDataStream(TextView view) {
return RxTextView
.afterTextChangeEvents(view)
.skipInitialValue()
.map(TextViewAfterTextChangeEvent::editable)
.map(Editable::toString);
}
private void setUpInjector() {
((ProfileActivity) getActivity())
.profileComponent
.inject(this);
}
}
<file_sep>/AndroidArchitecture/app/src/main/java/tisoul/dev/androidarchitecture/mvp/MVPProfileFragment.java
package tisoul.dev.androidarchitecture.mvp;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import javax.inject.Inject;
import tisoul.dev.androidarchitecture.ProfileActivity;
import tisoul.dev.androidarchitecture.R;
public class MVPProfileFragment
extends Fragment
implements Profile.View {
EditText tvName;
EditText tvEmail;
@Inject
Profile.Presenter presenter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpInjector();
presenter.setView(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_mvp, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setUpView(view);
}
@Override
public void onStart() {
super.onStart();
presenter.subscribe();
}
@Override
public void onStop() {
super.onStop();
presenter.unSubscribe();
}
@Override
public void setName(CharSequence name) {
tvName.setText(name);
}
@Override
public void setEmail(CharSequence email) {
tvEmail.setText(email);
}
public void onUpdateClick(View view) {
presenter
.update(
tvName.getText(),
tvEmail.getText());
}
private void setUpView(View view) {
tvName = (EditText) view.findViewById(R.id.tv_name);
tvEmail = (EditText) view.findViewById(R.id.tv_email);
view.findViewById(R.id.bt_update)
.setOnClickListener(this::onUpdateClick);
}
private void setUpInjector() {
((ProfileActivity) getActivity())
.profileComponent
.inject(this);
}
}
<file_sep>/AndroidArchitecture/app/src/main/java/tisoul/dev/androidarchitecture/mvp/Profile.java
package tisoul.dev.androidarchitecture.mvp;
public class Profile {
interface View {
void setName(CharSequence name);
void setEmail(CharSequence email);
}
public interface Presenter {
void setView(View view);
void subscribe();
void unSubscribe();
void update(CharSequence name, CharSequence email);
}
}
| 08fe8097fa3f39f21d8358ce7309c2482cf68427 | [
"Markdown",
"Java",
"Gradle"
]
| 6 | Java | luclx/Android-Architecture | 4e70bceef462414142f3b71a5dd6948f36a21d1e | 1488c039a2e63d5e8f21c9f5064d0f4c528d8050 |
refs/heads/master | <file_sep>import React from 'react';
import GitHubIcon from '@material-ui/icons/GitHub';
import LinkedInIcon from '@material-ui/icons/LinkedIn';
import EmailIcon from '@material-ui/icons/Email';
function Footer() {
return (
<section>
<div>
<a className="icon" target="_blank" rel="noreferrer" href="https://github.com/jbeedle19"><GitHubIcon fontSize="large" /></a>
<a className="icon" target="_blank" rel="noreferrer" href="https://www.linkedin.com/in/joshua-beedle/"><LinkedInIcon fontSize="large" /></a>
<a className="icon" href="mailto:<EMAIL>"><EmailIcon fontSize="large" /></a>
</div>
</section>
)
}
export default Footer;<file_sep>import React from 'react';
import Project from '../Project';
function Portfolio() {
return(
<section id="work" className="contact-section">
<div className="flex-row">
<h2 className="section-title primary-border">
Work
</h2>
</div>
<div>
<Project />
</div>
</section>
)
}
export default Portfolio;<file_sep># <NAME>'s Portfolio
## Purpose
A website that showcases <NAME>'s professional portfolio.
## Built With
* React
* HTML, CSS, JavaScript
# Website
https://jbeedle19.github.io/react-portfolio/
# Walkthrough
<file_sep>import React from 'react';
function Nav(props) {
const navSections = ['About Me', 'Portfolio', 'Contact', 'Resume'];
return (
<nav>
<ul>
{navSections.map(section => (
<li key={section}>
<button
onClick={() => props.handleSectionChange(section)}
>
{section}
</button>
</li>
))}
</ul>
</nav>
);
}
export default Nav;<file_sep>import React from 'react';
import pdf from '../../assets/images/JoshuaBeedleResume.pdf';
import ListGroup from 'react-bootstrap/ListGroup';
import DescriptionIcon from '@material-ui/icons/Description';
function Resume() {
const frontEndProficiencies = ["HTML", "CSS", "JavaScript", "jQuery", "React", "Bootstrap, Tailwind, Material-UI", "Responsive Design"];
const backEndProficiencies = ["APIs", "Node", "Express", "MySQL & Sequelize", "MongoDB & Mongoose", "REST", "GraphQL"];
return (
<section className='contact-section'>
<div>
<h2 className='section-title primary-border'>Resume</h2>
</div>
<div>
<h3 className="resume">Download My Resume | <a className="resume" target="_blank" rel="noreferrer" href={pdf}><DescriptionIcon fontSize="large"/></a></h3>
</div>
<div>
<h3>Front-end Proficiencies</h3>
<ListGroup variant="flush" className="my-3">
{frontEndProficiencies.map((context) => {
return <ListGroup.Item
key={context}
style={{backgroundColor: '#7389ae'}}
className="w-50 ml-5">
* {context}
</ListGroup.Item>
})}
</ListGroup>
</div>
<div>
<h3>Back-end Proficiencies</h3>
<ListGroup variant="flush" className='my-3'>
{backEndProficiencies.map((context) => {
return <ListGroup.Item
key={context}
style={{backgroundColor: '#7389ae'}}
className="w-50 ml-5">
* {context}
</ListGroup.Item>
})}
</ListGroup>
</div>
</section>
)
}
export default Resume;<file_sep>import React, { useState } from 'react';
import Header from './components/Header';
import About from './components/About';
import Portfolio from './components/Portfolio';
import Resume from './components/Resume';
import ContactForm from './components/Contact';
import Footer from './components/Footer';
function App() {
const [currentNavSection, handleSectionChange] = useState('About Me');
const renderSection = () => {
switch (currentNavSection) {
case 'Portfolio': return <Portfolio />;
case 'Contact': return <ContactForm />;
case 'Resume': return <Resume />;
default: return <About />;
}
};
return (
<div>
<Header
currentNavSection={currentNavSection}
handleSectionChange={handleSectionChange}
/>
<main>
<div>
{renderSection(currentNavSection)}
</div>
</main>
<footer>
<Footer />
</footer>
</div>
);
}
export default App;<file_sep>import React from 'react';
import headshot from '../../assets/images/headshot.jpg';
function About() {
return(
<section className='about-section'>
<div className='flex-row'>
<h2 className='section-title primary-border'>
About Me
</h2>
</div>
<article className='about-me-info'>
<div className='headshot'>
<img src={headshot} alt='headshot' />
</div>
<div className='about-text'>
<p>
Full-stack web developer with a background in teaching and customer service
looking to create unique user experiences on the web. Earned a certificate in
full-stack web development from the University of Pennsylvania, with skills
in HTML, CSS, JavaScript, MERN stack, MySql, and responsive web design.
<br />
<br />
Quick learner that is calm under pressure and has excellent time management
skills in order to easily meet deadlines and manage multiple tasks at the same time.
Was quickly elevated to a leadership role at a Four Diamond hotel after only just a few
months of working due to a strong work ethic. Well-organized and flexible team player that
also does well working independently.
</p>
</div>
</article>
</section>
);
}
export default About; | ba8589f3930cc5248825b66fdff12b0cf31335e1 | [
"JavaScript",
"Markdown"
]
| 7 | JavaScript | jbeedle19/react-portfolio | 9396e3477d9bc157ab9b350937afceebefc2eef3 | 08f242c3713d53bbd355be08168381f2d1e60293 |
refs/heads/master | <repo_name>AlessiaYChen/gcpe-hub-api<file_sep>/Gcpe.Hub.API/Startup.cs
using System.Data.SqlClient;
using AutoMapper;
using Gcpe.Hub.Data.Entity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Gcpe.Hub.API
{
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
Environment = env;
}
private IConfiguration Configuration { get; }
private IHostingEnvironment Environment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddDbContext<HubDbContext>(options => options.UseSqlServer(Configuration["HubDbContext"])
.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)));
services.AddMvc()
.AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = Configuration["Jwt:Authority"];
o.Audience = Configuration["Jwt:Audience"];
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = ctx =>
{
ctx.NoResult();
ctx.Response.StatusCode = 500;
ctx.Response.ContentType = "text/plain";
if (Environment.IsDevelopment())
{
return ctx.Response.WriteAsync(ctx.Exception.ToString());
}
return ctx.Response.WriteAsync("An error occurred processing your authentication");
}
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("Administrator", policy => policy.RequireClaim("user_roles", "[Administrators]"));
});
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc("v1", new Info
{
Version = "Alpha",
Title = "BC Gov Hub API service",
Description = "The .Net Core API for the Hub"
});
setupAction.OperationFilter<OperationIdCorrectionFilter>();
});
services.AddHealthChecks()
.AddCheck("sql", () =>
{
using (var connection = new SqlConnection(Configuration["HubDbContext"]))
{
try
{
connection.Open();
}
catch (SqlException)
{
return HealthCheckResult.Unhealthy();
}
return HealthCheckResult.Healthy();
}
})
.AddCheck("Webserver is running", () => HealthCheckResult.Healthy("Ok"));
services.AddCors();
}
private class OperationIdCorrectionFilter : IOperationFilter
{ // GetActivity() instead of ApiActivitiesByIdGet()
public void Apply(Operation operation, OperationFilterContext context)
{
if (context.ApiDescription.ActionDescriptor is ControllerActionDescriptor actionDescriptor)
{
operation.OperationId = actionDescriptor.ActionName;
}
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// app.UseHsts();
}
app.UseHealthChecks("/hc", new HealthCheckOptions { AllowCachingResponses = false });
// app.UseHttpsRedirection();
// temporary CORS fix
app.UseCors(opts => opts.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "BC Gov Hub API service");
});
}
}
}
<file_sep>/Gcpe.Hub.API/Controllers/SearchController.cs
using AutoMapper;
using Gcpe.Hub.API.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading;
using Gcpe.Hub.Data.Entity;
namespace Gcpe.Hub.API.Controllers
{
[Route("api/[Controller]")]
[ApiController]
[Produces("application/json")]
public class SearchController : ControllerBase
{
private readonly HubDbContext dbContext;
private readonly ILogger<SearchController> logger;
private readonly IMapper mapper;
public SearchController(HubDbContext dbContext,
ILogger<SearchController> logger,
IMapper mapper)
{
this.dbContext = dbContext;
this.logger = logger;
this.mapper = mapper;
}
[HttpGet]
public IActionResult Search([FromQuery] SearchParams searchParams)
{
Thread.Sleep(1000); // sleep so it takes a second to return the results to the client
return Ok();// _repository.GetAllArticles(searchParams));
}
[HttpGet("suggestions")]
public IActionResult Suggestions()
{
var suggestions = ActivitiesController.QueryAll(dbContext)
.Take(10)
.Select(a => a.Title);
return Ok(suggestions);
}
}
}
| 44fec2b954c477d356616a9fdd4404f47d58696a | [
"C#"
]
| 2 | C# | AlessiaYChen/gcpe-hub-api | 282ec53fbc30f76d59e046d51403a06d2567a39e | 8785b62c99523ae7b3b36db20d483b22c5bee5f5 |
refs/heads/master | <repo_name>Luisburgoro/Compania<file_sep>/src/main/java/Departament.java
import java.util.ArrayList;
// Se crea clase Departament
public class Departament {
public Employee managedBy;//atributo perteneciente a la clase Employee
private ArrayList<Employee>employeeArrayList;
private ArrayList<Office>officeArrayList;
/*- En la línea 6 de código se asocia el ArrayList de tipo Employee a la clase Departament.
- En la linea 7 de código se asocia el ArrayList de tipo Office a la clase Departament.
}
<file_sep>/src/main/java/Employee.java
//Se crea clase Employee
public class Employee {
private String name;// atributo de acceso privado perteneciente a la clase Employee
private String title;//atributo de acceso privado perteneciente a la clase Employee
public Departament manage;// Se asocia el atributo manage a la clase Employee de acuerdo a la clase Departamento
}
<file_sep>/src/main/java/Office.java
public class Office {
private String address;
}
<file_sep>/README.md
# Compania
## Entendiendo el código fuente
El analista de vuestro equipo de desarrollo ha terminado de modelar los aspectos
fundamentales de la empresa del cliente. Le presenta al resto del equipo de desarrollo
el siguiente modelo de clases UML, tras lo cual les pide implementar en lenguaje Java
“el esqueleto” de las clases y relaciones que se puedan inferir del modelo.
| da9e0f432e3ef1e5e1d4591a37619f0ca054df25 | [
"Markdown",
"Java"
]
| 4 | Java | Luisburgoro/Compania | f0efbb79cd037b6deb0612d795d0fde96c401190 | 08f18bf815a559fe3c783042cc9ec60e17fc62c4 |
refs/heads/master | <file_sep>import React from 'react';
import { WButton, WRow, WCol } from 'wt-frontend';
const TableHeader = (props) => {
const buttonStyle = props.disabled ? ' table-header-button-disabled ' : 'table-header-button ';
const clickDisabled = () => { };
//const { data } = props;
const handleSortByTask = () => {
props.SBC(0);
}
const handleSortByTaskReverse = () => {
props.SBC(1);
}
const handleSortByDueDate = () => {
props.SBC(2);
}
const handleSortByDueDateReverse = () => {
props.SBC(3);
}
const handleSortByStatus = () => {
props.SBC(4);
}
const handleSortByStatusReverse = () => {
props.SBC(5);
}
const handleSortByAssignedTo = () => {
props.SBC(6);
}
const handleSortByAssignedToReverse = () => {
props.SBC(7);
}
const handleCloseList = () => {
props.clearTransaction();
props.setActiveList({});
}
return (
<WRow className="table-header">
<WCol size="3">
<WButton className='table-header-section' wType="texted" onClick = {!props.isReversedTask ? handleSortByTask : handleSortByTaskReverse}>Task</WButton>
</WCol>
<WCol size="2">
<WButton className='table-header-section' wType="texted" onClick = {!props.isReversedDD ? handleSortByDueDate : handleSortByDueDateReverse}>Due Date</WButton>
</WCol>
<WCol size="2">
<WButton className='table-header-section' wType="texted" onClick = {!props.isReversedStatus ? handleSortByStatus : handleSortByStatusReverse}>Status</WButton>
</WCol>
<WCol size="2">
<WButton className='table-header-section' wType="texted" onClick = {!props.isReversedAssignedTo ? handleSortByAssignedTo : handleSortByAssignedToReverse}>Assigned To</WButton>
</WCol>
<WCol size="2">
<div className="table-header-buttons">
{props.auth && props.hasUndo()
? <WButton className="sidebar-buttons undo-redo" onClick={props.undo} wType="texted" clickAnimation="ripple-light" shape="rounded">
<i className="material-icons">undo</i>
</WButton>
: <WButton className="sidebar-buttons undo-redo-disabled" wType="texted" shape="rounded" shape="rounded">
<i className="material-icons">undo</i>
</WButton>
}
{props.auth && props.hasRedo()
? <WButton className="sidebar-buttons undo-redo" onClick={props.redo} wType="texted" clickAnimation="ripple-light" shape="rounded">
<i className="material-icons">redo</i>
</WButton>
: <WButton className="sidebar-buttons undo-redo-disabled" wType="texted" shape="rounded">
<i className="material-icons">redo</i>
</WButton>
}
<WButton onClick={props.disabled ? clickDisabled : props.addItem} wType="texted" className={`${buttonStyle}`}>
<i className="material-icons">add_box</i>
</WButton>
<WButton onClick={props.disabled ? clickDisabled : props.setShowDelete} wType="texted" className={`${buttonStyle}`}>
<i className="material-icons">delete_outline</i>
</WButton>
<WButton onClick={props.disabled ? clickDisabled : handleCloseList} wType="texted" className={`${buttonStyle}`}>
<i className="material-icons">close</i>
</WButton>
</div>
</WCol>
</WRow>
);
};
export default TableHeader;<file_sep>const ObjectId = require('mongoose').Types.ObjectId;
const Todolist = require('../models/todolist-model');
// The underscore param, "_", is a wildcard that can represent any value;
// here it is a stand-in for the parent parameter, which can be read about in
// the Apollo Server documentation regarding resolvers
module.exports = {
Query: { //Query used to fetch data
/**
@param {object} req - the request object containing a user id
@returns {array} an array of todolist objects on success, and an empty array on failure
**/
getAllTodos: async (_, __, { req }) => {
const _id = new ObjectId(req.userId);
if(!_id) { return([])};
const todolists = await Todolist.find({owner: _id});
if(todolists) return (todolists);
},
/**
@param {object} args - a todolist id
@returns {object} a todolist on success and an empty object on failure
**/
getTodoById: async (_, args) => {
const { _id } = args;
const objectId = new ObjectId(_id);
const todolist = await Todolist.findOne({_id: objectId});
if(todolist) return todolist;
else return ({});
},
},
Mutation: { //Mutation used to modify data
/**
@param {object} args - a todolist id and an empty item object
@returns {string} the objectID of the item or an error message
**/
addItem: async(_, args) => {
const { _id, item, index } = args;
const listId = new ObjectId(_id);
const objectId = new ObjectId();
const found = await Todolist.findOne({_id: listId});
if(!found) return ('Todolist not found');
if(item._id === ''){
item._id = objectId;
}
let listItems = found.items;
//listItems.push(item);
if(index < 0){
listItems.push(item);
}
else{
listItems.splice(index, 0, item);
}
const updated = await Todolist.updateOne({_id: listId}, { items: listItems });
if(updated) return (item._id);
else return ('Could not add item');
},
/**
@param {object} args - an empty todolist object
@returns {string} the objectID of the todolist or an error message
**/
addTodolist: async (_, args) => {
const { todolist } = args;
const objectId = new ObjectId();
const { id, name, owner, items, position } = todolist;
const newList = new Todolist({
_id: objectId,
id: id,
name: name,
owner: owner,
items: items,
position: position
});
const updated = await newList.save();
if(updated) return objectId;
else return ('Could not add todolist');
},
/**
@param {object} args - a todolist objectID and item objectID
@returns {array} the updated item array on success or the initial
array on failure
**/
deleteItem: async (_, args) => {
const { _id, itemId } = args;
const listId = new ObjectId(_id);
const found = await Todolist.findOne({_id: listId});
let listItems = found.items;
listItems = listItems.filter(item => item._id.toString() !== itemId);
const updated = await Todolist.updateOne({_id: listId}, { items: listItems })
if(updated) return (listItems);
else return (found.items);
},
/**
@param {object} args - a todolist objectID
@returns {boolean} true on successful delete, false on failure
**/
deleteTodolist: async (_, args) => {
const { _id } = args;
const objectId = new ObjectId(_id);
const deleted = await Todolist.deleteOne({_id: objectId});
if(deleted) return true;
else return false;
},
/**
@param {object} args - a todolist objectID, field, and the update value
@returns {boolean} true on successful update, false on failure
**/
updateTodolistField: async (_, args) => {
const { field, value, _id } = args;
const objectId = new ObjectId(_id);
const updated = await Todolist.updateOne({_id: objectId}, {[field]: value});
if(updated) return value;
else return "";
},
/**
@param {object} args - a todolist objectID, an item objectID, field, and
update value. Flag is used to interpret the completed
field,as it uses a boolean instead of a string
@returns {array} the updated item array on success, or the initial item array on failure
**/
updateItemField: async (_, args) => {
const { _id, itemId, field, flag } = args;
let { value } = args
const listId = new ObjectId(_id);
const found = await Todolist.findOne({_id: listId});
let listItems = found.items;
if(flag === 1) {
if(value === 'complete') { value = true; }
if(value === 'incomplete') { value = false; }
}
listItems.map(item => {
if(item._id.toString() === itemId) {
item[field] = value;
}
});
const updated = await Todolist.updateOne({_id: listId}, { items: listItems })
if(updated) return (listItems);
else return (found.items);
},
/**
@param {object} args - contains list id, item to swap, and swap direction
@returns {array} the reordered item array on success, or initial ordering on failure
**/
reorderItems: async (_, args) => {
const { _id, itemId, direction } = args;
const listId = new ObjectId(_id);
const found = await Todolist.findOne({_id: listId});
let listItems = found.items;
const index = listItems.findIndex(item => item._id.toString() === itemId);
// move selected item visually down the list
if(direction === 1 && index < listItems.length - 1) {
let next = listItems[index + 1];
let current = listItems[index]
listItems[index + 1] = current;
listItems[index] = next;
}
// move selected item visually up the list
else if(direction === -1 && index > 0) {
let prev = listItems[index - 1];
let current = listItems[index]
listItems[index - 1] = current;
listItems[index] = prev;
}
const updated = await Todolist.updateOne({_id: listId}, { items: listItems })
if(updated) return (listItems);
// return old ordering if reorder was unsuccessful
listItems = found.items;
return (found.items);
},
sortItemsByColumn: async (_, args) => {
const { _id, orientation } = args;
const listID = new ObjectId(_id);
const found = await Todolist.findOne({_id: listID}); //ensure that a list with the ListID exists
let listItems = found.items;
if(orientation === 0){ //sort by task
let flag = false;
for(let i = 0; i < listItems.length - 1; i++){
let lowest = i;
let temp = listItems[i];
for(let j = i + 1; j < listItems.length; j++){
if(listItems[j].description.toUpperCase().localeCompare(listItems[lowest].description.toUpperCase()) < 0){
lowest = j;
flag = true;
}
}
listItems[i] = listItems[lowest];
listItems[lowest] = temp;
}
if(!flag){
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 1){ //sort by task (reverse)
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 2){ //sort by due date
let flag = false;
for(let i = 0; i < listItems.length - 1; i++){
let lowest = i;
let temp = listItems[i];
for(let j = i + 1; j < listItems.length; j++){
if(listItems[j].due_date.toString().localeCompare(listItems[lowest].due_date.toString()) < 0){
lowest = j;
flag = true;
}
}
listItems[i] = listItems[lowest];
listItems[lowest] = temp;
}
if(!flag){
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 3){ //sort by due date (reverse)
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 4){ // sort by status
let flag = false;
for(let i = 0; i < listItems.length - 1; i++){
let lowest = i;
let temp = listItems[i];
for(let j = i + 1; j < listItems.length; j++){
if(listItems[j].completed.toString().localeCompare(listItems[lowest].completed.toString()) < 0){
lowest = j;
flag = true;
}
}
listItems[i] = listItems[lowest];
listItems[lowest] = temp;
}
if(!flag){
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 5){ // sort by status (reverse)
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 6){
let flag = false;
for(let i = 0; i < listItems.length - 1; i++){
let lowest = i;
let temp = listItems[i];
for(let j = i + 1; j < listItems.length; j++){
if(listItems[j].assigned_to.toUpperCase().localeCompare(listItems[lowest].assigned_to.toUpperCase()) < 0){
lowest = j;
flag = true;
}
}
listItems[i] = listItems[lowest];
listItems[lowest] = temp;
}
if(!flag){
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
else if(orientation === 7){
let middle = Math.floor(listItems.length/2);
let endIndex = listItems.length - 1;
for(let i = 0; i < middle; i++){
let temp = listItems[endIndex - i];
listItems[endIndex - i] = listItems[i];
listItems[i] = temp;
}
await Todolist.updateOne({ _id: listID }, { items: listItems});
}
return listItems;
},
revertSort: async (_, args) => {
const {_id, prevList} = args;
const listID = new ObjectId(_id)
await Todolist.updateOne({ _id: listID }, { items: prevList});
return prevList;
},
updatePosition: async (_, args) => {
const {_id, newPosition} = args;
const listID = new ObjectId(_id);
await Todolist.updateOne({ _id: listID }, { position: newPosition });
return("Successfully updated position");
}
}
}
| 5361238d3cd53c07ce27f0b983b6ec02dfeaa295 | [
"JavaScript"
]
| 2 | JavaScript | KevinD65/CSE-316-HW3 | 68ffca6c7d580bdd2084a9e28c6b5f54d7feab24 | 36a816ba20f7be1344a87234d1d04502e5b0e900 |
refs/heads/master | <file_sep><?php
/*
* Copyright 2018 <NAME> <<EMAIL>>
*
* 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.
*/
require_once("vendor/autoload.php");
require_once("config.php");
// Check config
if ($config['aws']['bucket'] == "" || $config['aws']['access_key'] == '' || $config['aws']['secret'] == '' || $config['aws']['acl'] == '') {
echo "Config not setup properly for AWS. Ensure all fields are filled in.\n";
exit;
}
$pid = pcntl_fork();
if ($pid == -1) {
start_upload($argv); // Can't fork, upload as normal process
} else if ($pid) {
// We've forked and are parent, end this process.
exit;
} else {
start_upload($argv);
}
function start_upload($argv) {
global $config;
$archive = $argv[1];
$key = isset($argv[2]) ? $argv[2] : $argv[1];
$s3 = Aws\S3\S3Client::factory(
[
'credentials' => [
'key' => $config['aws']['access_key'],
'secret' => $config['aws']['secret']
],
'version' => 'latest',
'region' => ($config['aws']['region'] != "") ? $config['aws']['region'] : 'us-west-2',
]
);
$s3->putObject([
'Bucket' => $config['aws']['bucket'],
'Key' => $key,
'SourceFile' => $archive,
'ACL' => $config['aws']['acl'],
'StorageClass' => $config['aws']['storage_class']
]);
unlink($archive);
}
<file_sep>dhawton/backup project.
<file_sep><?php
$defaultconfig = [
"compression" => [
"type" => "gz",
"level" => 0
],
"preruns" => [
],
"backups" => [
],
"aws" => [
"bucket" => "",
"region" => "",
"access_key" => "",
"secret" => "",
"acl" => "private",
"storage_class" => "STANDARD_IA",
]
];
<file_sep><?php
/*
* Copyright 2018 <NAME> <<EMAIL>>
*
* 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.
*/
require_once("vendor/autoload.php");
require_once("config.php");
require_once("default.config.php");
function main() {
global $defaultconfig, $config;
$config = array_merge($defaultconfig, $config);
// Check config
if ($config['aws']['bucket'] == "" || $config['aws']['access_key'] == '' || $config['aws']['secret'] == '') {
echo "Config not setup properly for AWS. Ensure all fields are filled in.\n";
exit;
}
if (!in_array($config['compression']['type'], ['gz','gzip','bz2','bzip2','xz'])) {
echo "Invalid compression type defined. Supported types: gz/gzip, bz2/bzip2, xz\n";
exit;
}
if (isset($config['prerun'])) {
foreach($config['preruns'] as $cmd) {
system ($cmd);
}
}
$datestamp = date("Ymd");
foreach($config['backups'] as $archive => $files) {
$filename = "$datestamp.$archive"; // ext added by functions
echo "Building archive $archive...\n";
$archive = build_archive($filename, $files);
echo "Archive $archive built. Starting upload script.\n";
system("php upload.php $archive");
echo "Upload script started.\n";
}
echo "Done.";
}
function build_archive($archive, $list) {
if (is_array($list)) {
$list = implode(" ", $list);
}
$tar = build_tar($archive, $list);
$archive = compress($tar);
return $archive;
}
function build_tar($archive, $files) {
system("tar -cf $archive.tar $files");
return "$archive.tar";
}
function compress($tar) {
global $config;
if ($config['compression']['type'] == "bz2" || $config['compression']['type'] == "bzip2") {
$archive = build_bz2($tar);
}
if ($config['compression']['type'] == "gz" || $config['compression']['type'] == "gzip") {
$archive = build_gz($tar);
}
if ($config['compression']['type'] == "xz") {
$archive = build_xz($tar);
}
return $archive;
}
function build_bz2($tar) {
global $config;
$cmd = "bzip2 ";
if ($config['compression']['level'] >= 0 && $config['compression']['level'] <= 9) {
$cmd .= "-" . $config['compression']['level'] . " ";
}
system("$cmd $tar");
return "$tar.bz2";
}
function build_gz($tar) {
global $config;
$cmd = "gzip ";
if ($config['compression']['level'] >= 0 && $config['compression']['level'] <= 9) {
$cmd .= "-" . $config['compression']['level'] . " ";
}
system("$cmd $tar");
return "$tar.gz";
}
function build_xz($tar) {
global $config;
$cmd = "xz ";
if ($config['compression']['level'] >= 0 && $config['compression']['level'] <= 9) {
$cmd .= "-" . $config['compression']['level'] . " ";
}
system("$cmd $tar");
return "$tar.xz";
}
main();
| d0f427219b64970fab3342c70d2979eb05a7c957 | [
"Markdown",
"PHP"
]
| 4 | PHP | dhawton/backups | 9ba767cbc84918a98b300ea36eecf512a3ce9660 | 92632645efac1a760b87fb4971512404a22bb1e3 |
refs/heads/master | <file_sep>/**
* Created by Nastushka on 08.11.2014.
*/
document.addEventListener('DOMContentLoaded',homeAccess,false);
document.addEventListener('DOMContentLoaded',loggedUser,false);
function homeAccess(){
var params = sentUser();
var xhr = new XMLHttpRequest();
xhr.open('GET', '/homeAccess?' + params, true);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
var phoneResponse = JSON.parse(xhr.responseText);
if(phoneResponse.redirect == '/registration'){
window.location = phoneResponse.redirect;
}
}
xhr.send(null);
}<file_sep>/**
* Created by Nastushka on 25.10.2014.
*/
document.addEventListener('DOMContentLoaded',showCartItems,false);
document.addEventListener('DOMContentLoaded',loggedUser,false);
function showCartItems(){
var params = sentUser();
var xhr = new XMLHttpRequest();
xhr.open('GET', '/cartAccess?' + params, true);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
var phoneResponse = JSON.parse(xhr.responseText);
if(phoneResponse.redirect == '/registration'){
window.location = phoneResponse.redirect;
}
else{
var respProd = phoneResponse.path;
for (var key in respProd){
var savedItems = cart.get('cart');
for(var i=0;i<savedItems.length;i++){
if(savedItems[i] == key){
var phoneItem = respProd[key];
var nameDiv = createItemWrap(key);
for (var keyInner in phoneItem){
if (keyInner == 'itemTitle') {
var prName = itemTitleWrap(phoneItem,keyInner);
nameDiv.appendChild(prName);
}
if (keyInner == 'itemThumbImgUrl') {
var prImage = imgWrap(phoneItem,keyInner);
nameDiv.insertBefore(prImage, prName);
}
if (keyInner == 'shortDescr') {
var prDescr = shortDescWtap(phoneItem,keyInner);
nameDiv.appendChild(prDescr);
}
if (keyInner == 'price') {
var newPrice = phoneItem[keyInner];
for (var key1 in newPrice) {
var prPrice = priceWrap(newPrice,key1);
nameDiv.insertBefore(prPrice, prDescr);
}
}
delButton();
}
}
}
}
}
}
xhr.send(null);
}
<file_sep>/**
* Created by Nastushka on 06.10.14.
*/
document.getElementById('submit_id').addEventListener('click',addUserToFile,false);
function CountLogin(item){
var item_view = 'login_view'; // var for displaying count of elements
var item_correct = 'login_correct'; // var for displaying message about error
document.getElementById(item_view).innerHTML = document.getElementById(item).value.length++;
if (document.getElementById(item).value.length >= 5) {
document.getElementById(item_correct).innerHTML = 'correct';
document.getElementById(item_correct).className = 'correct';
document.getElementById('check_login').value = 1;
}
else{
document.getElementById(item_correct).innerHTML = 'no less than 5 symbols';
document.getElementById(item_correct).className = 'acorrect';
document.getElementById('check_login').value = 0;
}
checkAll();
}
function CountPass(item){
var item_view = 'pass_view';
var item_correct = 'pass_correct';// var for displaying message about error
var item_login_value = document.getElementById('login_id').value;
var item_login_length = item_login_value.length;
document.getElementById(item_view).innerHTML = document.getElementById(item).value.length++;
if (document.getElementById(item).value == item_login_value && item_login_length >= 5) {
document.getElementById(item_correct).innerHTML = 'password matches to login';
document.getElementById(item_correct).className = 'acorrect';
document.getElementById('check_pass').value = 0;
} else {
if (document.getElementById(item).value.length >= 4) {
document.getElementById(item_correct).innerHTML = 'correct';
document.getElementById(item_correct).className = 'correct';
document.getElementById('check_pass').value = 1;
} else if (document.getElementById(item).value.length < 4) {
document.getElementById(item_correct).innerHTML = 'password should contain from 4 to 10 symbols';
document.getElementById(item_correct).className = 'acorrect';
document.getElementById('check_pass').value = 0;
}
}
checkAll();
}
function CorrectPass(item){
var item_pass_value = document.getElementById('pass_id').value;// var for displaying message about error
var item_pass_length = item_pass_value.length; // length of the password
var item_correct = 'repass_correct';
if (item_pass_length >= 4){
if (document.getElementById(item).value == item_pass_value){
document.getElementById(item_correct).innerHTML = 'passwords match';
document.getElementById(item_correct).className = 'correct';
document.getElementById('check_repass').value = 1;
}
else if (document.getElementById(item).value.length >= 4){
document.getElementById(item_correct).innerHTML = 'passwords do not match';
document.getElementById(item_correct).className = 'acorrect';
document.getElementById('check_repass').value = 0;
}
}
checkAll();
}
//check email address
function isEmail(item){
var at = '@';
var dot = '.';
var lat = item.indexOf(at);
var litem = item.length;
var ldot = item.indexOf(dot);
if (item.indexOf(at)==-1) return false; // if there is no at
if (item.indexOf(at)==-1 || item.indexOf(at) == 0 || item.indexOf(at) == litem) return false; // there is no, the 1st symbol, the last symbol
if (item.indexOf(dot)==-1 || item.indexOf(dot) == 0 || item.indexOf(dot) >= litem - 2) return false;
if (item.indexOf(at,(lat+1))!=-1) return false; // if we found multiple @
if (item.substring(lat-1,lat)==dot || item.substring(lat+1,lat+2)==dot) return false;
if (item.indexOf(dot,(lat+2))==-1) return false;
if (item.indexOf(" ")!=-1) return false;
return true;
}
// check correct email
function CorrectEmail(item) {
var item_correct = 'email_correct'; // var to display message about error
if (isEmail(item.value) == true){
document.getElementById(item_correct).innerHTML = 'correct';
document.getElementById(item_correct).className = 'correct';
document.getElementById('check_email').value = 1;
}
else {
document.getElementById(item_correct).innerHTML = 'please provide correct email';
document.getElementById(item_correct).className = 'acorrect';
document.getElementById('check_email').value = 0;
}
checkAll();
}
function checkAll(){
var x;
var check_login = document.getElementById('check_login').value;
var check_pass = document.getElementById('check_pass').value;
var check_repass = document.getElementById('check_repass').value;
var check_email = document.getElementById('check_email').value;
x = check_login + check_pass + check_repass + check_email;
document.getElementById('check_all').value = x;
if (document.getElementById('check_all').value == 1111){
//unlock button
document.getElementById('submit_id').disabled = false;
}
else {
//lock button
document.getElementById('submit_id').disabled = true;
}
}
function addUserToFile(){
var userLogin = document.getElementById('login_id').value;
var userPassword = document.getElementById('pass_id').value;
var userEmail = document.getElementById('email_id').value;
function userUnfo(userPassword,userEmail){
this.password = <PASSWORD>;
this.email = userEmail;
}
var userInfo = new userUnfo(userPassword,userEmail);
var xhr = new XMLHttpRequest();
var params = 'login=' + encodeURIComponent(userLogin) + '&userInfo=' + JSON.stringify(userInfo);
xhr.open('POST','/auth',true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
var resp = JSON.parse(xhr.responseText);
var userObj = {};
userObj[userLogin] = resp.userId;
users.set('user',userObj,'object');
window.location = resp.redirect;
}
xhr.send(params);
}
<file_sep>/**
* Created by Nastushka on 22.11.2014.
*/
document.addEventListener('DOMContentLoaded',createMap,false);
function createMap(){
ymaps.ready(init);
}
function init () {
// Создание экземпляра карты и его привязка к контейнеру с
// заданным id ("map").
var myMap = new ymaps.Map('map', {
// При инициализации карты обязательно нужно указать
// её центр и коэффициент масштабирования.
center: [53.9, 27.56], // Минск
zoom: 10
});
var myPlacemark = new ymaps.Placemark([53.9, 27.56]);
myMap.geoObjects.add(myPlacemark);
}<file_sep>/**
* Created by sergey on 4/10/14.
*/
var http = require('http');
var url = require('url');
var fs = require('fs');
var express = require('express');
var app = express();
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded());
function fileSend(req, resp) {
console.log(req.method + ': ' + req.path);
resp.sendfile(__dirname + req.path);
}
function getPageRelatedPath(req, resp) {
console.log(req.method + ': ' + req.path);
resp.sendfile(__dirname + '/pages' + req.path + '.html');
}
function getProductsDb(req, resp) {
var productsPath = '/db/products.json';
console.log(req.method + ': ' + productsPath);
resp.sendfile(__dirname + productsPath);
}
function pagesAccess(req, resp, value){
var db = fs.readFileSync('db/users.json', {
encoding: 'utf8'
});
db = JSON.parse(db);
var params = url.parse(req.url, true).query;
console.log('req.params', params);
var username = params['userLogin'];
console.log(username)
var token = params['userToken'];
console.log(token);
var count = 0;
for (var key in db){
console.log('db=',key);
if (key == username){
console.log('0=',key,username);
count++;
if (db[key] == token){
console.log('1');
return;
}
}
else{
console.log('2=',key,username);
console.log('count=',count);
}
}
if (count == 0){
resp.send({redirect:'/registration'});
console.log('not logged');
}
else{
var dbPhone = fs.readFileSync('db/products.json', {
encoding: 'utf8'
});
dbPhone = JSON.parse(dbPhone);
var respObj = {};
respObj.path = dbPhone;
console.log(respObj.path);
respObj.redirect = value;
resp.send(respObj);
console.log('logged');
}
resp.end();
}
app.get('/', function (req, resp) {
console.log(req.method + ': ' + req.path);
resp.sendfile(__dirname + "/index.html");
});
app.get('/cart', getPageRelatedPath);
app.get('/login', getPageRelatedPath, function(){
console.log("test");
});
app.get('/registration', getPageRelatedPath);
app.get('/scripts/*', fileSend);
app.get('/pages/*', fileSend);
app.get('/images/*', fileSend);
app.get('/styles/*', fileSend);
app.get('/getProducts', getProductsDb);
app.get('/phone', getPageRelatedPath);
app.get('/productReview', getPageRelatedPath);
app.get('/phoneAccess', function (req, resp){
pagesAccess(req, resp, '/phone');
});
app.get('/cartAccess', function (req, resp){
pagesAccess(req, resp,'/cart');
});
app.get('/homeAccess', function (req, resp){
var db = fs.readFileSync('db/users.json', {
encoding: 'utf8'
});
db = JSON.parse(db);
var params = url.parse(req.url, true).query;
console.log('req.params', params);
var username = params['userLogin'];
//console.log(username)
var token = params['userToken'];
//console.log(token);
var count = 0;
for (var key in db){
console.log('db=',key);
if (key == username){
//console.log('0=',key,username);
count++;
if (db[key] == token){
//console.log('1');
return;
}
}
else{
//console.log('2=',key,username);
//console.log('count=',count);
}
}
if (count == 0){
resp.send({redirect:'/registration'});
console.log('not logged');
}
else{
resp.send({redirect:'/'});
console.log('logged');
}
resp.end();
});
app.get('/loginAccess', function (req, resp){
pagesAccess(req, resp,'/');
});
app.get('/addProduct', function (req, resp) {
var db = fs.readFileSync('db/products.json', {
encoding: 'utf8'
});
db = JSON.parse(db);
var params = url.parse(req.url, true).query;
console.log('req.params', params);
var idPhone = params['id'];
var titlePar = params['itemTitle'];
var itemThumbImgUrlPar = params['itemThumbImgUrl'];
var shortDescPar = params['shortDesc'];
// params['price'] = JSON.parse(params['price']);
params['techInfo'] = JSON.parse(params['techInfo']);
var pricePar = JSON.parse(params['price']);
var techPar = params['techInfo'];
function phoneInfoObj(titlePar, itemThumbImgUrlPar, shortDescPar, pricePar, techPar) {
this.itemTitle = titlePar;
this.itemThumbImgUrl = itemThumbImgUrlPar;
this.shortDescr = shortDescPar;
this.price = pricePar;
this.techInfo = techPar;
}
var phoneInfoObj = new phoneInfoObj(titlePar, itemThumbImgUrlPar, shortDescPar, pricePar, techPar);
db[idPhone] = phoneInfoObj;
fs.writeFile('db/products.json', JSON.stringify(db, null, 4), function (err) {
if (err) {
console.log('err add', err);
} else {
console.log('Product saved');
}
});
resp.send(params);
resp.end();
});
app.post('/auth', function (req, resp) {
console.log('post');
var dbLogin = fs.readFileSync('db/users.json', {
encoding: 'utf8'
});
console.log('dbLogin', dbLogin);
dbLogin = JSON.parse(dbLogin);
var body = req.body;
console.log('body', body);
var userLogin = body['login'];
var userInfo = JSON.parse(body['userInfo']);
var guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
var uuid = guid();
userInfo.userToken = uuid;
dbLogin[userLogin] = userInfo;
fs.writeFile('db/users.json', JSON.stringify(dbLogin, null, 4), function (err) {
if (err) {
console.log('err add', err);
} else {
console.log('User saved');
}
});
var resAuth = {};
resAuth.userId = uuid;
resAuth.redirect = '/';
resp.send(resAuth);
resp.end();
});
app.post('/log', function (req, resp) {
console.log('post');
var dbLogin = fs.readFileSync('db/users.json', {
encoding: 'utf8'
});
console.log('dbLogin', dbLogin);
dbLogin = JSON.parse(dbLogin);
var body = req.body;
console.log('body', body);
var userInfo = JSON.parse(body['userInfo']);
var username = userInfo.username;
var password = userInfo.password;
console.log(password);
console.log(username);
var guid = (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})();
var uuid = guid();
for(var key in dbLogin){
if(username == key){
console.log(username,key);
var usOnj = dbLogin[key];
if(password == <PASSWORD>){
console.log(password,usOnj.password);
usOnj.userToken = uuid;
console.log(usOnj.userToken);
fs.writeFile('db/users.json', JSON.stringify(dbLogin, null, 4), function (err) {
if (err) {
console.log('err add', err);
} else {
console.log('User saved');
}
});
var resAuth = {};
resAuth.userId = uuid;
resAuth.redirect = '/';
resp.send(resAuth);
return;
}
}
}
resp.end();
});
app.post('/logOut', function (req, resp) {
console.log('post');
var dbLogin = fs.readFileSync('db/users.json', {
encoding: 'utf8'
});
dbLogin = JSON.parse(dbLogin);
var body = req.body;
console.log('body', body);
var username = body['userLogin'];
console.log('my',username);
for(var key in dbLogin){
if(username == key){
console.log(username,key);
var usOnj = dbLogin[key];
delete usOnj.userToken;
fs.writeFile('db/users.json', JSON.stringify(dbLogin, null, 4), function (err) {
if (err) {
console.log('err add', err);
} else {
console.log('User saved');
}
});
var resAuth = {};
//resAuth.userToken = null;
resAuth.redirect = '/login';
resp.send(resAuth);
return;
}
}
resp.end();
});
http.createServer(app).listen(8081, function () {
console.log('Working http://localhost:8081/');
});
<file_sep>/**
* Created by Nastushka on 17.11.2014.
*/
| 768ce7c6ac8c261916bb6a8527606f5ce1ecfb17 | [
"JavaScript"
]
| 6 | JavaScript | sharitonchik/bonfireNode | 978dab230f0c097e7379d828bbe72c7227361818 | c59fa3a4f9d297033f2ef077791157d358df3a09 |
refs/heads/master | <repo_name>WildflowerSchools/pi-gen<file_sep>/stageWF/01-k8s/00-run.sh
install -m 644 files/daemon.json "${ROOTFS_DIR}/etc/docker/"
rm -rf "${ROOTFS_DIR}/etc/systemd/system/dphys-swapfile.service.d/"
<file_sep>/stageWF/02-startup-checks/files/startup.sh
#!/bin/bash
export TERM="linux"
export MACs=$(ifconfig -a | grep Ethernet | awk '{print $2}')
export IPs=$(ifconfig -a | grep broadcast | awk '{print $2}')
export IP=$(echo "$IPs" | head -1)
export REQ_BODY=$(jq -n -c '{mac: (env.MACs | split("\n")), ip: (env.IPs | split("\n"))}')
function wait4network() {
{
for ((i=0;i<50;i++))
do
echo $(expr $i \* 2)
ping -w 1 8.8.8.8 >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo 100
sleep 1
break
fi
sleep 3
done
} | whiptail --title "Wildflower" --gauge "\nWaiting for network connection..." 8 40 0
}
DEFAULT=$(systemctl get-default)
if [ $DEFAULT == "multi-user.target" ]
then
wait4network()
CONTROL_NAME=$(avahi-browse _wfcontrol._tcp -p -t | grep IPv4 | awk 'BEGIN { FS = ";" } ; { print $4 }' | uniq | head -1)
curl --header "Content-Type: application/json" \
--request POST \
--data "$REQ_BODY" \
http://${CONTROL_NAME}:5000/
fi
exit 0
<file_sep>/stageWF/02-startup-checks/00-run.sh
#!/bin/bash -e
mkdir "${ROOTFS_DIR}/opt/wildflowertech"
install -m 644 files/sethostname.sh "${ROOTFS_DIR}/opt/wildflowertech/"
install -m 644 files/startup.sh "${ROOTFS_DIR}/opt/wildflowertech/"
install -m 644 files/wildflower.service "${ROOTFS_DIR}/etc/systemd/system/"
mkdir "${ROOTFS_DIR}/home/wildflowertech/.ssh/"
install -m 600 files/authorized_keys "${ROOTFS_DIR}/home/wildflowertech/.ssh/"
on_chroot << EOF
chown wildflowertech:wildflowertech /home/wildflowertech/.ssh/authorized_keys
EOF
<file_sep>/stageWF/02-startup-checks/files/sethostname.sh
#!/bin/bash
raspi-config nonint do_hostname "$1"
hostname -b "$1"
systemctl restart avahi-daemon | a4ecde8d75962645e551cccdf8bd6def2b7f867d | [
"Shell"
]
| 4 | Shell | WildflowerSchools/pi-gen | fa1ff8e1bcb4eea4406b8ef6e87c7dfda0662527 | f5e68b106b308959ae76511d9fb39ef84ec4ca51 |
refs/heads/master | <file_sep>const Firebase = require('./firebase');
const Mailer = require('./mailer');
const Stripe = require('stripe')(process.env.STRIPE_API_KEY);
const build_address_object = ({address_line1, address_line2, city, state, zip}) => Object.assign({ address_line1, city, state, zip }, address_line2 ? { address_line2 } : {})
const build_address_string = obj => `${obj.address_line1}, ${obj.address_line2 ? obj.address_line2 + ", " : ""}${obj.city}, ${obj.state} ${obj.zip}`
module.exports = {
post: (options, { body }) => Firebase.multiGet(options.inventory, Object.keys(body.order))
.then(inventory => Object.entries(body.order).reduce( (acc, [id, item]) => ({
total: acc.total + item.count * inventory[id].price,
order: Object.assign(acc.order, { [id]: item.count }),
email_content: acc.email_content.concat([{
count: item.count,
name: inventory[id].name,
price: inventory[id].price * item.count
}])
}), {
total: 0,
order: {},
email_content: [],
}))
.then(data => Object.assign(data, { confirmation: Math.floor(Math.random() * 9e9 + 1e9) }))
.then( ({ total, order, email_content, confirmation }) => Stripe.charges.create({
amount: total,
currency: 'usd',
source: body.token.id
})
.then( ({ payment_method_details: { card } }) => Firebase.post(options.order, { body: {
customer: {
name: body.name,
contact: {
email: body.email,
phone: body.phone
},
shipping_address: build_address_object(body.shipping_address)
},
order: order,
confirmation: confirmation,
fulfilled: false,
createdAt: Date.now(),
payment: {
amount: total,
last4: card.last4,
card: card.brand,
exp_month: card.exp_month,
exp_year: card.exp_year,
billing_address: build_address_object(body.billing_address)
}
}}))
.then(_ => Mailer.post(options.email, {
body: {
name: body.name,
email: body.email,
subject: `Email confirmation - Invoice #${confirmation}`,
phone: `${body.phone}`.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"),
card: body.token.card.last4,
shipping_address: build_address_string(body.shipping_address),
billing_address: build_address_string(body.billing_address),
confirmation: confirmation,
total: `$${Number(total/100).toFixed(2)}`,
body: email_content
}
})))
}
<file_sep>module.exports = {
Calendar: require('./calendar'),
Firebase: require('./firebase'),
Image: require('./image'),
Mailer: require('./mailer'),
Stripe: require('./stripe')
}
<file_sep>const Firebase = require('./firebase');
const request = require('request-promise');
module.exports = {
get: options => Firebase.get(options).then(id => Promise.all([Promise.resolve(id), request({
uri: `https://www.googleapis.com/calendar/v3/calendars/${id}/events`,
qs: { key: process.env.GCAL_API_KEY },
json: true
})]))
}
<file_sep>const rimraf = require('rimraf')
const Firebase = require('./firebase')
module.exports = {
post: async (options, req) => {
let { images } = req.files; const { bucket } = req.params;
if (!Array.isArray(images)) images = [images];
return Promise.all(images.map(img => Firebase.upload(img.file, `${bucket}/${img.uuid}.jpg`)))
.then(img_urls => {
(async _ => images.forEach(img => rimraf(`./tmp/${img.uuid}`,
err => console.log(err ? `Failed to delete tmp/${img.uuid}` : `Deleted tmp/${img.uuid}`)
)))();
return img_urls;
})
}
}
<file_sep>require('dotenv').config();
const PORT = process.env.PORT || 8000;
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const busboy = require('express-busboy');
const Libraries = require('./libraries');
const endpoints = require('./endpoints.json');
app.use(require('cors')())
app.use(bodyParser.json());
busboy.extend(app, { upload: true, path: './tmp', allowedPath: /./ })
for (const endpoint_url in endpoints) {
const endpoint_info = endpoints[endpoint_url];
for (const httpAction in endpoint_info) {
const { library, options, err_message, public } = endpoint_info[httpAction];
console.log(`Building endpoint - ${public ? "PUBLIC" : "SECURE"} - ${httpAction.toUpperCase().padEnd(6)} ${endpoint_url}`);
app[httpAction](endpoint_url, async (req, res) => {
console.log(`${httpAction} request @ ${req.url}`);
if (public || await Libraries.Firebase.authenticate(req.headers.authorization))
Libraries[library][httpAction](options, req)
.then(data => res.status(200).json(data))
.catch(err => {
console.log(err);
res.status(500).json({err: err_message})
})
else
res.status(403).json({ err: "Invalid authorization" })
})
}
}
// console.log(app._router.stack);
app.listen(PORT, () => console.log(`Server running on port ${PORT}!`));
<file_sep>const STD_CONFIG = process.env.IS_LOCAL ? require(`./config/firebase-${process.env.DB_MODE}.json`) : JSON.parse(process.env.FIREBASE_CONFIG)
const ADM_CONFIG = process.env.IS_LOCAL ? require(`./config/firebase-${process.env.DB_MODE}-admin.json`) : JSON.parse(process.env.FIREBASE_ADMIN_CONFIG)
const FirebaseApp = require('firebase-admin');
const uuid = require('uuid/v4');
FirebaseApp.initializeApp({ ...STD_CONFIG, credential: FirebaseApp.credential.cert(ADM_CONFIG) });
module.exports = {
authenticate: async token => token && FirebaseApp.auth().verifyIdToken(token).then(_ => true).catch(_ => false),
delete: async ({ db_ref }, { params }) => (await FirebaseApp.database().ref(db_ref).child(params.id)).remove().then(_ => ({ id: params.id })),
get: async ({ db_ref }) => (await FirebaseApp.database().ref(db_ref).once('value')).val(),
multiGet: ({ db_ref }, keys) => Promise.resolve(FirebaseApp.database().ref(db_ref))
.then(ref => Promise.all(keys.map(k => ref.child(k).once('value').then(snapshot => snapshot.val()))))
.then(res => keys.reduce((acc, k, i) => Object.assign(acc, { [k]: res[i] }), {})),
post: async ({ db_ref }, { body, params: { id = uuid() } }) => (await FirebaseApp.database().ref(db_ref).child(id)).set(body).then(_ => ({ [id]: body })),
put: async ({ db_ref }, { body, params: { id } }) => (await FirebaseApp.database().ref(db_ref + (id ? `/${id}` : ''))).update(body).then(_ => ({ data: body })),
upload: (local, filename, token = uuid()) => {
const bucket = FirebaseApp.storage().bucket();
const options = { destination: bucket.file(filename), metadata: { contentType: 'image/jpeg', metadata: { firebaseStorageDownloadTokens: token }}}
return new Promise ((resolve, reject) => bucket.upload(local, options, (err, data) => {
if (err) reject(err);
else resolve(`https://firebasestorage.googleapis.com/v0/b/${bucket.name}/o/${encodeURIComponent(filename)}?alt=media&token=${token}`)
}))
}
}
| dd40318874575104d94b85dfbe6b8d3a51d156b4 | [
"JavaScript"
]
| 6 | JavaScript | atulmerchia/fultonhhc-api | bc0d98c02b3098b2234e147b55c3004bc1d0e34f | 87b01a47d3b206bd1e6b4fa876e1cd01bc2f3e54 |
refs/heads/master | <repo_name>Chris-Miracle/oauth-google<file_sep>/redirect.php
<?php
require_once 'vendor/autoload.php';
// init configuration
$clientID = '534290604425-elo1t7b6jo6jclf6lm85ha1mqi5j26p0.apps.googleusercontent.com';
$clientSecret = '<KEY>';
$redirectUri = 'http://localhost/redirect.php';
// create Client Request to access Google API
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token['access_token']);
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
// Heroku Db
$url = getenv('JAWSDB_URL');
$dbparts = parse_url($url);
$hostname = $dbparts['host-axocheck'];
$username = $dbparts['user-chris'];
$password = $dbparts['<PASSWORD>'];
$database = ltrim($dbparts['path'],'/');
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Saving details into db
$sql = "INSERT INTO Users (name, email)
VALUES ($name, $email)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?> | 1d2976e45722238451d817343111acc3e81deefc | [
"PHP"
]
| 1 | PHP | Chris-Miracle/oauth-google | 64f8cf81b958e229841744add8b05b3cd3322280 | a038b653f8e2054bad0e4d9fa69314c70decda62 |
refs/heads/master | <repo_name>demon1772/deface<file_sep>/install.sh
green="\033[32;1m"
yellow="\033[33;1m"
blue="\033[34;1m"
red="\033[35;1m"
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
echo $red
echo "sabar";
sleep 0.1;
clear
pkg install wget
pkg install python
pkg install python2
pkg install php
pkg install git
pkg install bc
pkg install ruby
pkg install toilet
pkg install figlet
pkg install nano
pkg install w3m
pkg install curl
clear
echo<file_sep>/DFC.sh
#gila_coding
green="\033[32;1m"
yellow="\033[33;1m"
blue="\033[34;1m"
red="\033[35;1m"
clear
echo $blue
figlet -f future "Tebas Index"
echo $yellow "Script Ditaruh Diluar Penyimpanan Internal"
echo $red "Target Percobaan"
echo $yellow "http://contsol.co.za"
echo
echo $blue "masukan url"
echo $yellow
read -p "-->$" link
echo
echo $blue "Masukan Nama Script"
echo $green "nama script harus index.html"
echo $yellow
read -p "-->$" html
echo $red
curl -T /storage/emulated/0/$html $link
echo $yellow "+"$green"Hack Website"$blue" --->"$red" $link"
echo
echo $red"terima kasih telah menggunakan tools saya"
figlet -f future "Mr.demon"
exit | 6943819eb49a9aa0119f58e7f65ec5e5c5abcee5 | [
"Shell"
]
| 2 | Shell | demon1772/deface | 408cdcc65b0e7d44ab7d3422949be6a4e6351833 | bf2d81179024e0669985042ac468d5c6bf0392da |
refs/heads/master | <file_sep>import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import DataCatalogGroup from '../../../DataCatalog/DataCatalogGroup.jsx';
import DataPreview from '../../../Preview/DataPreview.jsx';
import AddData from './AddData.jsx';
import ObserveModelMixin from '../../../ObserveModelMixin';
import Styles from './my-data-tab.scss';
// My data tab include Add data section and preview section
const MyDataTab = createReactClass({
displayName: 'MyDataTab',
mixins: [ObserveModelMixin],
propTypes: {
terria: PropTypes.object,
viewState: PropTypes.object
},
onBackButtonClicked() {
this.props.viewState.myDataIsUploadView = false;
},
onAddMoreDataButtonClicked() {
this.props.viewState.myDataIsUploadView = true;
},
hasUserAddedData() {
return this.props.terria.catalog.userAddedDataGroup.items.length > 0;
},
render() {
return (
<div className={Styles.root}>
<div className={Styles.leftCol}>
<If condition={this.props.viewState.myDataIsUploadView}>
<div className={Styles.addedData}>
<If condition={this.hasUserAddedData()}>
<button type='button'
onClick={this.onBackButtonClicked}
className={Styles.btnBackToMyData}>
Back
</button>
</If>
<h3 className={Styles.h3}>Adding your own data</h3>
<AddData terria={this.props.terria}
viewState={this.props.viewState}/>
</div>
</If>
<If condition={this.hasUserAddedData()}>
<div className={Styles.addedData}>
<p className={Styles.explanation}>
Data added in this way is not saved or made visible to others unless you explicitly share
it by using the Share panel.
</p>
<ul className={Styles.dataCatalog}>
<DataCatalogGroup group={this.props.terria.catalog.userAddedDataGroup}
viewState={this.props.viewState}/>
</ul>
<button type='button'
onClick={this.onAddMoreDataButtonClicked}
className={Styles.btnAddMoreData}>
Add more data
</button>
</div>
</If>
</div>
<DataPreview terria={this.props.terria}
viewState={this.props.viewState}
previewed={this.props.viewState.userDataPreviewedItem}
/>
</div>
);
},
});
module.exports = MyDataTab;
| 0df3ce845a0e56855d9b94f7f552ef20050b4ea7 | [
"JavaScript"
]
| 1 | JavaScript | rsignell-usgs/terriajs | 243b46b4db7350200172312fbe986f18762d0dc9 | 77902bac09ca6241d0c36a232ade41f3a00ce71b |
refs/heads/master | <repo_name>AshleyCano-JuanCandia/movies-application<file_sep>/src/index.js
// "use strict";
/**
* es6 modules and imports
*/
// import sayHello from './hello';
// sayHello('World');
/**
* require style imports
*/
const $ = require('jquery');
const {getMovies} = require('./api.js');
let movieData = {};
let movieDataObject = {};
function updateMovies() {
getMovies().then((movies) => {
console.log('Here are all the movies:');
let movieHTML = "";
let currentMoviesHTML = "";
movies.forEach(({title, rating, id}) => {
$.get(`http://www.omdbapi.com/?t=${title}&apikey=f9b07338&`, {}).done(function (data) {
// console.group(title);
movieData = {
poster: data.Poster,
director: data.Director,
year: data.Year
};
// console.log(movieData);
console.log(`id#${id} - ${title} - rating: ${rating}`);
// console.log("data= ", movieData);
let backgroundImageStyling = `"background-image: url('${movieData.poster}');background-repeat:no-repeat;background-image: cover; border-radius: 10px"`;
movieHTML += `<div class="displayBox" style=${backgroundImageStyling} data-dbid="${id}">`;
movieHTML += `<div class="textArea">${title} <div class="smallerFont">`;
movieHTML += `${movieData.director}, ${movieData.year} <div class="smallerFont">rating: ${rating}</div>`;
movieHTML += `</div></div></div>`;
$("#movieData").html(movieHTML);
currentMoviesHTML += `<option value=${id} class="value">${title}</option>`;
$("#movies").html(currentMoviesHTML);
$("#movieToEdit").val($("#movies option:selected").text());
$(".displayBox").click(
function () {
$(this).toggleClass('active');
// $("#deleteMovieBtn").toggleClass("invisible");
});
}).fail(function () {
console.log("error on request");
});
});
}).catch((error) => {
alert('Oh no! Something went wrong.\nCheck the console for details.');
console.log(error);
});
}
//********** delete movie
$('#deleteMovieBtn').click(function (e) {
e.preventDefault();
console.log("movie to delete", $(".active").data("dbid"));
$(".active").each((selectedMovie) => {
let thisMovie = $(".active")[selectedMovie];
let movieId = $(thisMovie).data("dbid");
const options = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
}
};
fetch(`/api/movies/${movieId}`, options)
.then(() => {
console.log('delete a movie was created successfully!');
updateMovies();
})
.catch(() => console.log('Error on post'));
});
});
//************* delete movie
updateMovies();
$('#addMovie').click(function (e) {
e.preventDefault();
const newMovie = {
title: $('#title').val(),
rating: $('#rating').val()
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newMovie),
};
fetch('/api/movies', options)
.then(() => {
console.log('add a movie post was created successfully!');
updateMovies();
})
.catch(() => console.log('Error on post'));
});
// $('#movies').change(function () {
// $("#movieToEdit").val($("#movies option:selected").text());
// });
//
// $('#editMovie').click(function (e) {
// e.preventDefault();
//
// console.log($('#movieToEdit').val());
// console.log($('#newRating').val());
//
//
// const newMovie = {
// title: $('#movieToEdit').val(),
// rating: $('#newRating').val()
// };
// const options = {
// method: 'PUT',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(newMovie),
// };
// fetch('/api/movies/', options)
// .then(() => console.log('edit a movie post was created successfully!'))
// .catch(() => console.log('Error on post'));
// updateMovies();
// });
| d62b29526119a8cd7be99775f6644a3d8ad0ace5 | [
"JavaScript"
]
| 1 | JavaScript | AshleyCano-JuanCandia/movies-application | 845274bd1e1280d35b62316e5afc3285e5ed5a49 | 5018285062ca795a1ca7df2e4aa33d1233bf5afa |
refs/heads/master | <file_sep>def quicksort(array, sortFunc):
totLen = len(array)
if totLen <= 1:
return array
pivot = array[totLen/2]
array.remove(pivot)
less = []
greater = []
temp = []
for x in array:
if sortFunc(x, pivot) < 0:
less.append(x)
else:
greater.append(x)
temp.extend(quicksort(less, sortFunc))
temp.append(pivot)
temp.extend(quicksort(greater, sortFunc))
return temp<file_sep>import re, copy
VERBOSE = 0
def inferNameAndParams(opHeader, opParams):
"""Extracts predicate's name and params from its string represantation."""
if opParams is not None:
return (opHeader, opParams)
else:
opHeader = re.sub("\s+\?", " $", opHeader)
toks = opHeader.split(" ")
return (toks[0].lower(), toks[1:])
class Predicate(object):
def __init__(self, domain, opHeader, opParams = None):
"""
Initializes the predicate.
*extracts name and params
*throws exception if predicate's name is absent from the domain's declaration
*throws exception if given incorrect number of params
"""
name, params = inferNameAndParams(opHeader, opParams)
self.priority = -1
self.priorityGroup = False
self.deferred = False
self.isDefault = True
self.__name__ = name
self.params = params
self.domain = domain
if name not in domain.predicates:
raise Exception("\n\nUndeclaredpredicate predicate <{}>.\n".format(name.upper()))
elif len(params) != domain.predicates[name].paramsNumber:
raise Exception("\n\nIncorrect number of parameters for predicate <{}>. Required: {}; found: {}.\n".format(name.upper(), domain.predicates[name].paramsNumber, len(params)))
if VERBOSE:
print ("Predicate name: {}; Number of parameters: {}".format(name, domain.predicates[name].paramsNumber))
def __eq__(self, other):
"""
Checks if two predicates are equal.
This would normally return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__),
but the string rep of the predicate is instead used as a relaxed shortcut to its properties.
"""
return (isinstance(other, self.__class__)) and self.__str__() == other.__str__()
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
prime = 11
result = 7
result = int(prime * result) + hash(self.__name__)
result = int(prime * result) + hash(tuple(self.params))
return 1000000001 * int(result)
#return 1000001 * hash(self.hashStr())
def __str__(self):
return "<{} {}>".format(self.__name__.upper(), str(tuple(self.params)))
def hashStr(self):
pars = str(tuple(self.params))
res = "{} {}".format(self.__name__, pars)
return res + self.__name__
def isTemplate(self):
"""
Checks if the predicate is a template.
Returns true if all parameters are placeholders.
"""
for param in self.params:
if not param.startswith("$"):
return False
return True
def isSamePred(self, other):
"""
Checks if argument is the same predicate as the one in question.
Predicates are considered "same" if they have the same name and the same number of parameters.
"""
return self.__name__ == other.__name__ and len(self.params) == len(other.params)
def hasSameParams(self, other):
"""
Checks if the argument has the same parameters as the predicate in question.
That is if both predicates have the same parameters or any of the differing params is a placeholder (begins with $).
"""
if not self.isSamePred(other):
return False
for index in range(len(self.params)):
pSelf = self.params[index]
pOther = other.params[index]
if (not pSelf.startswith("$")) and (not pOther.startswith("$")) and pSelf != pOther:
return False
return True
def sharesParams(self, other):
"""
Checks if the argument shares some params with the predicate in question.
"""
if not self.isSamePred(other):
return False
for index in range(len(self.params)):
pSelf = self.params[index]
pOther = other.params[index]
if (not pSelf.startswith("$")) and (not pOther.startswith("$")) and pSelf == pOther:
return True
return False
def sharesUnpositionedParams(self, other):
"""
Checks if the argument shares some params with the predicate in question.
"""
if not self.isSamePred(other):
return False
for index in range(len(self.params)):
pSelf = self.params[index]
if (not pSelf.startswith("$")) and pSelf in other.params:
return True
return False
def paramsFullyBound(self, params):
"""Returns true if all arguments are bound or empty."""
for param in params:
if param.startswith("$"):
return False
return True
def borrowUnboundParams(self, other):
"""Tries to bind an unbound argument borrowed for other if the rest are similar."""
params = copy.deepcopy(self.params)
if not self.hasSameParams(other) or other.isTemplate() or self.paramsFullyBound(params):
return params
if VERBOSE:
print("Borrowing params: {} -> {}: {}".format(str(self), str(other), params))
for index in range(len(self.params)):
pSelf = self.params[index]
pOther = other.params[index]
if pSelf.startswith("$") and not pSelf in other.params:
params[params.index(pSelf)] = pOther
if VERBOSE:
print("Borrowed params: {} -> {}: {}".format(str(self), str(other), params))
return params
def adaptParams(self, newParams):
"""
Adapts state variables to predicate parameters.
Takes a mapping of arguments
"""
tempParams = []
for param in self.params:
if param in newParams:
tempParams.append(newParams[param])
else:
tempParams.append(param)
self.params = tempParams
self.isDefault = False
return self
<file_sep>class Operator():
def __init__(self, domain, name, params):
self.__name__ = name
self.params = params
domain.assertIsOp(self)
def printDebug(self, domain):
print("Operator name: {}; Number of parameters: {}; Number of preconditions: {}; Add effects: {}; Delete effects: {}.".format(name, domain.operators[name].paramsNumber,
len(domain.operators[name].preconditions), len(domain.operators[name].addEffects), len(domain.operators[name].deleteEffects)))
<file_sep>from strips import *
class PlanBuilder(object):
"""
Parses a domain and extracts a plan for a given problem.
Plan search is controlled with a set of depth parameters:
*max_depth: the maximum recursion depth per single subgoal search
*blocker_penalty_cost: priority penalty for pending operators among competing candidates.
"""
BLOCKER_PENALTY_COST = 0 #blockers are pending actions
def __init__(self, problem, priorityGroupsEnabled, max_depth, BLOCKER_PENALT_COST, verbose=0):
"""
max_depth = maximum recursion depth per single goal search
negative values evaluate to no limit.
"""
PlanBuilder.BLOCKER_PENALTY_COST = BLOCKER_PENALT_COST
self.domain = problem["domain"]
self.goals = problem["goal"]
self.initState = problem["world"]
self.state = self.initState | set()
self.predicates = {}
self.priorityGroups = {}
self.achievers = self.parsePositiveEffects(self.domain)
self.deleters = self.parseNegativeEffects(self.domain)
self.preconditions = self.parsePreconditions(self.domain)
self.blockers = set()
self.plan =[]
self.max_depth = max_depth
self.debug = verbose
self.depth = 0
self.timeGivenUp = 0
self.enablePGroups = priorityGroupsEnabled
def parsePositiveEffects(self, domain):
"""
extract every predicate's generators from the domain.
build table {unbound(pred):[unbound(op) for op in operators in op has pred as addEffect]}.
"""
actions = {}
for action in domain.operators:
for pred in domain.operators[action].addEffects:
if not pred.__name__ in actions:
actions[pred.__name__] = set()
self.predicates[pred.__name__] = self.predicates.get(pred.__name__, pred)
actions.get(pred.__name__).add(domain.operators[action].__name__)
return actions
def parseNegativeEffects(self, domain):
"""
extract actions that delete each kind of predicate.
build table {unbound(pred):[unbound(op) for op in operators in op has pred as delete effect]}.
"""
actions = {}
for action in domain.operators:
for pred in domain.operators[action].preconditions + domain.operators[action].deleteEffects:
if (not pred.__name__ in actions) and (not pred.__name__ in domain.operators[action].addEffects):
actions[pred.__name__] = set()
self.predicates[pred.__name__] = self.predicates.get(pred.__name__, pred)
actions.get(pred.__name__).add(domain.operators[action].__name__)
return actions
def parsePreconditions(self, domain):
"""
Parse an operator's preconditions
"""
actions = {}
for action in domain.operators:
if not action in actions:
actions[action] = set()
for pred in domain.operators[action].preconditions:
self.predicates[pred.__name__] = self.predicates.get(pred.__name__, pred)
actions.get(action).add(pred.__name__)
return actions
def getActionWeight(self, action, goal):
"""
Generate action priority based on current state and goal.
Used to order actions for selection when trying to achieve goal.
Weight depends on the number of the action's unachieved preconditions,
each precondition being in turn weighted according to a heuristic: self.abstractCost().
Actions already present in the list of blockers get penalized with BLOCKER_PENALTY_COST.
"""
ret = -1
if not (goal in self.state):
precond = [x.adaptParams(self.domain.stateBinding(x, self.state)) for x in self.domain.getBoundPreconditions(action, goal, self.state)]
ret = self.abstractCost(filter(lambda x : x not in self.state, precond))
if str(action) in self.blockers:
ret += PlanBuilder.BLOCKER_PENALTY_COST
return ret
def abstractCost(self, predicates):
"""
abstract cost for a list of predicates.
Current heuristic: sum of individual parameters
"""
ret = sum([len(pred.params) for pred in predicates])
return ret
def getAdders(self, pred):
"""
Get candidate adders for a predicate.
Generated from state bindings of the predicate's achievers.
returns a prioritized list of achieving operators.
"""
predKey = str(pred)
ops = sorted(self.achievers.get(pred.__name__, []), lambda x, y : self.rankBindingSource(self.domain.operators[x], self.domain.operators[y]), reverse=True)
actions = []
for op in ops:
action = self.domain.getBoundOperator(self.domain.getOperatorByName(op), pred)
mappings = {}
preconditions = self.domain.getBoundPreconditions(action, pred, self.state)
#proconditions = sorted(self.domain.getBoundPreconditions(action, pred, self.state), lambda y,x: self.rankBindingSource(x,y))
for x in preconditions:
mappings = self.domain.stateBinding(x, self.state, mappings)
action.params = self.getMappedParams(action.params, mappings)
if self.debug > 1:
print("MAPPINGS:", mappings)
actions.append(action)
if PlanBuilder.BLOCKER_PENALTY_COST <= 0:return actions
return sorted(actions, key = lambda x: self.getActionWeight(x, pred))
def test(self, mainGoalExpert, subGoalExpert):
"""
Plan tester.
A goal expert is needed to enforce subgoal ordering for goal search.
"""
goals = set(self.goals)
self.goalExpert = mainGoalExpert
'''bulkPreconditions = []
for g in goals:
ops = self.getAdders(g)
bulkPreconditions.extend(self.domain.getBoundPreconditions(ops[0], g, self.state))
for g in bulkPreconditions:
pass#self.achieve(g, set(), self.max_depth - 1)'''
while(not goals.issubset(self.state)):
tempGoals = goals# - self.state
orderedGoals = self.goalExpert.goalList(tempGoals, self)
if self.debug:print("=============\n\n\n\n\nOrdered goals: {} \n\n\n\n\n===============".format([str(t) for t in orderedGoals]))
for goal in orderedGoals:
self.achieve(goal, set(), 0)
self.goalExpert = subGoalExpert
def achieve(self, goal, residuals, depth):
"""
Plan generator for a subgoal.
"""
if goal in self.state:
if self.debug:
print(str(goal), "is true")
return True
elif not(goal.__name__ in self.achievers):
print("Predicate {} has no achieving operator. Returning.".format(goal.__name__))
return False
elif self.max_depth > 0 and depth > self.max_depth:
self.terminate("Max depth ({}) exceeded for subgoal {}.".format(self.max_depth, str(goal)))
self.markFailureState()
return False
if self.debug:
print("ACHIEVING", str(goal))
print("STATE:", [str(ff) for ff in self.state])
try:
operators = self.getAdders(goal)
except KeyError:
print("Unachievable state: {}. No defined operator produces the given state.".format(goal.__name__))
return False
for op in operators:
precond = set(self.domain.getBoundPreconditions(op, goal, self.state))
if self.debug > 1:
print("RAW ADDER:", str(op))
if goal in self.state:
return True
elif not op.paramsFullyBound():
continue
if self.debug:
print("Trying {} for {}".format(str(op), str(goal)))
if self.domain.isLegal(op, self.state):
self.state = self.perform(op)
self.plan.append(op)
if self.debug:
self.domain.printState(self.state)
elif not op in self.blockers:
if len(residuals.intersection(precond)) > 0:
continue
self.blockers.add(str(op))
residuals = self.retainedResiduals(residuals, precond)
if self.debug:
print("Preconditions: {}".format([str(o) for o in precond]))
for p in self.goalExpert.goalList(precond, self):
if not self.achieve(p, residuals, depth+1):
return False
if not goal in self.state and self.domain.isLegal(op, self.state):
self.state = self.perform(op)
self.plan.append(op)
else:
self.blockers.remove(op)
if self.debug:print("Achieving {} ends with result <{}>.".format(goal, goal in self.state))
if not (goal in self.state):
if self.debug:
print("STATE:")
self.domain.printState(self.state)
print("GOALS:")
self.domain.printState(self.goals)
print("NOT YET MET:", [str(t) for t in self.goals])
return goal in self.state
def rankBindingSource(self, par1, par2):
"""
Ranks an object (op or pred) for binding usefulness.
"""
p1 = len(par1.params)
p2 = len(par2.params)
return p1 - p2
def retainedResiduals(self, residuals, preconditions):
"""
Controls whether current preconditions should be considered as blockers for next searches.
Searches are limited by either the max depth or current residuals.
max depth greater than 1 uses no residuals.
"""
if self.max_depth > 1:
return set()
return residuals.union(preconditions) - self.state
def perform(self, op):
"""Apply action to state."""
if op in self.blockers:
self.blockers.remove(op)
return self.domain.applyAction(op, self.state)
def getMappedParams(self, retParams, mappings):
"""
Map parameters to template predicate or operator.
A template instance has params of the form $0, $1,...
Returns an instance where the template params have been replaced with state objects.
"""
for ndx in range(len(retParams)):
retParams[ndx] = mappings.get(retParams[ndx], retParams[ndx])
return retParams
def terminate(self, msg):
"""
Print debug information of current plan progress and errors.
"""
achieved = self.goals & self.state
progress = len(achieved) * 100.0/len(self.goals)
print("\n\n===============")
if progress < 100:
print("Halt at {}".format([str(o) for o in self.state]))
print("Blockers:", [str(o) for o in self.blockers])
print("PLAN PROGRESS: {} %.".format(progress))
print(msg + "\n==================")
def markFailureState(self):
if self.timeGivenUp >= 3:
self.timeGivenUp = 0
return
self.timeGivenUp += 1
def debug():
import os
pddlDir = os.path.dirname(os.path.abspath(os.path.join(os.pardir))) + "/lab/"
PATH_TO_DATA = pddlDir + "data/"
"""
Dummy goal expert: returns a list of goals without any processing.
"""
class Expert(object):
def goalList(self, goalSet, domain):
return list(goalSet)
strips = StripsRegex(0)
domainDir = "blocks"
problemFile = "probBlocks-5-1.pddl"
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
p = PlanBuilder(problem, 20)
print("Predicate generators:")
print("_________________________________")
print(p.achievers)
print("==============")
print("Predicate deleters:")
print("_________________________________")
print(p.deleters)
print("==============")
print("Action preconditions:")
print("_________________________________")
print(p.preconditions)
print("==============")
print("INITIAL STATE:")
print("_________________________________")
p.domain.printState(p.state)
print("==================")
print("==================\n\n")
p.test(Expert())
if self.debug:
p.domain.printState(p.goals)
p.domain.printState(p.state)
p.terminate("Plan length: {}.".format(len(p.plan)))
print("==================")
print("PLAN: {}".format([str(action) for action in p.plan]))
'''if __name__ == "__main__":
debug()
'''
import os
from operator import *
pddlDir = os.path.dirname(os.path.abspath(os.path.join(os.pardir))) + "/lab/"
PATH_TO_DATA = pddlDir + "data/"
"""
Dummy goal expert: returns a list of goals without any processing.
"""
class Expert(object):
def goalList(self, goalSet, domain):
return list(goalSet)
strips = StripsRegex(0)
domainDir = "blocks"
problemFile = "probBLOCKS-5-1.pddl"
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
<file_sep>from declaration import *
import copy
class Domain():
"""A PredicateRules retains all defined syntaxes and uses them to validate bindings to predicates"""
def __init__(self, name, verbose=0):
self.__name__ = name
self.NULL_OP = OperatorDeclaration("@NO-OP", [], [], [], [])
self.predicates = {}
self.operators = {"@NO-OP":self.NULL_OP}
self.VERBOSE = verbose
"""Define predicate in domain"""
def declarePredicate(self, name, params):
self.predicates[name] = PredicateDeclaration(name, params)
"""Define multiple predicates in domain"""
def declarePredicates(self, preds):
for pred in preds:
pars = pred.split()
self.declarePredicate(pars[0], pars[1:])
"""Define action in domain"""
def declareOperator(self, name, params, preconditions, addEffects, deleteEffects):
self.assertParams(params, addEffects)
self.assertParams(params, deleteEffects)
self.operators[name] = OperatorDeclaration(name, params, self.preBindParams(params, preconditions), addEffects, deleteEffects)
"""signature declaration of unbound parameters in the definition"""
def getSignatureParams(self, params):
return ["$" + param for param in params]
"""Check parameters in effects"""
def assertParams(self, params, predicates):
signatureParams = self.getSignatureParams(params)
for pred in predicates:
for param in pred.params:
if not param in signatureParams:
raise Exception("Unknown binding for parameter <{}>. Valid parameters are: {}\n".format(param.upper(), str(params)))
def getAdders(self, pred, state):
"""Get actions whose add effects has the given predicate"""
adders = self.getRawAdders(pred)
index = 0
ret = []
for rawOp in adders:
index+=1
op = self.getBoundOperator(self.operators[rawOp], pred)
if pred in op.preconditions:
continue
elif not op.paramsFullyBound():
suggestions = self.getPossibleActionBindings(op, pred, state)
if len(suggestions) >0:
op = suggestions[0]
else:
continue
if self.VERBOSE:
print('{} => {}'.format(str(op), pred))
if self.isLegal(op, state):
ret.append(op)
return ret
def getRawAdders(self, pred):
"""Get template actions whose add effects has the given predicate template"""
adders = []
for rawOp in self.operators:
if self.adds(rawOp, pred):
adders.append(rawOp)
return adders
def getOperatorByName(self, op):
"""Get an operator by name: returns a copy of the indexed operator"""
return self.operators[op].clone()
def preBindParams(self, params, predicates):
"""Check for parameter bindings in precondition"""
self.assertParams(params, predicates)
bindings = set()
req = set()
req.update(self.getSignatureParams(params))
for pred in predicates:
bindings.update(pred.params)
if req.difference(bindings):
raise Exception("Binding exception. No binding for parameter(s): {}".format(str(req.difference(bindings))))
return predicates
def bindParams(self, operator, predicates):
"""Bind parameters to arguments"""
params = operator.params
decParams = self.operators[operator.__name__].params
for pred in predicates:
if self.VERBOSE:
print("Params: ", str(pred), str(operator), pred.params, decParams)
pred.params = [params[decParams.index(param)] for param in pred.params]
return predicates
def getBindings(self, predicate, relOp, state):
args = {}
if type(predicate) == Predicate:
obj = self.predicates[predicate.__name__]
else:
obj = self.operators[predicate.__name__]
for index in range(len(obj.params)):
args[re.sub("\s*\?", "", obj.params[index])] = predicate.params[index]
return args
def stateBinding(self, arg, state, args={}):
for p in state:
if p.hasSameParams(arg):
fakePars = arg.borrowUnboundParams(p)
if p.paramsFullyBound(fakePars):
#print("Examining {} for {}".format(p, arg))
#print("TEST:", args)
for ndx in range(len(arg.params)):
key = <KEY>
if not (key in args):args[key] = fakePars[ndx]
return args
return args
def getBoundOperator(self, operator, predicate):
newOp = copy.copy(operator)
args = {}
for pred in newOp.addEffects:
if pred.isSamePred(predicate):
for index in range(len(pred.params)):
args[re.sub("\s*\?", "$", pred.params[index])] = predicate.params[index]
newOp.adaptParams(args)
return newOp
def getBoundPredicates(self, refPredicate, predicates, state=None):
return [copy.copy(p).adaptParams(self.getBindings(refPredicate, None, state)) for p in predicates]
def getBoundPreconditions(self, operator, predicate, state):
"""Returns an operator's preconditions bound with state objects."""
if isinstance(operator, str):
operator = self.operators[operator]
args={}
for ndx in range(len(operator.params)):
args["$" + str(ndx)] = operator.params[ndx]
precond = [copy.copy(p).adaptParams(args) for p in self.operators[operator.__name__].preconditions]
if self.VERBOSE:
print("_______________________BIGGINING WITH {} FOR {} ____________________".format([str(p) for p in precond], operator))
print([str(p) for p in precond])
for ndx in range(len(precond)):
p = precond[ndx]
for pp in state:
if pp.hasSameParams(p) and not p.isTemplate():
precond[ndx] = copy.copy(pp)
if self.VERBOSE:
print("=====================RETURNING {} FOR {} ===================".format([str(p) for p in precond], operator))
return precond
def adds(self, operator, predicate):
"""Check if an operator adds a predicate."""
if predicate.isTemplate():
return False
for pred in operator.addEffects:
if pred.isSamePred(operator):
return True
return False
def adds(self, operator, predicate):
"""Checks if an operator adds a predicate."""
if predicate.isTemplate():
return False
if operator in self.operators:
op = self.operators[operator]
for pred in op.addEffects:
if pred.isSamePred(predicate):
return True
return False
def allParamsBound(self, predicate):
"""Checks if all the predicate's parameters are bound to state variables."""
for param in predicate.params:
if param.startswith("$"):
return False
return True
def isTrue(self, predicate, state):
"""Checks if predicate is true in state."""
if self.allParamsBound(predicate):
return str(predicate) in [str(p) for p in state]
else:
for pred in state:
if pred.isSamePred(predicate) and pred.hasSameParams(predicate):
return True
return False
def isLegal(self, action, state):
"""Checks if all the action's preconditions are satisfied in a state."""
for pred in self.getBoundPredicates(action, action.preconditions, state):
if not self.isTrue(pred, state):
return False
return True
def applyAction(self, operator, state):
"""
Applies the operator's effect on a state.
Adds positive effects to state, and removes negative effects.
Throws exception if the action is not legal.
"""
self.assertIsOp(operator)
if self.VERBOSE:
print("Applying ", operator.__name__, operator.params)
for pred in self.getBoundPredicates(operator, [copy.copy(pred) for pred in self.operators[operator.__name__].preconditions], state):
if not self.isTrue(pred, state):
print("Exception with state: ", [str(p) for p in state])
raise Exception("Precondition error: <{}> for operator ::{}::".format(self.printPredicate(pred), str(operator)))
if self.VERBOSE:
print("DELETING ", [str(p) for p in self.getBoundPredicates(operator, self.operators[operator.__name__].deleteEffects)])
print("ADDING ", [str(p) for p in self.getBoundPredicates(operator, self.operators[operator.__name__].addEffects)])
state -= set(self.getBoundPredicates(operator, self.operators[operator.__name__].deleteEffects, state))
state |= set(self.getBoundPredicates(operator, self.operators[operator.__name__].addEffects, state))
return state
def assertIsOp(self, opp):
"""Checks if an action is defined in the current domain."""
name = opp.__name__
if name not in self.operators:
raise Exception("\n\nUndeclared operator {}.\n".format(name))
elif len(opp.params) != self.operators[name].paramsNumber:
raise Exception("\n\nIncorrect number of parameters for operator {}. Required: {}; found: {}.\n".format(name, self.operators[name].paramsNumber, len(opp.params)))
def printPredicate(self, pred):
"""Prints a string representation of the predicate."""
return "{} {}".format(pred.__name__.upper(), ' '.join(pred.params))
def debugPredicates(self):
"""Prints all predicates defined in the domain."""
for p in self.predicates:
print("PRED: ", self.printPredicate(self.predicates[p]))
def printState(self, state):
"""Print a string rep of the state"""
print("State :{}".format(str([self.printPredicate(pred) for pred in state])))
def getName(self):
"""Returns the domain's name."""
return self.__name__
<file_sep>from predicate import *
import copy, cPickle
class Declaration(object):
"""A Declaration is an instance of syntax rule defined"""
def __init__(self, name, params):
if not type(params) is list:
raise Exception("{} definition {} requires parameters as a list. Found: a {}.".format(self.__class__.__name__, name, params.__class__.__name__))
self.__name__ = name
if params != False:
self.params = ["$"+param.replace("$", "") for param in params]
self.bindings = {}
for index in range(len(self.params)):
self.bindings[self.params[index]] = "$" + str(index)
self.paramsNumber = len(params)
self.params = ["$" + str(index) for index in range(len(self.params))]
self.templateParams = copy.copy(self.params)
else:
self.paramsNumber = 0
def __hash__(self):
prime = 31
result = 101
result = int(prime * result) + self.__name__.upper().__hash__()
result = int(prime * result) + ("".join(self.params)).__hash__()
return int(result)
class PredicateDeclaration(Declaration):
def __init__(self, name, params):
super(PredicateDeclaration, self).__init__(name, params)
class OperatorDeclaration(Declaration):
def __init__(self, name, params, preconditions, addEffects, deleteEffects, bindPreds=True):
super(OperatorDeclaration, self).__init__(name, params)
self.preconditions = [self.indexedPred(pred, bindPreds) for pred in preconditions]
self.addEffects = [self.indexedPred(pred, bindPreds) for pred in addEffects]
self.deleteEffects = [self.indexedPred(pred, bindPreds) for pred in deleteEffects]
def clone(self):
"""Implements a deepcopy"""
return cPickle.loads(cPickle.dumps(self, -1))
def indexedPred(self, pred, bindPreds):
if bindPreds : pred.params = [self.bindings[param] for param in pred.params]
return pred
def __str__(self):
return "OP<{} ({})>".format(self.__name__.upper(), ','.join(self.params))
def __eq__(self, other):
"""
Checks if two predicates are equal.
This would normally return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__),
but the string rep of the predicate is instead used as a relaxed shortcut to its properties.
"""
return (isinstance(other, self.__class__)) and self.__str__() == other.__str__()
def __ne__(self, other):
return not self.__eq__(other)
def paramsFullyBound(self):
"""Return true if all arguments are bound or empty."""
for param in self.params:
if param.startswith("$"):
return False
return True
def adaptParams(self, newParams):
"""Readapts parameters from a mapping of replacement parameters."""
tempParams = []
for param in self.params:
if param in newParams:
tempParams.append(newParams[param])
else:
tempParams.append(param)
self.params = tempParams
def getPreconditions(self):
"""Returns this operator's preconditions."""
return self.getInstantiatedParams(self.preconditions)
def getAddEffects(self):
"""Returns this operator's add effects."""
return self.getInstantiatedParams(self.addEffects)
def getDeleteEffects(self):
"""Returns this operator's delete effects."""
#adds = set(self.addEffects)
#requires = set(self.preconditions)
#deletes = set(self.deleteEffects).union(requires - adds)
return self.getInstantiatedParams(self.deleteEffects)
def getInstantiatedParams(self, templates):
"""Returns a copy of the template parameters instantiated with the operator's state parameters."""
mappings = {}
for idx in range(len(self.templateParams)):
mappings[self.templateParams[idx]] = self.params[idx]
ret = copy.copy(templates)
for op in ret:
op.adaptParams(mappings)
return ret
def deletes(self, predicate):
return predicate in self.getDeleteEffects()
def blocks(self, other):
critical = other.getPreconditions()
for pred in critical:
if self.deletes(pred):
return True
return False
def cancels(self, other):
critical = other.getAddEffects()
for pred in critical:
if self.deletes(pred):
return True
return False
def adds(self, predicate, domain):
boundEffects = domain.getBoundPredicates(self, self.addEffects)
return (predicate in boundEffects)
<file_sep>import os, sys, copy, time, cPickle
wDir = os.path.dirname(os.path.abspath(os.path.join(os.pardir)))
libDir = "{}{}{}{}{}".format(wDir, os.sep, "lib", os.sep, "strips")
sys.path.append(libDir)
PATH_TO_DATA = wDir + "/lab/data/"
DEBUG = False
def debugPrint(*strs):
if DEBUG:
print(strs)
class Params():pass
class Plan():pass
def plan(params, primaryGoalsExpert, subGoalsExpert):
domainDir = params.domainDir
problemFile = params.problemFile
global DEBUG
DEBUG = params.planDebug
searchDepth = params.searchDepth
planDebug = params.planDebug
blockPenaltyCost = params.blockPenaltyCost
priorityGroupsEnabled = params.priorityGroupsEnabled
import strips, planbuilder as planbuilder
strips = strips.StripsRegex(params.verbosity)
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
p = planbuilder.PlanBuilder(problem, priorityGroupsEnabled, searchDepth, blockPenaltyCost, planDebug)
debugPrint("Predicate generators:")
debugPrint("_________________________________")
debugPrint(p.achievers)
debugPrint("==============")
debugPrint("Predicate deleters:")
debugPrint("_________________________________")
debugPrint(p.deleters)
debugPrint("==============")
debugPrint("Action preconditions:")
debugPrint("_________________________________")
debugPrint(p.preconditions)
debugPrint("==============")
debugPrint("INITIAL STATE:")
debugPrint("_________________________________")
p.domain.printState(p.state)
debugPrint("==================")
debugPrint("GOALS:")
debugPrint("_________________________________")
p.domain.printState(p.goals)
debugPrint("==================")
debugPrint("==================\n\n")
p.test(primaryGoalsExpert, subGoalsExpert, 0)
p.domain.printState(p.goals)
p.domain.printState(p.state)
p.terminate("Plan length: {}.".format(len(p.plan)))
debugPrint("==================")
debugPrint("PLAN: {}".format([str(action) for action in p.plan]))
return p.plan
def getPlanBuilder(params, expert):
domainDir = params.domainDir
problemFile = params.problemFile
DEBUG = params.planDebug
searchDepth = params.searchDepth
planDebug = params.planDebug
blockPenaltyCost = params.blockPenaltyCost
priorityGroupsEnabled = params.priorityGroupsEnabled
import strips, planbuilder as planbuilder
strips = strips.StripsRegex(params.verbosity)
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
p = planbuilder.PlanBuilder(problem, priorityGroupsEnabled, searchDepth, blockPenaltyCost, planDebug)
return p
def applyPlan(params, planObj, priorityGroups = {}):
def isNotDefault(pred):
return not pred.isDefault
domainDir = params.domainDir
problemFile = params.problemFile
plan = planObj.operators
global DEBUG
DEBUG = params.planDebug
searchDepth = params.searchDepth
planDebug = params.planDebug
blockPenaltyCost = params.blockPenaltyCost
priorityGroupsEnabled = params.priorityGroupsEnabled
import strips, planbuilder as planbuilder
strips = strips.StripsRegex(params.verbosity)
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
p = planbuilder.PlanBuilder(problem, priorityGroupsEnabled, searchDepth, blockPenaltyCost, planDebug)
if DEBUG:
debugPrint("==================\n\n")
debugPrint("Initial State:")
domain.printState(p.state)
debugPrint("==================")
debugPrint("Goals:")
p.domain.printState(p.goals)
debugPrint("==================")
curAchieved = set(filter(isNotDefault, p.state)).intersection(p.goals)
undoCount = 0
for op in plan:
p.domain.applyAction(op, p.state)
achieved = set(filter(isNotDefault, p.state)).intersection(p.goals)
lastDestroyed = curAchieved - achieved
lastAchieved = achieved - curAchieved
curAchieved = achieved
if len(lastAchieved) > 0:
if DEBUG:
debugPrint("Achieve {}".format([str(pred) + " :: " + str(priorityGroups.get(str(pred), -11111)) for pred in lastAchieved]))
if len(lastDestroyed) > 0:
undoCount+=1
if DEBUG:
debugPrint("UNDO {}".format([str(pred) for pred in lastDestroyed]))
if DEBUG:
debugPrint("Final State:")
domain.printState(p.state)
debugPrint("All goals achieved? {}".format(p.goals.issubset(p.state)))
debugPrint("Destroyed ", undoCount)
#print("PLAN: {}".format([str(p) for p in plan]))
print("Length: {}, time plan is available: {}, goal destructions: {}".format(len(plan), round(planObj.runtime, 2), undoCount))
def generatePlans(params, primaryGoalsExpert, subGoalsExpert, numPlans = 3):
domainDir = params.domainDir
problemFile = params.problemFile
absTime = time.time()
global DEBUG
DEBUG = params.planDebug
searchDepth = params.searchDepth
planDebug = params.planDebug
blockPenaltyCost = params.blockPenaltyCost
priorityGroupsEnabled = params.priorityGroupsEnabled
import strips, planbuilder as planbuilder
strips = strips.StripsRegex(params.verbosity)
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
problem = strips.parseProblem(domain, PATH_TO_DATA + domainDir + "/" + problemFile)
p = planbuilder.PlanBuilder(problem, priorityGroupsEnabled, searchDepth, blockPenaltyCost, planDebug)
plans = []
debugPrint("Predicate generators:")
debugPrint("_________________________________")
debugPrint(p.achievers)
debugPrint("==============")
debugPrint("Predicate deleters:")
debugPrint("_________________________________")
debugPrint(p.deleters)
debugPrint("==============")
debugPrint("Action preconditions:")
debugPrint("_________________________________")
debugPrint(p.preconditions)
debugPrint("==============")
debugPrint("INITIAL STATE:")
debugPrint("_________________________________")
p.domain.printState(p.state)
debugPrint("==================")
debugPrint("GOALS:")
debugPrint("_________________________________")
p.domain.printState(p.goals)
debugPrint("==================")
debugPrint("==================\n\n")
startNdx = 0
lastPlanLen = 0
for i in range(numPlans):
p.depth = int((i+0.5)*2)
p.test(primaryGoalsExpert, subGoalsExpert)
p.domain.printState(p.goals)
p.domain.printState(p.state)
newGoals = p.goals | (p.state - p.initState)
p.terminate("Plan length: {}.".format(len(p.plan)))
debugPrint("==================")
debugPrint("==================")
debugPrint("GOALS: ", [str(g) for g in p.goals])
debugPrint("PLAN (index {}, length: {}; \ninitState: {}; goals: {}; finalState: {}; addedGoals ({}): {})"
.format(i+1, len(p.plan), len(p.initState), len(p.goals), len(p.state), len(newGoals - p.goals), [str(g) for g in newGoals - p.goals]))
debugPrint("=====================================================\n===============================\n")
planObj = Plan()
curTime = time.time()
planObj.runtime = curTime - absTime
#absTime = time.time()
planObj.operators = p.plan
plans.append(planObj)
lastPlan = p.plan
p.goals = newGoals
p.state = cPickle.loads(cPickle.dumps(p.initState, -1))
p.plan = []
return (p.priorityGroups, plans)
def domain(params):
domainDir = params.domainDir
problemFile = params.problemFile
global DEBUG
DEBUG = params.planDebug
searchDepth = params.searchDepth
planDebug = params.planDebug
blockPenaltyCost = params.blockPenaltyCost
import strips, planbuilder as planbuilder
strips = strips.StripsRegex(params.verbosity)
domain = strips.createDomain(PATH_TO_DATA + domainDir + "/domain.pddl")
return domain
<file_sep>import re
from domain import *
predSyntax = "((\s+(?P<predicate>\([^\)\(]+\))|(?P<negPredicate>\(not\s+\([^\)\(]+?\)\)))+?)"
predDef = "(\s+(?P<predicate>\([^\)\(]+\))|(?P<negPredicate>\(not\s+\([^\)\(]+?\)\)))"
predReSyntax = "((\s+((?P=predicate)|(?P=negPredicate)))+?)"
class StripsRegex:
"""
Regular expressions for STRIPS parsing.
Extracts domain specification from a pddl file;
extracts problem definition from a pddl file.
REQUIREMENT:
*groups of predicates are presented as CONJUNCTIONS.
*They thus require to be grouped in an AND() group.
*That is correct, at least considering [A,B...] vs <AND A B...>, and [A] as <AND A>.
TODO:
*Eliminate the necessity to represent a single element as a one-item conjunction.
"""
predicatess = re.compile("(\(\w+(\s+\w+)?\))+", re.IGNORECASE | re.DOTALL)
DOMAINDEF = re.compile("\(define(\s)+\(domain(\s+)(?P<domain>\w+)+\)", re.IGNORECASE | re.DOTALL)
PROBLEMDEF = re.compile("\(define(\s)+\(problem(\s+)(?P<problem>[\w\-_]+)+\)", re.IGNORECASE | re.DOTALL)
DOMAINDECL = re.compile("\(:domain(\s+)(?P<domain>\w+)+\)", re.IGNORECASE | re.DOTALL)
OBJECTS = re.compile("\(:objects(?P<objects>(?P<object>\s+\w+)+)\)", re.IGNORECASE | re.DOTALL)
PREDICATES = re.compile("\(:predicates{}\s*\)".format(predSyntax), re.IGNORECASE | re.DOTALL)
PARAMETERS = ":parameters\s+(?P<PARAMS>\((\s*\?(?P<param>\w+))+\))"
EMPTY_PARAMETERS = ":parameters\s+(?P<PARAMS>\(\s*\))"
ATOM = "((\(not\s*)?(?P<ATOM>\((?P<ref>[\w\-_]+)(\s+\?(?P<binding>\w+))*\s*\))\s*\)?)"
CONCRETE_ATOM = "((\(not\s+)?(?P<ATOM>\((?P<ref>[\w\-_]+)(\s+(?P<binding>\w+))*\s*\))\s*\)?)"
PREDSYNTAX = "(\s+(?P<predicate>{}+)\s*)".format(ATOM)
CONCRETE_PREDSYNTAX = "(\s+(?P<predicate>{}+)\s*)".format(CONCRETE_ATOM)
CONJUNCTION = "\s+(\(\s*and{}+\))".format(PREDSYNTAX)
CONCRETE_CONJUNCTION = "\s+(\(\s*and{}+\))".format(CONCRETE_PREDSYNTAX)
DISJUNCTION = "\s+\(\s*or{}\)".format(PREDSYNTAX)
PRECONDITION = ":precondition{}".format(CONJUNCTION)
EMPTY_PRECONDITION = ":precondition\s+\(\s*\)"
EFFECTS = re.compile(":effect{}".format(CONJUNCTION), re.IGNORECASE | re.DOTALL)
INIT = re.compile("(\(\:init.+?(?=\(\:goal))|(\(\:goal.+?\)$)", re.IGNORECASE | re.DOTALL)
GOAL = re.compile(":goal{}".format(CONCRETE_CONJUNCTION), re.IGNORECASE | re.DOTALL)
ACTIONHEADER = re.compile("\(:action\s+(?P<op_name>[\w\-_]+)", re.IGNORECASE | re.DOTALL)
def __init__(self, verbose=0):
self.context = None
self.domain = None
self.problem = None
self.VERBOSE = verbose
def createDomain(self, filename):
"""Extracts domain from a pddl file."""
fileH = open(filename, 'r')
content = re.sub("\\n|\\t", " ", fileH.read())
content = content[:content.rfind(')')] + ")"
name = self.extractDomainDef(content)
domain = Domain(name, self.VERBOSE)
predicates = self.extractPredicates(content)
domain.declarePredicates([self.atomize(pred) for pred in predicates])
#domain.debugPredicates()
operators = self.extractOperators(content)
for op in operators:
opHeader = op["op"]
precondPreds = op["preconditions"]
preconditions = [Predicate(domain, self.atomize(pred)) for pred in precondPreds["POSITIVES"]]
effectPreds = op["effects"]
addEffects = [Predicate(domain, self.atomize(pred)) for pred in effectPreds["POSITIVES"]]
deleteEffects = [Predicate(domain, self.atomize(pred)) for pred in effectPreds["NEGATIVES"]]
domain.declareOperator(opHeader[0], opHeader[1:], preconditions, addEffects, deleteEffects)
if self.VERBOSE:
print("Operators: ", operators)
fileH.close()
return domain
def parseProblem(self, domain, filename):
"""Extracts planning problem from a pddl file."""
fileH = open(filename, 'r')
content = re.sub("\\n|\\t", " ", fileH.read())
name = self.extractProblemDef(content)
domName = self.extractDomainDecl(content)
assert domName == domain.getName()
initPreds = self.extractAtoms(StripsRegex.INIT, content, "INITIAL STATE")
if self.VERBOSE:
print("Initial State: ", initPreds)
goalPreds = self.extractAtoms(StripsRegex.GOAL, content, "GOAL STATE")
if self.VERBOSE:
print("Goal: ", goalPreds)
problem = {}
problem["name"] = name
problem["domain"] = domain
problem["world"] = set([Predicate(domain, self.atomize(pred)) for pred in initPreds["POSITIVES"]])
problem["goal"] = set([Predicate(domain, self.atomize(pred)) for pred in goalPreds["POSITIVES"]])
fileH.close()
return problem
def extractName(self, refKey, M):
name = "####"
if M:
name = M.group(refKey)
else:
raise Exception("{} name not found.".format(refKey.capitalize()))
if self.VERBOSE:
print("{} name: {}".format(refKey.capitalize(), name))
return name
def extractDomainDecl(self, text):
"""Extracts a domain's declaration."""
M = re.search(StripsRegex.DOMAINDECL, text)
return self.extractName("domain", M)
def extractDomainDef(self, text):
"""Extracts a domain specification."""
M = re.search(StripsRegex.DOMAINDEF, text)
return self.extractName("domain", M)
def extractProblemDef(self, text):
"""Extracts a problem definition from text."""
M = re.search(StripsRegex.PROBLEMDEF, text)
return self.extractName("problem", M)
def extractPredicates(self, text):
"""Extract domain predicates from text."""
M = re.search(StripsRegex.PREDICATES, text)
if not M:
raise Exception("No predicates")
return [predicate.group("predicate") for predicate in re.finditer(predSyntax, M.group())]
def extractOperators(self, text):
"""Extracts domain operator sections from domain pddl text."""
actions = [op.group() for op in re.finditer(re.compile("(\(\:action.+?(?=\(\:action))|(\(\:action.+?\)$)", re.IGNORECASE | re.DOTALL), text)]
ret = []
for action in actions:
operator = {}
operator["op"] = self.extractOpHeader(action)
try:
operator["preconditions"] = self.extractBindings(StripsRegex.PRECONDITION, action)
except:
operator["preconditions"] = self.extractBindings(StripsRegex.EMPTY_PRECONDITION, action)
operator["effects"] = self.extractBindings(StripsRegex.EFFECTS, action)
ret.append(operator)
return ret
def extractOpHeader(self, action):
"""Extracts operator's header : name and params."""
OP = re.search(StripsRegex.ACTIONHEADER, action)
assert OP is not False
ret = [OP.group("op_name")]
PARAMS = re.search(StripsRegex.PARAMETERS, action)
if PARAMS == None:
PARAMS = re.search(StripsRegex.EMPTY_PARAMETERS, action)
bindings = re.findall("\?\w+", PARAMS.group("PARAMS"))
params = [param.replace("?", "") for param in bindings]
ret.extend(params)
return ret
def extractBindings(self, reg, body):
"""
Extracts an operator's effects from the operator's section text.
Returns a tuple : (addEffects, deleteEffects) as extracted from the action's effects.
TODO:
*delete effects should also be searched among predicates present in the preconditions but not in the add effects.
*that will be in accordance with the closed world assumption.
"""
ret = {}
OP = re.search(reg, body)
#print(body)
assert OP is not False
positives = [predicate.group("predicate") for predicate in re.finditer(predSyntax, OP.group())]
negatives = [predicate.group("negPredicate") for predicate in re.finditer(predSyntax, OP.group())]
ret["POSITIVES"] = [predicate for predicate in positives if predicate is not None]
ret["NEGATIVES"] = [predicate for predicate in negatives if predicate is not None]
return ret
def extractAtoms(self, reg, text, refKey):
atoms = self.extractBindings(reg, text)
if not atoms:
raise Exception("No predicates for {}".format(refKey))
return atoms
def atomize(self, predString):
ret = re.sub("((\(\s*not\s+)?\(\s*|(\)))", "", predString)
return ret<file_sep>import planner, expert, cProfile, pstats
DEBUG = False
def debugPrint(*strS):
if DEBUG:
print(strS)
params = planner.Params()
params.domainDir = "blocks"
params.problemFile = "probBLOCKS-10-2.pddl"
params.verbosity = 0
params.planDebug = 0
params.searchDepth = 100
params.blockPenaltyCost = 10
params.priorityGroupsEnabled = True
params.cachePredicates = True
priorityGoalExpert = expert.PriorityGoalOrderExpert()
HybridPriorityGoalExpert = expert.PriorityGoalOrderExpert(True)
blocksExpert = expert.BlockStackingExpert()
def runMe():
prioPlan = []#planner.plan(params, priorityGoalExpert, priorityGoalExpert)
prioPlanH = planner.plan(params, HybridPriorityGoalExpert, HybridPriorityGoalExpert)
planB = []#planner.plan(params, blocksExpert, blocksExpert)
def testPlanner():
priorityGroups, plans = planner.generatePlans(params, HybridPriorityGoalExpert, HybridPriorityGoalExpert, 5)
for plan in plans:
debugPrint("PLAN ({}) : {}\n===\n".format(len(plan.operators), [str(pred) for pred in plan.operators]))
minPlan = 0
minLen = len(plans[0].operators)
for i in range(len(plans)):
planner.applyPlan(params, plans[i], priorityGroups)
if len(plans[i].operators) < minLen:
minLen = len(plans[i].operators)
minPlan = i
#params.planDebug = 1
#planner.applyPlan(params, plans[minPlan], priorityGroups)
#print("PLAN: {}".format([str(p) for p in plans[minPlan].operators]))
testPlanner()
#cProfile.run('testPlanner()', sort='cumulative')
"""aa = [1,2,3,4,5,6]
expp = expert.PriorityLinksExpert(True)
for a in aa:
expp.appendNode(expert.PriorityLinksExpert.Node(a))
print([v.val for v in expp.nodesList()])
for node in expp.nodesList():
if node.val == 1:
f = node
elif node.val == 4:
l = node
node = node.nextNode
expp.moveAfter(l, f)
print([v.val for v in expp.nodesList()])
for node in expp.nodesList():
if node.val == 4:
f = node
elif node.val == 2:
l = node
node = node.nextNode
expp.moveAfter(l, f)
print([v.val for v in expp.nodesList()])"""
<file_sep>class Operator():
def __init__(self, domain, name, params):
self.__name__ = name
self.params = params
if name not in domain.operators:
raise Exception("\n\nUndeclared operator {}.\n".format(name))
elif len(params) != domain.operators[name].paramsNumber:
raise Exception("\n\nIncorrect number of parameters for operator {}. Required: {}; found: {}.\n".format(name, domain.operators[name].paramsNumber, len(params)))
#print("Operator name: {}; Number of parameters: {}; Number of preconditions: {}; Add effects: {}; Delete effects{}.".format(name, domain.operators[name].paramsNumber,
#len(domain.operators[name].preconditions), len(domain.operators[name].addEffects), len(domain.operators[name].deleteEffects)))<file_sep>planbuilder
===========
ABOUT:
------
This is a simple linear planner built in python.
The planner uses a goal order expert to order subgoals based on conflicts between them.
This avoids goal destruction and shortens plans.
It uses a limited depth-first search to search for achieving operators. The depth has a regulating parameter (set in test.py)
STRUCTURE
---------
1. lib/
contains the implementation of a PDDL parser and a plan builder
2. lab/
code/ : contains the goal order expert and test.py, the entry point
data/ : contains test data (domains and problems)
HOW TO USE IT
-------------
The entry point for the planner is in lab/code/test.py, where the domain and test problem must be specified.
Test problems must be expressed in PDDL.
Based on the default goal order expert, different goal ordering strategies may be implemented and used instead of the default one.
<file_sep>from ctypes import *
DEBUG = False
def debugPrint(str):
if DEBUG:
print(str)
class BlockStackingExpert(object):
"""Naive goal order expert for blocks world"""
PRIORITIES = {'clear':0, 'holding':2, 'ontable':3, 'on':-4, 'handempty':5}
def __init__(self):
pass
def goalList(self, goalSet, domain):
return sorted(list(goalSet), key = self.ratePred)
def ratePred(self, pred):
metric = BlockStackingExpert.PRIORITIES.get(pred.__name__, 10)
return metric
def shortenPlan(self, plan):
ops = {}
for i in range(len(plan)):
op = str(plan[i])
ops[op] = i
retPlan = set(plan)
return sorted(retPlan, cmp=lambda x,y:ops[str(x)] - ops[str(y)])
class PriorityGoalOrderExpert(BlockStackingExpert):
class Group(object):
def __init__(self, level):
self.level = level
def __str__(self):
return "Level " + str(self.level)
def __init__(self, hybrid=False):
self.hybrid = hybrid
self.adders = {}
self.conflicts = {}
self.deleters = {}
def goalList(self, goalSet, planBuilder):
if self.hybrid:ret = super(PriorityGoalOrderExpert, self).goalList(goalSet, planBuilder)
else:ret = sorted(goalSet)
ret = self.updatePriorities(ret, planBuilder)
debugPrint("ORIG ORDER: for {}.".format([str(t) for t in ret]))
def priorityRank(g1, g2):
return g1.priority - g2.priority
for i in range(planBuilder.depth):
ret = self.updatePriorities(sorted(ret, lambda x,y : priorityRank(x,y)), planBuilder)
'''print("=================")
for g in ret:
print("{} : {}".format(str(g), g.priority))
print("===================")
#raise Exception("Here!")'''
return ret
def updatePriorities(self, goalsList, planBuilder):
totLen = len(goalsList)
sqTotLen = totLen * totLen
blocked = {}
for index in range(totLen):
goal = goalsList[index]
blocked[str(goal)] = []
goal.priorityGroup = py_object(PriorityGoalOrderExpert.Group(index))
if goal in planBuilder.goals:
goal.priority = (1 + index) * totLen#index
else:
goal.priority = (1 + index) * totLen
debugPrint("INCOMING PRIORITIES: {} ".format([(str(g), g.priority) for g in goalsList]))
for index in range(totLen):
goal = goalsList[index]
tAdders = self.getAdders(goal, planBuilder)
if not tAdders: break
tAdder = tAdders[0]
for other in goalsList:
if other == goal or len(other.params) == 0:
continue
adders = self.getAdders(other, planBuilder)
if not adders:break
adder = adders[0]
if self.conflictsWith(tAdder, adder):
debugPrint("{}({}) blocks {}({}) ".format(goal, goal.priority, other, other.priority))
oldPriority = other.priority
other.priority = min(goal.priority - 1, other.priority)
blocked[str(goal)].append(other)
self.conflictScan(blocked, other, oldPriority - other.priority, int(planBuilder.depth/2))
mergedGroup = self.mergeGroups(goal, other)
pointer(goal.priorityGroup).contents.value = mergedGroup
pointer(other.priorityGroup).contents.value = mergedGroup
debugPrint("PRIORITY UPDATES: {}({} :: {}) ; {}({} :: {}) ".format(goal, goal.priority, goal.priorityGroup.value.level, other, other.priority, other.priorityGroup.value.level))
if other.priority < goal.priority and tAdder.adds(other, planBuilder.domain):
other.deferred = True
other.priority = sqTotLen
return goalsList
def getAdders(self, pred, planBuilder):
if pred in self.adders:
return self.adders[pred]
adders = planBuilder.getAdders(pred)
self.adders[pred] = adders
return adders
def conflictsWith(self, curAction, otherAction):
deleters = self.deleters.get(otherAction, set())
if curAction in deleters:
return True
if not(otherAction in self.conflicts):
self.conflicts[otherAction] = otherAction.getPreconditions() + otherAction.getAddEffects()
for pred in self.conflicts[otherAction]:
if curAction.deletes(pred):
deleters.add(curAction)
self.deleters[otherAction] = deleters
return True
return False
def conflictScan(self, conflictsMap, consideredGoal, priorityDelta, depth):
if depth < 0:return
for blockedGoal in conflictsMap[str(consideredGoal)]:
blockedGoal.priority -= priorityDelta
blockedGoal.priorityGroup.value.level = min(blockedGoal.priorityGroup.value.level, blockedGoal.priority)
self.conflictScan(conflictsMap, blockedGoal, priorityDelta, depth-1)
def mergeGroups(self, goal, other):
group1 = goal.priorityGroup.value
group2 = other.priorityGroup.value
if group1.level < group2.level:
return group1
return group2
class PriorityLinksExpert(PriorityGoalOrderExpert):
class Node(object):
def __init__(self, action):
self.val = action
self.prevNode = None
self.nextNode = None
def __init__(self, hybrid=False):
super(PriorityLinksExpert, self).__init__(hybrid)
self.heads = []
def goalList(self, goalSet, planBuilder):
for goal in goalSet:
self.appendNode(PriorityLinksExpert.Node(goal))
self.updatePriorities(planBuilder)
print("GOAL SET: {}".format([str(G) for G in goalSet]))
print("-------------")
print("GOALLLLLLLLLLLLLLLLS: {}".format([str(node.val) for node in self.nodesList()]))
print("-------------")
return [node.val for node in self.nodesList()]
def updatePriorities(self, planBuilder):
goalNodes = self.nodesList()
for i in range(0, len(goalNodes)):
goalNode = goalNodes[i]
goal = goalNode.val
tAdders = self.getAdders(goal, planBuilder)
if not tAdders: break
tAdder = tAdders[0]
for j in range(i+1, len(goalNodes)):
otherNode = goalNodes[j]
other = otherNode.val
if otherNode == goalNode or len(other.params) == 0:
continue
adders = self.getAdders(other, planBuilder)
if not adders:break
adder = adders[0]
if self.conflictsWith(tAdder, adder):
debugPrint("{}({}) blocks {}({}) ".format(goal, goal.priority, other, other.priority))
self.moveAfter(otherNode, goalNode)
def moveAfter(self, curNode, toMove):
if curNode.nextNode != None:
return#raise Exception("curNode's next must be NULL!")
elif not (toMove in self.heads and toMove in self.heads):
return
self.heads.remove(toMove)
curNode.nextNode = toMove
def appendNode(self, node):
if node in self.heads:
return
self.heads.append(node)
def nodesList(self):
ret = []
for head in self.heads:
node = head
while node != None:
ret.append(node)
node = node.nextNode
return ret | 2c430929a9d5b3f0237ae207dd456df6d15c2a8a | [
"Markdown",
"Python"
]
| 12 | Python | butshuti/planbuilder | 915a76a9167a578bd4a12809837e0fcef5105e7d | e3c3ec5861c1682291228953e73467c7b1ab7e6b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.